How can I invert the selected items in multiple listboxes using only one for loop?
I am using three list boxes. I have to invert the selected items in all th开发者_运维知识库e list boxes using an invert button.
How can code it using only a single loop? There can be more than 3 list boxes as well.
Hi you could use this function to invert the selection for a given listbox.
/* Windows ListBox
public void InvertSelection(ListBox objLstbox)
{
if(objLstbox == null) return;
for (int i = 0; i < objLstbox.Items.Count; i++)
objLstbox.SetSelected(i, !objLstbox.GetSelected(i));
}
*/
//WebApp listbox
public void InvertSelection(ListBox objLstbox)
{
if (objLstbox == null) return;
for (int i = 0; i < objLstbox.Items.Count; i++)
objLstbox.Items[i].Selected = !objLstbox.Items[i].Selected;
}
private void btnInvert_Click(object sender, EventArgs e)
{
InvertSelection(listBox1);
InvertSelection(listBox2);
InvertSelection(listBox3);
}
public void InvertSelection(ListBox objLstbox)
{
if (objLstbox == null) return;
for (int i = 0; i < objLstbox.Items.Count; i++)
objLstbox.Items[i].Selected = !objLstbox.Items[i].Selected;
}
protected void Button1_Click(object sender, EventArgs e)
{
InvertSelection(ListBox1);
}
I banged my head on this with the rest of you, and finally developed my own function for Inverting Here's the VB.Net Answer:
Private Function InvertListBoxSelections(ByRef tempListBox As ListBox) As Integer
Dim selectedind(tempListBox.SelectedItems.Count) As Integer
Try
For selind = 0 To tempListBox.SelectedItems.Count - 1
selectedind.SetValue(tempListBox.Items.IndexOf(tempListBox.SelectedItems(selind)), selind)
Next
tempListBox.ClearSelected()
For listitemIndex = 0 To tempListBox.Items.Count
If Array.IndexOf(selectedind, listitemIndex) < 0 Then
tempListBox.SetSelected(listitemIndex, True)
End If
Next
Return 1
Catch ex As Exception
Return 0
End Try
End Function
for (int i = 0; i < listbox.Items.Count; i++)
{
if (listbox.SelectedItems.Contains(listbox.Items[i]))
listbox.SetSelected(i, false);
else
listbox.SetSelected(i, true);
}
Since I got here and got confused by selection i'll leave this here.
This code inverts all checked items by using .SetItemChecked and .GetItemChecked:
private void ButtonInvertChecked_Click(object sender, EventArgs e)
{
for (int i = 0; i < checkedListBox.Items.Count; i++)
checkedListBox.SetItemChecked (i, !checkedListBox.GetItemChecked(i));
}
精彩评论