如何仅使用一个for循环反转多个列表框中的选定项目?

时间:2011-02-02 07:14:32

标签: c# winforms listbox for-loop listboxitem

我正在使用三个列表框。我必须使用反转按钮反转所有列表框中的所选项目。

如何只使用一个循环来编码?也可以有超过3个列表框。

4 个答案:

答案 0 :(得分:4)

您好,您可以使用此功能来反转给定列表框的选择。

    /* 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);
    }

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我和你们其他人一起讨论这个问题,最后开发了自己的Inverting功能 这是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

答案 3 :(得分:0)

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