例如,我有100个组合框,需要在选择新索引时更新特定的组合框。当组合框设置新值时,如何仅使用一种方法来捕获事件?
答案 0 :(得分:1)
只创建一个事件处理程序ComboBox_SelectedIndexChanged
,并为此事件订阅所有组合框:
combobox1.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
combobox2.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
combobox3.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
combobox4.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
//and so on
事件处理程序代码:
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
//now "sender" is the reference to the combo box raised the event
//so just cast it
ComboBox combobox = sender as ComboBox;
//now access it as you want
}