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