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
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;
Use LINQ if you can.
label1.Text = dataGridView1.Rows.Cast<DataGridViewRow>()
.AsEnumerable()
.Sum(x => int.Parse(x.Cells[1].Value.ToString()))
.ToString();
decimal Total = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
Total+= Convert.ToDecimal(dataGridView1.Rows[i].Cells["ColumnName"].Value);
}
labelName.Text = Total.ToString();
Fast and clean way using LINQ
int total = dataGridView1.Rows.Cast<DataGridViewRow>()
.Sum(t => Convert.ToInt32(t.Cells[1].Value));
verified on VS2013
Add the total row to your data collection that will be bound to the grid.
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();