I want to get the sum of a column of datagridview and show that in textbox. After each entry the sum should be changed dynamically. For that I am using textChanged event of
If you need to take into account the possibility that a user may edit existing values in the grid rows, you can subscribe to the CellEndEdit
event.
Here, I'm checking the column index so you're not recalculating the sum if any other unrelated columns are edited. (I'm also validating the input and setting the value to 0 if, say, someone enters letters.)
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 5)
{
decimal result;
if (!Decimal.TryParse(Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value), out result))
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
textBox1.Text = dataGridView1.Rows.Cast()
.Sum(x => Convert.ToDecimal(x.Cells[5].Value))
.ToString();
}
}
Others may have better solutions... this is just one possibility.