Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get sum dynamically of datagridview column in textbox

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();
        }
like image 421
Haider Khattak Avatar asked Dec 04 '22 08:12

Haider Khattak


1 Answers

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.

like image 175
sab669 Avatar answered Jan 03 '23 19:01

sab669