I need to show the sum of the count
column from this datagridview
, but I don't know how I can get to the data in the datagridview.
When I click on the button, I want to show 94
in label1
.
How can this be done?
I need to show the sum of the count
column from this datagridview
, but I don't know how I can get to the data in the datagridview.
When I click on the button, I want to show 94
in label1
.
How can this be done?
int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
}
label1.text = sum.ToString();
Use LINQ if you can.
label1.Text = dataGridView1.Rows.Cast<DataGridViewRow>()
.AsEnumerable()
.Sum(x => int.Parse(x.Cells[1].Value.ToString()))
.ToString();
If your grid is bound to a DataTable
, I believe you can just do:
// Should probably add a DBNull check for safety; but you get the idea.
long sum = (long)table.Compute("Sum(count)", "True");
If it isn't bound to a table, you could easily make it so:
var table = new DataTable();
table.Columns.Add("type", typeof(string));
table.Columns.Add("count", typeof(int));
// This will automatically create the DataGridView's columns.
dataGridView.DataSource = table;
Add the total row to your data collection that will be bound to the grid.