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

本文关键字:控制 SelectedIndexChanged 组合 comboBox 方法 一个 | 更新日期: 2023-09-27 18:09:38

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

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

只创建一个事件处理程序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
}