Search code examples
c#listboxselecteditemselectedindex

C# How to sync Two Lisboxes with MultiSimple as SelectionMode


As the question suggests, I have two listboxes. I use one to get me the ID from the database, and another to display the related information to the user.

I've been using this for other tables like:

int IDIndex = Listbox1.SelectedIndex;
ListBox2.SelectedIndex = IDIndex;

How do I do that if ListBox1 has more than one item selected?

@Edit: The following code is what I've used for this. Check @Pikoh's answer also

Boolean IndexChanged = false;
int IDIndex = -1;
foreach(int ind in ListBox1.SelectedIndices)
{
    if (!ListBox2.SelectedIndices.Contains(ind)) {
        ListBox2.SetSelected(ind, true);
        //Index Selected: ind
        IDIndex = ind;
        IndexChanged = true;
    }
}
if (!IndexChanged)
{
    foreach (int ind in ListBox2.SelectedIndices)
    {
        if (!ListBox1.SelectedIndices.Contains(ind))
        {
            ListBox2.SetSelected(ind, false);
            //Index Deselected: ind
            IDIndex = ind;
            IndexChanged = true;
        }
    }
}

This allows me to know which index was changed. My program has to know this to check the database for the related information.


Solution

  • You can use the SelectedIndices collection. Then, you can do something like:

    if (Listbox1.SelectedIndices.Count>0)
    {
         IDIndex = Listbox1.SelectedIndices[0];
    }
    

    Or

    IDIndex = this.listBox1.SelectedIndices.Cast<int>().First();
    

    Or you can loop on the collection. It depends on the behaviour you want. This answer assumes a Winforms Listbox

    Edit If you want to replicate the selected indices of Listbox1 in Listbox2, you can do something like this:

    Listbox2.ClearSelected();
    foreach (int ind in Listbox1.SelectedIndices)
    {
         Listbox2.SetSelected(ind, true);
    }