views:

109

answers:

1

I have an application with lots of ListBox controls. I was wondering if it would be possible to add the eventhandler for the onselectedindexchanged in the constructor of the Listbox? All listboxes will use the same method for this.

I know I can add them manually but I was hoping for a solution that would change all the ones I currently have to use the same eventhandler and when I add a new one to not have to tie to the method.

+1  A: 

You could simply iterate over the controls? For example (in your Form's / Control's ctor, after initiaize):

CascadeListBoxEvent(this, MyHandlerMethod)

using the utility method:

static void CascadeListBoxEvent(Control parent, EventHandler handler)
{
    Queue<Control> queue = new Queue<Control>();
    queue.Enqueue(parent);
    while (queue.Count > 0)
    {
        Control c = queue.Dequeue();
        ListBox lb = c as ListBox;
        if (lb != null)
        {
            lb.SelectedIndexChanged += handler;
        }
        foreach (Control child in c.Controls)
        {
            queue.Enqueue(child);
        }
    }
}
Marc Gravell
+1 for providing a better solution than what was asked.
Babak Naffas