I am very confused and have spent a long time trying to debug this event. I have a column and I want to add the first 3 cells in the column and update the 4th cell to be the sum of the first 3.
This works the very first time I populate the first 3 cells. Afterwards, if I try to edit any cell again, the 4th cell won’t change its value. It ONLY works if I edit the 1st cell.
Does anyone know why this is happening? Here is the small part of my code that does this:
int sum = 0;
for (int i = 0; i < 3; i++)
{
if (dataGridView1.Rows[i].Cells[1].Value == null)
sum += 0;
else
sum += int.Parse(dataGridView1.Rows[i].Cells[0].Value.ToString()) * int.Parse(dataGridView1.Rows[0].Cells[1].Value.ToString());
}
dataGridView1.Rows[3].Cells[1].Value = sum;
Those lines of code are within the dataGridView1_CellEndEdit function, so occurs after I change a cell’s value.
A few things I notice about this that should probably be confirmed/fixed.
With this line, what exactly are you doing? You’re checking for a value in the second column of the row in question here, but then you only ever add items from the first column (and multiply each by some number from the first row, second column). This isn’t exactly clear what you’re trying to do. That’s one of the difficulties with dealing with DataGridViews, is that there’s a lot more guesswork than modifying a bound data source. For example, are you sure the column (indexes) actually reference the items you’re interested in? Are you keeping it consistent? Also, I believe the
CellEndEditevent only fires when focus is lost from a particular cell after being edited.I’m going to give some modified code, but without knowing some additional info I might just be getting this wrong. Based on what you said, you only want the sum of the first 3 values of a column, so that’s what this code does. If this is wrong, please tell me and I’ll correct it (if I can).