I want to connect a BindingSource to a list of class objects and then objects value to a ComboBox.
Can anyone suggest how to do it?
public class Country { public string Name { get; set; } public IList<City> Cities { get; set; } public Country() { Cities = new List<City>(); } }
is my class and I want to bind its name field to a BindingSource which could be then associated with a ComboBox
As you are referring to a combobox, I’m assuming you don’t want to use 2-way databinding (if so, look at using a
BindingList)To find the country selected in the bound combobox, you would do something like:
Country country = (Country)comboBox1.SelectedItem;.If you want the ComboBox to dynamically update you’ll need to make sure that the data structure that you have set as the
DataSourceimplementsIBindingList; one such structure isBindingList<T>.Tip: make sure that you are binding the
DisplayMemberto a Property on the class and not a public field. If you class usespublic string Name { get; set; }it will work but if it usespublic string Name;it will not be able to access the value and instead will display the object type for each line in the combo box.