Multiple listboxes created dynamically with event

83 views Asked by At

I'm creating dynamically multiple listboxes in c# using the for loop. I want to add to each one of them a SelectionChanged so that when the selected item changed I display a content based on which listbox it is and the item. But it seems that the event is linked to only the last one:

for (int d =0; d<3; d++)
{                   
   //list des attribut
   ListBox lb = new ListBox();
   lb.Width = 200;
   lb.Height = 250;

   for( int i=0; i< names.Length; i++)
   {                                     
       lb.Items.Add(names[i]);       
   }

   listboxes.Add(lb);
   lb.SelectionChanged += (sender, e) => LBTest_SelectionChanged(sender, e, d); 
   ResultPalner.Children.Add(lb);
}

public void LBTest_SelectionChanged(object sender, EventArgs e, int i)
{
   // Do something here according to which listbox it is!
}
2

There are 2 answers

1
Salah Akbari On BEST ANSWER

Try this:

public void LBTest_SelectionChanged(object sender, EventArgs e, int i)
{
   ListBox lst = sender as ListBox;
   if (lst.Name ==  "listBox1")
    {
       // do something here according to..        
    }
}
0
user35443 On

You need to use object sender in the LBTest_SelectionChanged to find out which ListBox changed its selection.

public void LBTest_SelectionChanged(object sender, EventArgs e, int i) {
    if(/* sender is listbox 1*/) {
        /* do something */
    } else if (/* sender is listbox 2*/) {
        /* do something else */
    } else ...
}

Like

public void LBTest_SelectionChanged(object sender, EventArgs e, int i) {
    if((ListBox)sender.Name == "name1") {
        /* do something */
    } else if ((ListBox)sender.Name == "name2") {
        /* do something else */
    } else ...
}

The thing that happens is basically what you do. You want the same function to respond to slection changes of all ListBoxess. That's why it happens.