Reputation: 123
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.
Upvotes: 1
Views: 413
Reputation: 1062770
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);
}
}
}
Upvotes: 1