首页 文章

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

提问于
浏览
2

我有一个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);
        }
    }

我已经尝试了forebound bindingSource,但它给出了一个枚举错误,但是无法正常工作 . 据我所知,没有代码可以清除整个源代码,所以我尝试通过List本身并通过项目名称删除它们,但这不起作用,因为foreach实际上返回一个对象或东西,不是一个字符串 .

有关如何做到这一点的任何建议?

2 回答

  • 7

    如果使用某个通用List将Listbox绑定到BindingSource,那么您可以这样做:

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

    另一方面,在你的表单,Viewmodel或其他任何可以做到这一点的工作中持有对底层列表的引用 .

    编辑:这仅在您的List是ObservableCollection时有效 . 对于普通List,您可以尝试在BindingSource上调用ResetBindings()来强制刷新 .

  • 3

    您可以通过键入直接完成

    listBox1.Items.Clear();
    

相关问题