当选择1如何取消选择其他列表框 [英] how to deselect other listBoxes when 1 is selected
问题描述
我有3个列表框,我想在选择其中1到取消选择其他.我怎样才能做到这一点? 我尝试将focused属性设置为false,但是c#不允许分配给focused属性.
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.
推荐答案
假定您有三个列表框,请执行以下操作.当特定列表框更改选择时,此代码将清除所有其他列表框的选择.您可以通过设置其SelectedIndex = -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;
}
}
if (listBox#.SelectedIndex > -1)
是必需的,因为通过代码设置列表框的SelectedIndex
也会触发其SelectedIndexChanged
事件,否则将在所有列表框被选中时清除所有列表框.
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.
或者,如果表单上只有这三个列表框,则可以将其合并为一种方法.将所有三个列表框链接到此事件方法:
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;
}
}
}
这篇关于当选择1如何取消选择其他列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!