简体   繁体   English

单元格值更改时更新 dataGridView

[英]Update dataGridView when cell value changed

I'm having some problem with refresing cell value in dataGridView.我在 dataGridView 中刷新单元格值时遇到了一些问题。

My program in c# set values of some rows on button click, but I allow user to change some value in DataGridView.我的 C# 程序在单击按钮时设置了某些行的值,但我允许用户更改 DataGridView 中的某些值。

EG. EG。 Column3 = Column2+Column1.列 3 = 列 2 + 列 1。

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.当我单击按钮时它可以正常工作,但是当我更改 Column2 中的某些单元格值后,我还希望 Column3 更改值。

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 :并在我的 button1_Click 代码中设置:

   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.尝试将以下操作添加到 DataGridView 上的 CellValueChanged 事件。

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.现在它只适用于整数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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