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

时间:2022-01-27 19:35:32

I have a DataGridViewComboBoxColumn in a data grid view. I have attached a list as a data source . Now i need to fire an event based on the selected index of the combobox..How can I go aboout doing it ? Thanks in Advance

我在数据网格视图中有一个DataGridViewComboBoxColumn。我附上一份清单作为资料来源。现在我需要根据组合框的选定索引启动一个事件。我怎么才能做这件事呢?谢谢提前

1 个解决方案

#1


7  

Given that the SelectedIndex property belongs to the editing control (which is only active when the DataGridView is in edit mode), you could attach an event handler to EditingControlShowing like so:

既然SelectedIndex属性属于编辑控件(只有在DataGridView处于编辑模式时才激活),那么可以将事件处理程序附加到editingcontrolshow中,如下所示:

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;
    }
}

Note that the actual type of the control is DataGridViewComboBoxEditingControl, which extends ComboBox. You only need the functionality from the base class, plus it's less to type.

注意,该控件的实际类型是datagridviewcomboboxediting控件,它扩展了ComboBox。您只需要来自基类的功能,而且它的类型更少。

#1


7  

Given that the SelectedIndex property belongs to the editing control (which is only active when the DataGridView is in edit mode), you could attach an event handler to EditingControlShowing like so:

既然SelectedIndex属性属于编辑控件(只有在DataGridView处于编辑模式时才激活),那么可以将事件处理程序附加到editingcontrolshow中,如下所示:

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;
    }
}

Note that the actual type of the control is DataGridViewComboBoxEditingControl, which extends ComboBox. You only need the functionality from the base class, plus it's less to type.

注意,该控件的实际类型是datagridviewcomboboxediting控件,它扩展了ComboBox。您只需要来自基类的功能,而且它的类型更少。