SelectedIndexChanged事件多次触发

时间:2013-01-30 16:10:04

标签: c# datagridview

我需要在用户更改网格中DataGridViewComboBoxColumn的值时执行操作。假设我必须显示一条消息。

问题是messagebox.show(“hello”)代码执行了数百万次。

这是我的代码。

grilla.EditingControlShowing+=new DataGridViewEditingControlShowingEventHandler(grilla_EditingControlShowing);

void  grilla_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is ComboBox) //i have only one combobox column.
            {
                ComboBox cb = (ComboBox)e.Control;
                // first remove event handler to keep from attaching multiple:
                cb.SelectedIndexChanged -= new EventHandler(cb_SelectedIndexChanged);

                // now attach the event handler
                cb.SelectedIndexChanged += new EventHandler(cb_SelectedIndexChanged);
            }

        }

        void cb_SelectedIndexChanged(object sender, EventArgs e)
        {
            MessageBox.Show("hello");
        }

1 个答案:

答案 0 :(得分:1)

最后,我找到了一个完全符合我想要的代码:

grid.CurrentCellDirtyStateChanged += (s, e) => 
            {
                if (grid.IsCurrentCellDirty)
                {
                    grid.CommitEdit(DataGridViewDataErrorContexts.Commit);

                    MessageBox.Show("hello");
                }
            };

更改组合单元的值后,该消息仅显示一次。