views:

95

answers:

4

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?

alt text

+1  A: 
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();
JamesMLV
@ JamesMLV : thank you for your answer.
mahnaz
A: 

Use LINQ if you can.

  label1.Text =  dataGridView1.Rows.Cast<DataGridViewRow>()
                                   .AsEnumerable()
                                   .Sum(x => int.Parse(x.Cells[1].Value.ToString()))
                                   .ToString();
p.campbell
Can a `DataGridViewRow` ever be cast to a `DataRow`?
Dan Tao
@p.campbell: But... but... is there a `Field` extension method on `DataGridViewRow`?
Dan Tao
+5  A: 

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;
Dan Tao
@Dan I'm reminded of the reason I'm here... I never even realized a `Compute` function existed on the DataTable object!
Brad
A: 

Add the total row to your data collection that will be bound to the grid.

dretzlaff17