Morris
Morris

Reputation: 161

Sync. SelectedIndex of two multiselect Listboxes

I'm strungling to sync. the selectedIndexs of two multi-select Listboxes. With single-select enabled the code is just:

 private void libHT_SelectedIndexChanged(object sender, EventArgs e)
    {
        libMonth.SelectedIndex = libHT.SelectedIndex;
    }

But this doesn't work if multi-select is enabled. Can you help me? Do I have to use a for or foreach?

Thanks for your help. Thomas

Upvotes: 0

Views: 71

Answers (2)

Vikhram
Vikhram

Reputation: 4394

Yes, you will have to loop over all the selections. Code like below can help you with that

private void libHT_SelectedIndexChanged(object sender, EventArgs e) {
    libMonth.SelectedIndices.Clear();
    foreach (int indx in libHT.SelectedIndices)
        libMonth.SelectedIndices.Add(indx);
}

Don't forget:

  1. To hook the index changed event: libHT.SelectedIndexChanged += libHT_SelectedIndexChanged;
  2. To set the selection mode correctly libHT.SelectionMode = libMonth.SelectionMode = SelectionMode.MultiExtended;
  3. To watch out for your programmatic selection, causing infinite recursion

Upvotes: 0

David Setty
David Setty

Reputation: 609

There is the SelectedIndices property.

private void libHT_SelectedIndexChanged(object sender, EventArgs e)
{
        libMonth.SelectedIndices.Clear();
        foreach (var index in libHT.SelectedIndices.Cast<int>())
        {
            libMonth.SelectedIndices.Add(index);
        }
}

Try that

Upvotes: 1

Related Questions