rever
rever

Reputation: 197

Handle event by list of windows form controls

I have one Windows Form within a lot of ListBoxes, and every ListBox have to do the same thing. I think to handle these like a list.

OnLoad I create the list:

private List<ListBox> lsts = new List<ListBox>();        
lsts.Add(lstStart);
lsts.Add(lst0);
lsts.Add(lst1);
lsts.Add(lst2);
lsts.Add(lst3);

How can I write the SelectedIndexChanged Method for all ListBoxes in my List?

Try for answer, I didn't found a tutorial for that.

Upvotes: 1

Views: 51

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39956

Use this code first to generate SelectedIndexChanged for all ListBoxes:

lsts.ForEach(c => c.SelectedIndexChanged += lsts_SelectedIndexChanged);

And:

private void lsts_SelectedIndexChanged(object sender, EventArgs e)
{
    //Use sender to find the selected ListBox 
    var selectedListBox = (ListBox)sender;
    //Do what you want with selected ListBox 
    MessageBox.Show(selectedListBox.Name);
}

Upvotes: 2

Related Questions