简体   繁体   English

C# - 从列表框中删除所有项目

[英]C# - Remove all items from listbox

I have a C# winform that uses a listbox with a bound list for the datasource. 我有一个C#winform,它使用带有数据源绑定列表的列表框。 The list is created from a text file on the computer. 该列表是从计算机上的文本文件创建的。 I'm trying to create a "Remove all" button for this listbox and am having a little trouble. 我正在尝试为此列表框创建一个“全部删除”按钮,但我遇到了一些麻烦。

First, here is the relevant code: 首先,这是相关代码:

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);
        }
    }

I've tried foreaching the bindingSource, but it gives an enumeration error and just won't work. 我试过foreached bindingSource,但它给出了一个枚举错误,但是无法正常工作。 As far as I can tell, there's not code to just purge an entire source, so I tried going through the List itself and removing them via the item name, but that doesn't work either since the foreach actually returns an object or something and not a string. 据我所知,没有代码可以清除整个源代码,所以我尝试通过List本身并通过项目名称删除它们,但这不起作用,因为foreach实际上返回一个对象或东西,不是一个字符串。

Any suggestions on how to do this? 有关如何做到这一点的任何建议?

您可以通过输入直接完成

listBox1.Items.Clear();

If you bound the Listbox to a BindingSource using some generic List then you can just do this: 如果使用某个通用List将Listbox绑定到BindingSource,那么您可以这样做:

BindingSource bindingSource = (BindingSource)listBox1.DataSource;
IList SourceList = (IList)bindingSource.List;

SourceList.Clear();

On the other handy, holding a reference to the underlaying List in your Form, Viewmodel or whatever would do the trick aswell. 另一方面,在你的表单,Viewmodel或其他任何可以做到这一点的工作中持有对底层List的引用。

EDIT: This only works if your List is a ObservableCollection. 编辑:这仅在您的List是ObservableCollection时有效。 For normal List you can try call ResetBindings() on the BindingSource to enforce a refresh. 对于普通List,您可以尝试在BindingSource上调用ResetBindings()来强制刷新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM