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.
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;
}
}
}
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;
}
}
}
In my little NET5/Winforms app, the selected item of the current listbox won't stay blue/marked.
I found the solution for that is restoring focus back and set the index. Improving on the generic solution with a proper type check, Nane's answer,
private void lbDefect_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox thisListBox = sender as ListBox;
if (thisListBox == null || thisListBox.SelectedIndex == 0)
{
return;
}
var iSelected = thisListBox.SelectedIndex; // keep position..
foreach (ListBox loopListBox in this.Controls.OfType<ListBox>().ToList())
{
if (thisListBox != loopListBox)
{
loopListBox.SelectedIndex = -1;
}
}
// .. and this will show the selection for the current listbox
thisListBox.Focus();
thisListBox.SelectedIndex = iSelected;
}
精彩评论