Reloading Listbox content

2019-08-27 20:15发布

问题:

When i see this post Here.

However in my code i don't see any DataBind() Method.

lstBox.DataBind();

How to reload listbox in C#.Net?

Refresh() Method is also didn't work.

回答1:

You might try use ObservableCollection as the ItemSource, and all is done automatically. Your task is then to populate items into the ObservableCollection, there is no need to manually update.



回答2:

DataBind() is for ASP.NET controls - as far as I'm aware, there is no equivalent method for Windows Forms controls. What's the datasource for your Listbox? I remember having a similar problem a while back, and I solved my problem by binding my control to a BindingSource object instead of whatever I was using. Similarly it may benefit you to bind your Listbox to a BindingSource instead of your current datasource. From MSDN:

The BindingSource component serves many purposes. First, it simplifies binding controls on a form to data by providing currency management, change notification, and other services between Windows Forms controls and data sources.

In other words, once you make changes to your BindingSource (such as calling BindingSource.Add, or setting the BindingSource's DataSource property to another collection), your ListBox will automatically be updated without any need to call a "DataBind()"-like method.

If your listbox is currently bound to a collection object, you can simply bind your collection to the BindingSource instead, then bind your control to the BindingSource:

BindingSource.DataSource = ListboxItems;
ListBox.DataSource = BindingSource;

Alternatively you can manually build the contents of the BindingSource:

MyBindingSource.Clear();
MyBindingSource.Add(new BusinessObject("Bill", "Clinton", 1946));
MyBindingSource.Add(new BusinessObject("George", "Bush", 1946));
MyBindingSource.Add(new BusinessObject("Barack", "Obama", 1961));

lstBox.DataSource = MyBindingSource;