我的表单上有2个列表框,但我只想在两者之间进行单一选择,我该如何处理?
当然,我先尝试过这样做......
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
ListBox2.ClearSelected()
End Sub
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
ListBox1.ClearSelected()
End Sub
但是,由于这会导致所选索引被更改,因此它会清除您刚刚选择的内容......
感谢您的帮助!
答案 0 :(得分:2)
您可以测试原因选择索引发生变化的原因,如下所示:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
// If listBox2 focused i.e. user clicked list box2 - do nothing:
// one should not try to clear list box2 selection
if (listBox2.Focused)
return;
listBox2.ClearSelected();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e) {
// If list box1 is in focus that means that user just have selected itme there;
// so, do nothing: we shouldn't erase user's selection
if (listBox1.Focused)
return;
listBox1.ClearSelected();
}
答案 1 :(得分:1)
首先,您的问题被标记为C#,但代码示例是VB。 其次,我会在C#中做到如下:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox2.SelectedIndexChanged -= new System.EventHandler(this.listBox2_SelectedIndexChanged);
listBox2.ClearSelected();
listBox2.SelectedIndexChanged += new System.EventHandler(this.listBox2_SelectedIndexChanged);
}
并对其他事件处理程序执行相同的操作。