I am building an application that needs to display data in a GridView control, grouped by a particular value, and then export it to PDF.I used this set of classes here (http://www.agrinei.com/gridviewhelper/gridviewhelper_pt.htm) for grouping, and it works well. However, I had to set EnableViewState to false for it to work properly. The problem comes when I need to export it to PDF. Previously (before using GridViewHelper), this was working. However, it now generates an empty report (I suppose because EnableViewState is false).
How can I save the data and structure of the GridView produced through use of the GridViewHelper class in order to export it to PDF?
Some of my aspx (portions of code omitted for brevity)
public partial class all : System.Web.UI.Page
{
Int32 userID;
Int32 currentID;
protected void Page_Load(object sender, EventArgs e)
{
GridViewHelper helper = new GridViewHelper(allTicketGrid);
helper.RegisterGroup("propName", true, true);
helper.ApplyGroupSort();
userID = Convert.ToInt32(Session["userID"]);
if (Session["userLevel"] == null || Session["userLevel"] == "")
{
Response.Redirect("~/Default.aspx");
}
if (!IsPostBack)
{
this.populate();
}
}
protected void populate()
{
toDateBox.Text = DateTime.Now.ToShortDateString();
fromDateBox.Text = DateTime.Now.ToShortDateString();
using (ticketModel dbContext = new ticketModel())
{
END_USER user = dbContext.END_USER.First(u => u.END_USER_ID == userID);
itemCheckBoxList.DataSource = dbContext.ITEM_TYPE.ToList();
itemCheckBoxList.DataTextField = "DESCRIPTION";
itemCheckBoxList.DataValueField = "ITEM_TYPE_ID";
itemCheckBoxList.DataBind();
List<Int32> propIDList = new List<Int32>();
foreach(END_USER_PROPERTY item in user.END_USER_PROPERTY.ToList() ) {
propIDList.Add((Int32)item.PROPERTY_ID);
}
locationCheckBoxList.DataSource = dbContext.PROPERTies.Where(p=> propIDList.Contains(p.PROPERTY_ID)).ToList();
locationCheckBoxList.DataTextField = "SHORT_NAME";
locationCheckBoxList.DataValueField = "PROPERTY_ID";
locationCheckBoxList.DataBind();
}
}
protected void exportReport(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < allTicketGrid.Columns.Count; i++)
{
dt.Columns.Add(allTicketGrid.Columns[i].HeaderText);
}
foreach (GridViewRow rowView in allTicketGrid.Rows)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < rowView.Cells.Count; i++)
{
dr[i] = rowView.Cells[i].Text.Trim();
}
dt.Rows.Add(dr);
}
Document doc = pdfWorker.readyDocument();
pdfWorker.createTable(doc, dt);
String filePath = Server.MapPath("~/reports/files/");
String fileName = "report_" + DateTime.Now.ToString("MM-dd-yyyy") + ".pdf";
filePath += fileName;
pdfWorker.savePDF(doc, filePath);
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(filePath);
Response.End();
}
protected void generateReport(object sender, EventArgs e)
{
int[] selectedLocations = getLocations();
int[] selectedItemTypes = getItems();
DateTime from = Convert.ToDateTime(fromDateBox.Text);
DateTime to = Convert.ToDateTime(toDateBox.Text);
if (!allButton.Checked)
{
Int32 statusID;
if (openButton.Checked)
{
statusID = 1;
}
else
{
statusID = 2;
}
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => t.STATUS_TYPE.STATUS_TYPE_ID == statusID && selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
else
{
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
}
and my pdfWorker class:
static class pdfWorker
{
public static Document readyDocument() {
Document doc = new Document();
Section section = doc.AddSection();
Style docStyles = doc.Styles["Normal"];
docStyles.Document.DefaultPageSetup.Orientation = MigraDoc.DocumentObjectModel.Orientation.Landscape;
docStyles.Font.Size = 8;
docStyles.ParagraphFormat.FirstLineIndent = 0;
return doc;
}
public static void createTable(Document document, DataTable dataTable)
{
Table table = new Table();
table.Format.Font.Size = 6;
table.BottomPadding = 10;
int colCount = dataTable.Columns.Count;
Row pdfRow;
Cell pdfCell;
for (int i = 0; i < colCount; i++)
{
table.AddColumn();
}
pdfRow = table.AddRow();
for (int i = 0; i < colCount; i++)
{
pdfCell = pdfRow.Cells[i];
pdfCell.Row.Format.Font.Size = 10;
pdfCell.AddParagraph(dataTable.Columns[i].ToString());
}
foreach (DataRow row in dataTable.Rows)
{
pdfRow = table.AddRow();
pdfRow.HeightRule = RowHeightRule.AtLeast;
for (int i = 0; i < colCount; i++)
{
pdfCell = pdfRow.Cells[i];
pdfCell.AddParagraph(row[i].ToString());
}
}
document.LastSection.Add(table);
}
public static void savePDF(Document doc, String fileName) {
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
SaveFileDialog saveDialog = new SaveFileDialog();
renderer.Document = doc;
renderer.RenderDocument();
renderer.PdfDocument.Save(fileName);
}
}
}
Thanks so much for any help.
You can put the code that populates the GridView in a separate method:
protected void generateReport(object sender, EventArgs e)
{
BindReportData();
}
private void BindReportData()
{
int[] selectedLocations = getLocations();
int[] selectedItemTypes = getItems();
DateTime from = Convert.ToDateTime(fromDateBox.Text);
DateTime to = Convert.ToDateTime(toDateBox.Text);
if (!allButton.Checked)
{
Int32 statusID;
if (openButton.Checked)
{
statusID = 1;
}
else
{
statusID = 2;
}
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => t.STATUS_TYPE.STATUS_TYPE_ID == statusID && selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
else
{
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
}
And call that method at the start of exportReport:
protected void exportReport(object sender, EventArgs e)
{
BindReportData();
...
}
Related
I have a ListView in my Form.
I want to delete a row, but when I select one and delete it, later it comes back and I can't delete from the List where data comes from.
Why is that?
Pontszam pt = new Pontszam();
List<int> pontszamook = new List<int>();
List<string> nevek = new List<string>();
List<string> idk = new List<string>();
List<string> ptList = new List<string>();
int osszSor = 0;
public int sorokSzama()
{
osszSor = pt.select().Count;
return osszSor;
}
private void Ponttablazat_Load(object sender, EventArgs e)
{
osszSor = sorokSzama();
ptList = pt.select();
listScore.Items.Clear();
for (int i = 0; i < osszSor; i++)
{
string[] adatok = ptList[i].Split(';');
idk.Add(adatok[0]);
nevek.Add(adatok[1]);
pontszamook.Add(Convert.ToInt32(adatok[2]));
var row = new string[] { nevek[i], Convert.ToString(pontszamook[i]) };
ListViewItem lvi = new ListViewItem(idk[i]);
lvi.SubItems.AddRange(row);
listScore.Items.Add(lvi);
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (listScore.SelectedItems != null)
{
for (int i = listScore.SelectedItems.Count - 1; i >= 0; i--)
{
ListViewItem itm = listScore.SelectedItems[i];
int indeX = itm.Index;
listScore.Items[itm.Index].Remove();
ptList[indeX] = null;
idk[indeX] = null;
nevek[indeX] = null;
pontszamook[indeX] = -1;
pt.deletetRow(itm.Index);
}
}
}
private void btnDelete_Click(object sender, EventArgs e) { if (listScore.SelectedItems != null) { for (int i = listScore.SelectedItems.Count - 1; i >= 0; i--) { ListViewItem itm = listScore.SelectedItems[i]; int indeX = itm.Index; listScore.Items[itm.Index].Remove(); ptList[indeX] = null; idk[indeX] = null; nevek[indeX] = null; pontszamook[indeX] = -1; pt.deletetRow(itm.Index); } } }
Im having a problem when i try to filter my gridview trough combobox basicly when i click on the button "Procurar" the grid doesnt update but the row im in just switch. i will explain with the images
then when i choose a different Category "Categoria" it does this
Basicically it overwrote my original row with the new one that as the Categoria "Vegan".
here is the code:
private void btnSearch_Click(object sender, EventArgs e) {
string receitas = #"receitas.txt";
if (File.Exists(receitas)) {
StreamReader sr2 = File.OpenText(receitas);
string linha2 = "";
int x = 0;
while ((linha2 = sr2.ReadLine()) != null) {
string[] campos2 = linha2.Split(';');
if (comboBoxCategorias.SelectedItem.ToString() == campos2[2]) {
if ((txtTitulo.Text == "") || (txtIngredientes.Text == "")) {
dataGridReceitas[0, x].Value = campos2[0];
dataGridReceitas[1, x].Value = campos2[1];
dataGridReceitas[2, x].Value = campos2[2];
dataGridReceitas[3, x].Value = campos2[3];
x++;
}
}
}
sr2.Close();
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
dataGridReceitas.Rows.Clear();
string receitas = #"receitas.txt";
if (File.Exists(receitas))
{
StreamReader sr2 = File.OpenText(receitas);
string linha2 = "";
int x = 0;
while ((linha2 = sr2.ReadLine()) != null)
{
string[] campos2 = linha2.Split(';');
if(comboBoxCategorias.SelectedItem.ToString() == campos2[2])
{
if((txtTitulo.Text == "") || (txtIngredientes.Text == ""))
{
dataGridReceitas.Rows.Add(1);
dataGridReceitas[0, x].Value = campos2[0];
dataGridReceitas[1, x].Value = campos2[1];
dataGridReceitas[2, x].Value = campos2[2];
dataGridReceitas[3, x].Value = campos2[3];
x++;
}
}
}
sr2.Close();
}
}
the solution was adding the code dataGridReceitas.Rows.Clear(); to clear the grid and just appearing the rows i wanted also adding the DataGridReceitas.Rows.Add(1) so when the search result is bigger than 1 the aplication dont crash
First, I import a csv file to the datagridview and changed it to the format that I want.
I'm able to filter out the data that i do not want by clicking a button, i get the data i want in the console by using console.writeline. (just for testing so i can see what's actually happen). There are quite numbers of column that do not content the data i want for calculation, so i use .contains() and .replace to filter it out.
Now, i want to store the cell.value.toString() which hold the value to an array but i have no idea how to implant array to it.
Here is the code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test2
{
public partial class Form1 : Form
{
OpenFileDialog openFile = new OpenFileDialog();
public int colC { get; private set; }
public Form1()
{
InitializeComponent();
}
public void Button1_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() == DialogResult.OK)
{
List<string[]> rows = File.ReadLines(openFile.FileName).Select(x => x.Split(',')).ToList();
DataTable dt = new DataTable();
List<string> headerNames = rows[0].ToList();
foreach (var headers in rows[0])
{
dt.Columns.Add(headers);
}
foreach (var x in rows.Skip(1).OrderBy(r => r.First()))
{
if (x[0] == "Lot ID") //linq to check if 2 lists are have the same elements (perfect for strings)
continue; //skip the row with repeated headers
if (x.All(val => string.IsNullOrWhiteSpace(val))) //if all columns of the row are whitespace / empty, skip this row
continue;
dt.Rows.Add(x);
}
dataGridView1.DataSource = dt;
dataGridView1.ReadOnly = true;
// dataGridView1.Columns["Lot ID"].ReadOnly = true;
//dataGridView1.Columns[" Magazine ID"].ReadOnly = true;
//dataGridView1.Columns["Frame ID"].ReadOnly = true;
}
}
public void Form1_Load_1(object sender, EventArgs e)
{
openFile.Filter = "CSV|*.csv";
}
public void Button2_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "txt files (*.txt)|*.txt|Csv files (*.csv)|*.csv";
sfd.FilterIndex = 2;
if (sfd.ShowDialog() == DialogResult.OK)
{
try
{
StreamWriter sw = new StreamWriter(sfd.FileName, false);
{
string columnHeaderText = "";
int countColumn = dataGridView1.ColumnCount - 1;
if (countColumn >= 0)
{
columnHeaderText = dataGridView1.Columns[0].HeaderText;
}
for (int i = 1; i <= countColumn; i++)
{
columnHeaderText = columnHeaderText + ',' + dataGridView1.Columns[i].HeaderText;
}
sw.WriteLine(columnHeaderText);
foreach (DataGridViewRow dataRowObject in dataGridView1.Rows)
{
if (!dataRowObject.IsNewRow)
{
string dataFromGrid = "";
dataFromGrid = dataRowObject.Cells[0].Value.ToString();
for (int i = 1; i <= countColumn; i++)
{
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
}
sw.WriteLine(dataFromGrid);
}
}
sw.Flush();
sw.Close();
}
}
catch (Exception exceptionObject)
{
MessageBox.Show(exceptionObject.ToString());
}
}
}
public void Button3_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
//prevent error occur coz , only execute the not null line
if(cell.Value != null)
{
string cellV = cell.Value.ToString();
//do operations with cell, filter out the unnecessary data
if (!cellV.Contains("="))
{
continue;
}
else if (cellV.Contains("P = "))
{
cellV = cellV.Replace("P = ", "");
}
else if (cellV.Contains("F = n/a"))
{
cellV =cellV.Replace("F = n/a", "0");
}
else if (cellV.Contains("F = "))
{
cellV = cellV.Replace("F = ", "");
}
Console.WriteLine(cellV + "\n");
}
}
}
}
}
}
Please have a look in the last method and the Picture.
Here is the output.
I skip all the data which is not related to calculation by using continue
How do i store the data that i filtered out in array???
Please do not hesitate to ask if you have any inquiry about the question.
I hope that this may help. First and more important, is that when you loop through a DataGridView that has a DataSource, it is better to do modifications/additions, etc… through the DataSource instead of the grid. In this example it will make no difference, however, the code below loops through the DataSource (the DataTable) and not the grid.
Below is a revised button 3 click that will convert the strings that contain equal “=” signs to decimal values. If the string that contains an equal “=” character and does not have a valid decimal number after the equal sign… zero (0) is returned. A helper method is used to take the string “P = XX.xx” and returns a valid decimal number or zero (0) if the number is invalid. Hope this makes sense.
private void button3_Click(object sender, EventArgs e) {
decimal decimalNumber = 0.0m;
foreach (DataRow row in dt.Rows) {
for (int i = 0; i < dt.Columns.Count; i++) {
if (row.ItemArray[i] != null) {
if (row.ItemArray[i].ToString().Contains("=")) {
decimalNumber = GetDecimalFromEquation(row.ItemArray[i].ToString());
textBox1.Text += decimalNumber.ToString() + Environment.NewLine;
}
}
}
textBox1.Text += Environment.NewLine;
}
}
private decimal GetDecimalFromEquation(string numberString) {
decimal parsedValue = 0.0m;
if (numberString.Contains("=")) {
numberString = numberString.Replace(" ", "");
string[] splitArray = numberString.Split('=');
if (splitArray.Length >= 2) {
decimal.TryParse(splitArray[1], out parsedValue);
}
}
return parsedValue;
}
Possible cleaner version of the read csv method.
private void button1_Click(object sender, EventArgs e) {
if (openFile.ShowDialog() == DialogResult.OK) {
List<string[]> rows = File.ReadLines(openFile.FileName).Select(x => x.Split(',')).ToList();
List<string> headerNames = rows[0].ToList();
foreach (var headers in rows[0]) {
dt.Columns.Add(headers);
}
foreach (var x in rows.Skip(1).OrderBy(r => r.First())) {
if ((!(x[0] == "Lot ID")) || (!(x.All(val => string.IsNullOrWhiteSpace(val)))))
dt.Rows.Add(x);
}
dataGridView1.DataSource = dt;
dataGridView1.ReadOnly = true;
}
}
Lastly, possible cleaner version of the write method. It uses the DataTable instead of the grid itself.
private void button2_Click(object sender, EventArgs e) {
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "txt files (*.txt)|*.txt|Csv files (*.csv)|*.csv";
sfd.FilterIndex = 2;
if (sfd.ShowDialog() == DialogResult.OK) {
try {
using (StreamWriter sw = new StreamWriter(sfd.FileName, false)) {
string columnString = "";
for (int i = 0; i < dt.Columns.Count - 1; i++) {
columnString += dt.Columns[i].ColumnName;
if (i < dataGridView1.Columns.Count - 2)
columnString += ",";
}
sw.WriteLine(columnString);
string rowString = "";
foreach (DataRow dr in dt.Rows) {
rowString = "";
for (int i = 0; i < dt.Columns.Count - 1; i++) {
rowString += dr.ItemArray[i].ToString();
if (i < dt.Columns.Count - 2)
rowString += ",";
}
sw.WriteLine(rowString);
}
}
}
catch (Exception exceptionObject) {
MessageBox.Show(exceptionObject.ToString());
}
}
}
You could use a List<string> values and store the values in the string using
values.Add(cellV);
You can then use values.ToArray() to get an array to the stored values.
Your function will look like this
public void Button3_Click(object sender, EventArgs e)
{
List<string> values = new List<string>();
// Create a new instance of the Form2 class
// Form2 goForm2 = new Form2();
// Show the settings form
// goForm2.Show();
//string checkP = "p = ";
// string removePE = checkP.Replace("P = ", "").Replace("F = ", "");
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
//prevent error occur coz , only execute the not null line
if(cell.Value != null)
{
string cellV = cell.Value.ToString();
//do operations with cell
if (!cellV.Contains("="))
{
continue;
}
else if (cellV.Contains("P = "))
{
cellV = cellV.Replace("P = ", "");
}
else if (cellV.Contains("F = n/a"))
{
cellV =cellV.Replace("F = n/a", "0");
}
else if (cellV.Contains("F = "))
{
cellV = cellV.Replace("F = ", "");
}
values.Add(cellV);
Console.WriteLine(cellV + "\n");
}
}
}
}
I have a DataList that contains CheckBoxList, and I filter the datalist on selectedindexchanged outside datalist. The problem is when I select value from dropdownlist I can't get the checked values from database
and checkboxlist items count is 0
this is the code
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string GroupValue;
if (DropDownList1.SelectedValue.ToString().IsEmpty()) { GroupValue = null; } else { GroupValue = DropDownList1.SelectedValue.ToString(); }
if (pageMode == PageMode.Update)
{
int rowID = int.Parse(GrdUsers.GetRowValues(GrdUsers.FocusedRowIndex, "ID").ToString());
//ConnectionLayer cn = new ConnectionLayer();
//DataTable dt = cn.ExecutQuery("PagesSys", new object[] { 0, DropDownList1.SelectedItem.Text.ToString() });
//dlstPages.DataSource = dt;
//dlstPages.DataBind();
BindOption(rowID);
}
private void BindOption(int UserID)
{
try
{
if (pageMode == PageMode.Update)
{
if (DropDownList1.SelectedItem.Value != "-1")
{
dlstPages.DataSource = ViewState["FunctionOption"];
dlstPages.DataBind();
if (dlstPages.Items.Count > 0)
{
for (int i = 0; i < dlstPages.Items.Count; i++)
{
DataTable dt = new Users().UserPrivilege(UserID, int.Parse(dlstPages.DataKeys[i].ToString()));
if (dt.Rows.Count > 0)
{
dt.PrimaryKey = new DataColumn[] { dt.Columns["OptionId"] };
CheckBoxList chklist = (CheckBoxList)dlstPages.Items[i].FindControl("chkOption");
for (int j = 0; j < chklist.Items.Count; j++)
{
if (dt.Rows.Find(chklist.Items[j].Value) != null)
{
chklist.Items[j].Selected = true;
}
}
}
}
}
}
}
}
catch (Exception ex)
{
}
}
You need to use the arguments to the function to get the dropdown list object, then you can find the selected value. Something like:
DropDownList ddl= (DropDownList)sender;
var value = ddl.SelectedValue.ToString();
I'm trying to bind data with a chart to display it. However when I'm trying to link one of the columns with one of the axis of the chart it comes up with "The name Column1 does not exist in the current context" error. Does anybody know what I'm doing wrong and how to fix it?
Here is my code:
namespace bike
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var col1 = new List<string>();
var col2 = new List<string>();
var col3 = new List<string>();
var col4 = new List<string>();
var Column1 = col1.Select<string, int>(q => Convert.ToInt32(q));
var Column2 = col2.Select<string, int>(q => Convert.ToInt32(q));
var Column3 = col3.Select<string, int>(q => Convert.ToInt32(q));
var Column4 = col4.Select<string, int>(q => Convert.ToInt32(q));
dataGridView1.Columns.Add("col1", "Heart Rate");
dataGridView1.Columns.Add("col2", "Speed");
dataGridView1.Columns.Add("col3", "Power");
dataGridView1.Columns.Add("col4", "Altitude");
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
int row = 0;
string line;
bool isInHRData = false;
while ((line = sr.ReadLine()) !=null)
{
if (!isInHRData)
{
if (line != "[HRData]")
continue;
isInHRData = true;
continue;
}
else if (line.StartsWith("[") && line.EndsWith("["))
break;
string[] columns = line.Split('\t');
if (columns.Length > 0)
col1.Add(columns[0]);
if (columns.Length > 1)
col2.Add(columns[1]);
if (columns.Length > 2)
col3.Add(columns[2]);
if (columns.Length > 3)
col4.Add(columns[3]);
/*col1.Add(columns[0]);
col2.Add(columns[1]);
col3.Add(columns[2]);
col4.Add(columns[3]);
*/
dataGridView1.Rows.Add();
for (int i = 0; i < columns.Length; i++)
{
dataGridView1[i, row].Value = columns[i];
}
row++;
}
int maxSpeed = Column2.Max();
maxSpeed = maxSpeed / 10;
string MaxSpeed = Convert.ToString(maxSpeed);
textBox1.Text = MaxSpeed;
double aveSpeed = Column2.Average();
aveSpeed = aveSpeed / 10;
aveSpeed = Math.Round(aveSpeed, 0);
string AveSpeed = Convert.ToString(aveSpeed);
textBox2.Text = AveSpeed;
double aveHeart = Column1.Average();
aveHeart = Math.Round(aveHeart, 0);
string AveHeart = Convert.ToString(aveHeart);
textBox3.Text = AveHeart;
int maxHeart = Column1.Max();
string MaxHeart = Convert.ToString(maxHeart);
textBox4.Text = MaxHeart;
int minHeart = Column1.Min();
string MinHeart = Convert.ToString(minHeart);
textBox5.Text = MinHeart;
double avePower = Column3.Average();
avePower = Math.Round(avePower, 0);
string AvePower = Convert.ToString(avePower);
textBox6.Text = AvePower;
int maxPower = Column3.Max();
string MaxPower = Convert.ToString(maxPower);
textBox7.Text = MaxPower;
double aveAltitude = Column4.Average();
aveAltitude = Math.Round(aveAltitude, 0);
string AveAltitude = Convert.ToString(aveAltitude);
textBox8.Text = AveAltitude;
int maxAltitude = Column4.Max();
string MaxAltitude = Convert.ToString(maxAltitude);
textBox9.Text = MaxAltitude;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
chart1.DataSource = dataGridView1;
chart1.Series["Series1"].XValueMember = Column1;
chart1.Series["Series1"].YValueMembers = "test";
chart1.DataBind();
}
}
}
You're declaring Column1 as a local variable within your (rather long) button1_Click method. If you want it to be part of the state of the object, which will make it available in button2_Click, you should declare it as an instance variable instead.
You might want to consider what will happen if button 2 is clicked before button 1 though.