开发者

Cancelling Windows Forms Events

I have a windows form. It has a ComboBox and a DataGrid

I have a Leave event on my ComboBox and I have a DoubleClick event on my DataGrid row

The idea is that on leaving the ComboBox, if the value of the ComboBox changed then use the new value to reload the DataGrid.

Let's say the ComboBox is displaying a value of 1 and for that value there are 5 records displayed in the DataGrid. Now the user enters 2 in the ComboBox and tabs away. In my Leave event I see that the value has changed and I reload the DataGrid with all the records for that value.

But if the user enters 2 and double clicks on existing records for the value 1, than the leave event reloads the DataGrid and than the DoubleClick event FIRES.

How do I find a开发者_StackOverflow list of pending events and cancel each and every one of them, if the DataGrid has been reloaded?


You've got an event order problem, the DataGridView.Enter event fires too soon. This can be cleanly solved by delaying event actions with the Control.BeginInvoke() method. Its delegate target fires as soon as your program re-enters the message loop. In other words, after all pending events have fired. Make it look similar to this:

private bool selectionDirty;

private void comboBox1_TextChanged(object sender, EventArgs e) {
  selectionDirty = true;
}

private void dataGridView1_Enter(object sender, EventArgs e) {
  this.BeginInvoke(new Action(() => selectionDirty = false));
}

private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
  if (selectionDirty) return;
  // etc...
}


Instead of using the Leave Event, try SelectedIndexChanged Event, that would be fired before the DataGrids DoubleClick event. The downside is if the user is scrolling the ComboBox with the keyboard, then it will fire 5 times if the user scrolls 5 steps down in the ComboBox.

Another solution would be to store a local variable lComboEntered=true when entering the ComboBox and set the value to false when the Leave event fires. And in the DataGrid DoubleClick event check if the lComboEntered=false before doing anything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜