how to deselect other listBoxes when 1 is selected

2019-08-02 13:38发布

问题:

I have 3 listBoxes and I want to deselect others when 1 of them is selected. How can I do this? I have tried setting the focused property to false, but c# doesn't allow assigning to the focused property.

回答1:

Assuming you have three list boxes, do the following. This code will clear the selection of every other list box when a particular list box changes selections. You can clear a list box selection by setting its SelectedIndex = -1.

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex > -1)
    {
        listBox2.SelectedIndex = -1;
        listBox3.SelectedIndex = -1;
    }
}

private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listBox2.SelectedIndex > -1)
    {
        listBox1.SelectedIndex = -1;
        listBox3.SelectedIndex = -1;
    }
}

private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listBox3.SelectedIndex > -1)
    {
        listBox1.SelectedIndex = -1;
        listBox2.SelectedIndex = -1;
    }
}

The if (listBox#.SelectedIndex > -1) is necessary because setting the SelectedIndex of a list box via code will also trigger its SelectedIndexChanged event, which would otherwise cause all list boxes to clear any time one of them was selected.

EDIT:

Alternatively, if you only have those three list boxes on your form, then you could consolidate it into one method. Link all three list boxes to this event method:

private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
    ListBox thisListBox = sender as ListBox;
    if (thisListBox == null || thisListBox.SelectedIndex == 0)
    {
        return;
    }

    foreach (ListBox loopListBox in this.Controls)
    {
        if (thisListBox != loopListBox)
        {
            loopListBox.SelectedIndex = -1;
        }
    }
}


回答2:

Using @Devin Burke's answer, so you don't have to worry having other controls in the form:

using System.Linq;
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
    ListBox thisListBox = sender as ListBox;
    if (thisListBox == null || thisListBox.SelectedIndex == 0)
    {
        return;
    }

    foreach (ListBox loopListBox in this.Controls.OfType<ListBox>().ToList())
    {
        if (thisListBox != loopListBox)
        {
            loopListBox.SelectedIndex = -1;
        }
    }
}