How can I invert selected items in multiple lists using only one loop?

I use three lists. I have to invert the selected items in all lists using the invert button.

How to code it using only one loop? There may also be more than 3 lists.

+3
source share
4 answers

Hi, you can use this function to invert the selection for a given list.

    /* 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);
    }
+4
source
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);
}
0
source

I hit my head about it with the rest, and finally developed my own function for Inverting. Here's the answer from VB.Net:

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
0
source
    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);
    }
0
source

Source: https://habr.com/ru/post/1789426/


All Articles