我正在使用ListBox
使用 List<SomeObject>
作为其 DataSource
.
当需要从列表框中删除项目时,我将从列表中删除该项目,然后将列表重新添加为数据源。
除了列表末尾的项目(包括包含一项的列表)之外,此方法工作正常。在这些情况下,当我尝试重新附加数据源时会收到错误:
InvalidArgument=Value of '0' is not valid for 'SelectedIndex'.
这对我来说很有意义 - ListBox 正在尝试选择现在超出范围的索引处的项目。没有意义的是,即使我调用ClearSelected()
,这种行为仍然存在。在重新附加之前立即在列表框中显示:
if (this.RulesBox.DataSource != null) this.RulesBox.DataSource = null;
this.RulesBox.ClearSelected();
this.RulesBox.DataSource = this.Rules;
我需要做什么才能正确清除 SelectedIndex?
最佳答案
我建议使用 BindingSource 从列表中删除项目。
这将避免将列表重新附加到列表框。
在此示例中,我使用 List<string>
ListBox l = new ListBox();
BindingSource bs = new BindingSource();
void Main()
{
Form f = new Form();
Button b = new Button();
b.Click += onclick;
b.Dock = DockStyle.Bottom;
List<string> ls = new List<string>()
{"Steve", "Mark", "John"};
bs.DataSource = ls;
l.DataSource = bs;
l.Dock = DockStyle.Fill;
f.Controls.Add(b);
f.Controls.Add(l);
f.Show();
}
void onclick(object sender, EventArgs e)
{
if(l.SelectedIndex != -1)
{
bs.RemoveAt(l.SelectedIndex);
}
}
顺便说一句,我能够使用 ClearSelected 重现您的问题。看来您需要调用 ClearSelected 两次才能有效地删除列表框中任何项目的选择。
像这样的事情
this.RulesBox.ClearSelected();
this.RulesBox.ClearSelected();
但是,我再次认为您应该使用 BindingSource,而不是分离并重新附加 DataSource。对于很少的项目,可能这不是什么大问题,但是,如果您有很多项目,我认为您应该注意到这种附加/分离方法的性能下降。
关于c# - 为什么调用 ClearSelected 并附加数据源后 SelectedIndex 可能为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29263654/