简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM