How refresh items of a ListBox? [duplicate]

≡放荡痞女 提交于 2019-12-22 09:48:03

问题


Possible Duplicate:
C# Force ListBox to update elements

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.


回答1:


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



回答2:


As mentioned in Marc G's answer.

C# Force ListBox to update elements

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

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


来源:https://stackoverflow.com/questions/13998587/how-refresh-items-of-a-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!