如何在Winform中的数据网格视图中为DataGridViewComboBoxColumn创建事件处理程序

Ana*_*nth 1 c# datagridview winforms

我在数据网格视图中有一个DataGridViewComboBoxColumn.我附上了一个列表作为数据源.现在我需要根据组合框的选定索引触发一个事件.我怎样才能完成它呢?提前致谢

Bra*_*ith 7

鉴于该SelectedIndex属性属于编辑控件(仅DataGridView在处于编辑模式时才处于活动状态),您可以附加一个事件处理程序,EditingControlShowing如下所示:

void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) {
    if (e.Control is ComboBox) {
        // remove handler first to avoid attaching twice
        ((ComboBox)e.Control).SelectedIndexChanged -= MyEventHandler;
        ((ComboBox)e.Control).SelectedIndexChanged += MyEventHandler;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,控件的实际类型是DataGridViewComboBoxEditingControl扩展的ComboBox.您只需要基类的功能,而且输入的内容更少.