1
votes

I got a problem with a ListBox in a WinForm application. I have two ListBoxes inside of a tab control and depending on the selection in the first one (lb1), the DataSource of the second one (lb2) changes. This is done in the SelectedValueChanged Event.

        private void listBox_ControlUnits_SelectedValueChanged(object sender, EventArgs e)
    {
        ControlUnit unit = (sender as ListBox).SelectedItem as ControlUnit;

        textBox_ProjectNameTab.Text = unit.ProjectName;
        listBox_ControlCircuits.DataSource = null;
        listBox_ControlCircuits.DataSource = unit.ControlCircuits;           
    }

lb1 is filled with a DataSource, too.

Now if I select a value in lb1 the selection automatically jumps back to the first item and I can not figure out why. is this some kind of UI update problem? Even without the SelectedValueChanged event and the connection to the second listbox the issue occures.

Short gif of the problem, sorry for the blurriness

If I select one item more than once it works somehow (as seen in the gif).

Edit: I found the problem but I do not quite understand what happens. I have another listBox on another tab of my tab control. This listBox has the same DataSource as lb1. This seems to cause this behavior.

2
Is there a SelectedValueChanged event on the listbox_ControlCircuit as well?GvS
No event on this listBox.Joe

2 Answers

2
votes

I finally found the problem: I did not know that if I use the same DataSource for two ListBoxes they share the BindingContext per default. I created a new BindingContext for the second ListBox and now the selection does no longer change.

            listBox_allGroups.DataSource = null;
            listBox_allGroups.DataSource = x.y;
            listBox_allGroups.DisplayMember = "Name";

            listBox_ControlUnits.DataSource = null;
            listBox_ControlUnits.DataSource = x.y;
            listBox_ControlUnits.DisplayMember = "Name";
            listBox_ControlUnits.BindingContext = new BindingContext();
0
votes

You can use a variable to hold the selected item

object _selecteditem=null;

and check it in ListBox click event.

prive void ListBox1_Click(object sender,EventArgs e)
{
      if(ListBox1.SelectItem == _selecteditem) return;
      // do ...
}