C# 用一个方法控制多个组合框组合框\u选择的索引已更改

C# 用一个方法控制多个组合框组合框\u选择的索引已更改,c#,winforms,C#,Winforms,例如,我有100个组合框,需要在选择新索引时更新特定的组合框。当组合框设置了新值时,如何仅使用一种方法捕获事件?仅创建一个事件处理程序组合框\u SelectedIndexChanged,并将所有组合框订阅到此事件: combobox1.SelectedIndexChanged += ComboBox_SelectedIndexChanged; combobox2.SelectedIndexChanged += ComboBox_SelectedIndexChanged; combobox3.S

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

仅创建一个事件处理程序
组合框\u 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
}

如果需要,可以将相同的SelectedIndexChanged事件分配给所有组合框。