Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind Winforms ListBox collection to List<object>

I have a class containing details of my customer.

class CustomerData : INotifyPropertyChanged
{
    private string _Name;
    public string Name 
    { 
        get 
        { return _Name } 
        set 
        {
            _Name = value;
            OnPropertyChanged("Name");
        }
    }

   // Lots of other properties configured.
}

I also have a list of CustomerData values List<CustomerData> MyData;

I currently databinding an individual CustomerData object to textboxes in the below way which works fine.

this.NameTxtBox.DataBindings.Add("Text", MyCustomer, "Name", false, DataSourceUpdateMode.OnPropertyChanged);

I'm struggling to find a way to bind each object in the list MyData to a ListBox.

I want to have each object in the MyData list in displayed in the ListBox showing the name.

I have tried setting the DataSource equal to the MyData list and setting the DisplayMember to "Name" however when i add items to the MyData list the listbox does not update.

Any ideas on how this is done?

like image 253
CathalMF Avatar asked Sep 11 '25 23:09

CathalMF


1 Answers

I found that List<T> will not allow updating of a ListBox when the bound list is modified. In order to get this to work you need to use BindingList<T>

BindingList<CustomerData> MyData = new BindingList<CustomerData>();

MyListBox.DataSource = MyData;
MyListBox.DisplayMember = "Name";

MyData.Add(new CustomerData(){ Name = "Jimmy" } ); //<-- This causes the ListBox to update with the new entry Jimmy.
like image 178
CathalMF Avatar answered Sep 13 '25 11:09

CathalMF