如果手动完成,如何在DataGridView中触发单元格值更改事件?

时间:2017-09-19 13:51:41

标签: c# winforms visual-studio events datagridview

所以我知道这个问题得到了回答(Do not trigger cell value change event in DataGridView when the value is changed programatically),但所提供的答案没有足够的记录,也没有用。

基本上我正在通过验证引入的数据来处理datagridview的Cell Value Changed事件,如果数据超出指定范围,我将其更改为适合。而且存在问题;当我以编程方式执行此操作时,它会触发事件两次;我不希望它这样做。

有什么想法吗?

提前致谢!

1 个答案:

答案 0 :(得分:1)

当您需要以编程方式更改值时,可以禁用CellValueChangedEvent。在更改了值之后,只需重新启用CellValueChangedEvent,例如。

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    //check whether the value is valid
    var specifiedMax = 100;
    var compareValue = int.Parse(this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
    if (compareValue > specifiedMax)
    {
        //disable the cellvaluechanged event before changing the value
        this.dataGridView1.CellValueChanged -= this.dataGridView1_CellValueChanged;
        try
        {
          this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 100;
        }
        finally
        {
            //enable the cellvaluechanged event again
            this.dataGridView1.CellValueChanged += this.dataGridView1_CellValueChanged;
        }
    }
}
相关问题