簡體   English   中英

C# - 從列表框中刪除所有項目

[英]C# - Remove all items from listbox

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

我試過foreached bindingSource,但它給出了一個枚舉錯誤,但是無法正常工作。 據我所知,沒有代碼可以清除整個源代碼,所以我嘗試通過List本身並通過項目名稱刪除它們,但這不起作用,因為foreach實際上返回一個對象或東西,不是一個字符串。

有關如何做到這一點的任何建議?

您可以通過輸入直接完成

listBox1.Items.Clear();

如果使用某個通用List將Listbox綁定到BindingSource,那么您可以這樣做:

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

SourceList.Clear();

另一方面,在你的表單,Viewmodel或其他任何可以做到這一點的工作中持有對底層List的引用。

編輯:這僅在您的List是ObservableCollection時有效。 對於普通List,您可以嘗試在BindingSource上調用ResetBindings()來強制刷新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM