Eri*_*ric 2 c# listbox visual-studio-2010 winforms
我有一个C#winform,它使用带有数据源绑定列表的列表框.该列表是从计算机上的文本文件创建的.我正在尝试为此列表框创建一个"全部删除"按钮,但我遇到了一些麻烦.
首先,这是相关代码:
private void btnRemoveAll_Click(object sender, EventArgs e)
{
// Use a binding source to keep the listbox updated with all items
// that we add
BindingSource bindingSource = (BindingSource)listBox1.DataSource;
// There doesn't seem to be a method for purging the entire source,
// so going to try a workaround using the main list.
List<string> copy_items = items;
foreach (String item in copy_items)
{
bindingSource.Remove(item);
}
}
Run Code Online (Sandbox Code Playgroud)
我试过foreached bindingSource,但它给出了一个枚举错误,但是无法正常工作.据我所知,没有代码可以清除整个源代码,所以我尝试通过List本身并通过项目名称删除它们,但这不起作用,因为foreach实际上返回一个对象或东西,不是一个字符串.
有关如何做到这一点的任何建议?
如果您使用一些通用列表将列表框绑定到 BindingSource,那么您可以这样做:
BindingSource bindingSource = (BindingSource)listBox1.DataSource;
IList SourceList = (IList)bindingSource.List;
SourceList.Clear();
Run Code Online (Sandbox Code Playgroud)
另一方面,在表单、视图模型或任何其他内容中保留对底层列表的引用也可以达到目的。
编辑:这仅在您的列表是 ObservableCollection 时才有效。对于普通列表,您可以尝试在 BindingSource 上调用 ResetBindings() 来强制刷新。