I have a scenario where I have three listboxes. Multiple Items can be selected in the listboxes. Based on the selection of items in one listbox, I need to select and deselect the corresponding rows in the other listboxes.
I have the code below, but I am missing something. When I select and deselecting the item, it selects and deselects the other rows items incorrectly.
for (int count = 0; count < listBox_1.SelectedIndices.Count; count )
{
// Determine if the item is selected.
if (listBox_1.GetSelected(count) == true)
{
listBox_2.SetSelected(listBox_1.SelectedIndices[count], false);
listBox_3.SetSelected(listBox_1.SelectedIndices[count], false);
}
else if (listBox_1.GetSelected(count) == false)
{
// Select all items that are not selected.
listBox_2.SetSelected(listBox_1.SelectedIndices[count], true);
listBox_3.SetSelected(listBox_1.SelectedIndices[count], true);
}
}
Here Selection of items in LB1 should control the selection in LB2 and LB3. Now, since Item 2 and 3 are selected in LB1 - items 2 and 3 should be selected in LB2 and LB3 as well. But that's not what's happening.
CodePudding user response:
Here Selection of items in LB1 should control the selection in LB2 and LB3. Now, since Item 2 and 3 are selected in LB1 - items 2 and 3 should be selected in LB2 and LB3 as well. But that's not what's happening.
I would recommend looping through all items of listBox_1
...
for (int idx = 0; idx <= listBox_1.Items.Count - 1; idx )
{
if (listBox_1.GetSelected(idx))
{
if (idx <= listBox_2.Items.Count)
listBox_2.SetSelected(idx, true);
if (idx <= listBox_3.Items.Count)
listBox_3.SetSelected(idx, true);
}
else
{
if (idx <= listBox_2.Items.Count)
listBox_2.SetSelected(idx, false);
if (idx <= listBox_3.Items.Count)
listBox_3.SetSelected(idx, false);
}
}
Please note, I put a check as well to make sure the index would exist, otherwise it could throw an error if the index doesn't exist.
CodePudding user response:
It is unclear where this code is called. I would simply clear the other list2 and list3 boxes and then set the same selected indexes as the ones in list box 1... some thing like...
listBox_2.ClearSelected();
listBox_3.ClearSelected();
foreach (int selectedItem in listBox_1.SelectedIndices) {
listBox_2.SetSelected(selectedItem, true);
listBox_3.SetSelected(selectedItem, true);
}