0

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

1
  • In asp.net or in winform? Commented Jan 21, 2014 at 17:47

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is a pretty good approach. I'd also recommend storing something (either the object or an index) to the ComboBox.Tag property to help identify 'which' one the sender is in the event handler.
@SiLo That was the point of my last sentence. I'm not sure what the usefulness would be. I would rather discard the arrays and just deal with the objects as I know them.
0

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*/};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.