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 a textbox but when the entry is made it does not show any result. I want to get the result dynamically in the textbox. I want to avoid the use of button for sum.
Here is a piece of code for the textbox textChanged event:
private void textBox9_TextChanged(object sender, EventArgs e)
{
double sum = 0;
for (int i = 0; i < dataGridView2.Rows.Count; ++i)
{
sum += Convert.ToDouble(dataGridView2.Rows[i].Cells[5].Value);
}
textBox9.Text = sum.ToString();
}
You've got your code right, but instead I've put it in the CellValueChanged event and check to make sure it was the same cell you're looking for. This will get fired if the cell's value changes, or if a new row is added and subsequently gets a value assigned.
private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 5)
textBox9.Text = CellSum().ToString();
}
private double CellSum()
{
double sum = 0;
for (int i = 0; i < dataGridView2.Rows.Count; ++i)
{
double d = 0;
Double.TryParse(dataGridView2.Rows[i].Cells[5].Value.ToString(), out d);
sum += d;
}
return sum;
}
I split up your logic into a separate method, so incase you ever want to get the sum for something else, you can simply call that method. I suppose you could just read textbox.Text, but...
I've also used Double.TryParse as it provides some basic protection incase the value in that given cell is not actually a number. I don't know what the source of the data is (user entered / from an outside source?) so I figured I'd add a little protection.
Edit Grant raises a great point, editted my solution to include cell value being modified. I used the CellValueChanged event instead of CellEndEdit, incase something other than the user can change its value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With