how to deselect other listBoxes when 1 is selected

心已入冬 提交于 2019-12-11 05:57: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;
        }
    }
}


来源:https://stackoverflow.com/questions/7178067/how-to-deselect-other-listboxes-when-1-is-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!