'Update dataGridView when cell value changed
I'm having some problem with refresing cell value in dataGridView.
My program in c# set values of some rows on button click, but I allow user to change some value in DataGridView.
EG. Column3 = Column2+Column1.
Which works correctly when i click button but after it when I change some cell value in Column2 I also want Column3 to change value.
I'v tried
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
dataGridView11.Update();
dataGridView1.Refresh();
}
And
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
button1_Click(this, new EventArgs());
new value = true;
}
And set in my button1_Click code this :
if(value == true){
for (int i = 0; i < dataTable.Rows.Count; i++){
dataTable.Rows[i][all] = (int)dataTable.Rows[i][columnNumber]
+ (int)dataTable.Rows[i][amount];
}
}
But it kinda doesn't work. Can anyone tell me how should I do it?
Solution 1:[1]
Try to add following action to CellValueChanged event on your DataGridView.
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
var grid = (sender as DataGridView);
if (e.RowIndex != -1 && (e.ColumnIndex == 0 || e.ColumnIndex == 1))
(grid.Rows[e.RowIndex]).Cells[2].Value = (int)(grid.Rows[e.RowIndex]).Cells[0].Value + (int)(grid.Rows[e.RowIndex]).Cells[1].Value;
}
It checks if first or second column was changed and if this change is for any possible row. It should update 3rd column based on values in 1st and 2nd column for that one row where you changed these column values. Right now it only works for integer values.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CrudaLilium |
