Bind List to DataSource

房东的猫 提交于 2019-12-05 04:38:48

You don't have a BindingSource in you example.

you need to modify it like this to use a BindingSource

   var bs = new BindingSource();
   Foo foo1 = new Foo("bar1");
   fooList.Add(foo1);

     bs.DataSource = fooList; //<-- point of interrest

    //Bind fooList to the listBox
    listBox1.DataSource = bs; //<-- notes it takes the entire bindingSource

Edit

Be aware that (as was pointed out in comments) - the bindingsource does not work with INotifyPropertyChanged

Try

listBox1.DataSource = new BindingList<Foo>(fooList);

then

private void button1_Click(object sender, EventArgs e)
{
    Foo foo2 = new Foo("bar2");
    (listBox1.DataSource as BindingList<Foo>).Add(foo2);
}

This will update fooList without having to change its original type. Also, it will update the ListBox when you change the Bar member like fooList[1].Bar = "Hello";

However, you will have to set the DisplayMember property of the ListBox to "Bar", or to keep the .ToString() override as is in the Foo class definition.

In order to avoid to have to cast every time, I suggest you to use a BindingList variable at the same level as your List definition :

private List<Foo> fooList;
private BindingList<Foo> fooListUI;

fooListUI = new BindingList<Foo>(fooList);
listBox1.DataSource = fooListUI;

and in the button :

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