C# 如何刷新列表框的项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13998587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:19:38  来源:igfitidea点击:

How refresh items of a ListBox?

c#winformslistbox

提问by TheScholar

Possible Duplicate:
C# Force ListBox to update elements

可能的重复:
C# 强制 ListBox 更新元素

Let's consider this small piece of code:

让我们考虑一下这段代码:

listbox.DataSource = base_items;
listbox.DisplayMember = "Name";
// ... a bit later in the program
base_items.Add(  new Base_Item("Unnamed")  );

From this point, how do I do to make the listbox update its items? The only way for me to see the update is to close the window and reload it again.

从这一点来看,我该如何让列表框更新其项目?我看到更新的唯一方法是关闭窗口并重新加载它。

采纳答案by Gregor Primar

Just remove and add databinding again. You can create method that can be used on first load and when new item was added:

只需删除并再次添加数据绑定。您可以创建可在首次加载和添加新项目时使用的方法:

    void BindData()
    {
        listBox.DataSource = null;
        listBox.DataSource = base_items;
        listbox.DisplayMember = "Name";
    }

So here is the code for adding new item and refreshing listbox:

所以这是添加新项目和刷新列表框的代码:

    base_items.Add(new Base_Item("Unnamed"));
    BindData();

回答by Khan

As mentioned in Marc G's answer.

正如 Marc G 的回答中提到的。

C# Force ListBox to update elements

C# 强制 ListBox 更新元素

If you know that the list needs refreshing, simple update the DisplayMemberof the listbox.

如果您知道列表需要刷新,只需更新DisplayMember列表框。

listbox.DisplayMember = "";
listbox.DisplayMember = "Name";