Reputation: 869
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
Upvotes: 0
Views: 927
Reputation: 11035
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.
Upvotes: 1
Reputation: 121
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*/};
Upvotes: 0