简体   繁体   中英

multiple combo box in c#

I am new to c#. I am trying to create multiple combo boxes based on result from query. If the query results 5 items I need to make 5 combo boxes. But I do not know how to add event handler( on selection changed event). I am using an array of combo boxes and number of boxes may vary. How do I come to know which comboBox of this array was changed and handle the event for same

Assuming this is WinForms...

As you are creating the controls, assign a generic event handler:

foreach (DataRow row in ADataTable)
{
    ComboBox box = new ComboBox();
    box.OnSelectionChanged += comboBox_OnSelectionChanged;
}

protected void comboBox_OnSelectionChanged(Object sender, EventArgs e)
{
    if (sender is ComboBox)
    {
        ComboBox box = (ComboBox)sender;
        //do what you like with it
    }
}

In order to operate on the ComboBox in question, you need know nothing about the array. In fact, you probably don't need the array at all unless there is more to the story.

you could either create a child class of the combo box in which case you can override the event, or you can get the name of your combobox and do something like so

comboboxName.OnSelected += (obj, args) => MethodToCall();

I dont think that is the exact name of the event but that should get you started. There are multiple variations of handling the event such as

comboboxName.OnSelected += MethodToCall;
void MethodToCall(Object sender, EventArgs e){}

or

comboboxName.OnSelected += () => delegate{/*put some code here*/};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM