iBi*_*kov 14 c# listbox winforms
嘿.我有以下代码填充我的列表框
UsersListBox.DataSource = GrpList;
Run Code Online (Sandbox Code Playgroud)
但是,在填充框后,默认情况下会选择列表中的第一个项目,并触发"选定的索引已更改"事件.如何在填充列表框后立即阻止选择项目,或者如何阻止事件触发?
谢谢
Jos*_*ant 21
为了防止事件发生,以下是我过去使用过的两个选项:
在设置DataSource时取消注册事件处理程序.
UsersListBox.SelectedIndexChanged -= UsersListBox_SelectedIndexChanged;
UsersListBox.DataSource = GrpList;
UsersListBox.SelectedIndex = -1; // This optional line keeps the first item from being selected.
UsersListBox.SelectedIndexChanged += UsersListBox_SelectedIndexChanged;
Run Code Online (Sandbox Code Playgroud)创建一个布尔标志来忽略该事件.
private bool ignoreSelectedIndexChanged;
private void UsersListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (ignoreSelectedIndexChanged) return;
...
}
...
ignoreSelectedIndexChanged = true;
UsersListBox.DataSource = GrpList;
UsersListBox.SelectedIndex = -1; // This optional line keeps the first item from being selected.
ignoreSelectedIndexChanged = false;
Run Code Online (Sandbox Code Playgroud)嗯,看起来像设置了ListBox.DataSource 后自动选中了第一个元素。其他解决方案是好的,但它们不能解决问题。这是我解决问题的方法:
// Get the current selection mode
SelectionMode selectionMode = yourListBox.SelectionMode;
// Set the selection mode to none
yourListBox.SelectionMode = SelectionMode.None;
// Set a new DataSource
yourListBox.DataSource = yourList;
// Set back the original selection mode
yourListBox.SelectionMode = selectionMode;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11092 次 |
| 最近记录: |