3

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?

Behzad
  • 3,502
  • 4
  • 36
  • 63
CathalMF
  • 9,705
  • 6
  • 70
  • 106
  • 2
    Have you checked this : http://stackoverflow.com/questions/2675067/binding-listbox-to-listobject ? – George Vovos Jun 16 '15 at 10:16
  • Yes i have tried that. However when i add items to my List the ListBox does not update. – CathalMF Jun 16 '15 at 10:27
  • 2
    winforms does not use observation system. therefor you have to push object to listbox itself. – JSJ Jun 16 '15 at 10:34
  • 1
    Ah found it. Instead of List i needed to use BindingList. This allows the ListBox to update as the collection is modified. – CathalMF Jun 16 '15 at 10:51

1 Answers1

4

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.
CathalMF
  • 9,705
  • 6
  • 70
  • 106