Fire automatically an event when the content of a cell changes in the DataGridView

时间:2018-02-05 12:58:04

标签: c# visual-studio datagridview

I am a beginner with c # and Visual Studio. Nowadays, I'm doing a program that has the following GUI. In this program the user inserts a value (in the value cell), according to that its correction value is calculated, through a mathematical formula. At this moment, the event that I am using to trigger the calculation of the correction value is dataGridView1_CellEnter (see code below). It works perfectly when I click the cell where the value was modified. However, I would like to do this process automatically, without clicking any cell. Is there any event recognizes the value of a cell is automatically changed or any ideas how to implement it? I would appreciate your help. :)

enter image description here

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e){

        if (dataGridView1.Rows[e.RowIndex].Cells[1].Value != null){
            j = e.RowIndex;
            actualValue = float.Parse(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            IsValidMesswert();
        }
        else {
            if (dataGridView1.CurrentCell.ColumnIndex == 1){
                MessageBox.Show("Introduce a value", "value");
            }               
        }
    }

1 个答案:

答案 0 :(得分:1)

您是否考虑过使用DataTable?假设“值”列中的值是从同一行中的某些其他单元格生成的,那么,这似乎是计算值而不是数据本身的一部分。您可以将列添加到网格并在描述时手动管理...或者您可以将列添加到DataTable,然后使用其他单元格将列Expression设置为您想要的公式同一行...然后管理这些"更改“值将是自动的。

下面是我上面描述的一个简单例子。

Form有一个空DataGridView。创建DataTable并将一些数据添加到表中。此表用作DataSource的{​​{1}}。

加载后,用户可以更改“Value1”或“Value2”列中的值。执行此操作后,“结果”列单元格将自动更新以反映更改。当前公式简单地将两个值相乘。我希望这可能有所帮助。

DataGridView