使用一个方法comboBox_SelectedIndexChanged控制许多组合框

时间:2015-08-23 16:39:25

标签: c# winforms

例如,我有100个组合框,需要在选择新索引时更新特定的组合框。当组合框设置新值时,如何仅使用一种方法来捕获事件?

1 个答案:

答案 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
}