2017-09-19 6 views
0

私はこの質問が答えられた(Do not trigger cell value change event in DataGridView when the value is changed programatically)が、回答は十分に文書化されておらず、うまくいかなかったことを知っています。DataGridViewでセル値変更イベントをトリガするにはどうすればよいですか?

DataGridViewのCell Value Changedイベントでは、データが指定された範囲外の場合は、導入されたデータを検証して作業しています。そしてそこに問題がある。プログラムで実行すると、イベントが2回トリガーされます。私はそれがしたくないです。

アイデア?

ありがとうございます!

答えて

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; 
     } 
    } 
} 
関連する問題