What's the simplest way to bind a Listbox to a List of objects in Windows Forms?
To bind a ComboBox or ListBox control If you are binding to a table, set the DisplayMember property to the name of a column in the data source. If you are binding to an IList, set the display member to a public property of the type in the list.
In this article Then, the Visual Studio tools are used to bind the types defined in the model to the WinForms controls. The WinForms data-binding framework enables navigation between related objects: selecting rows in the master view causes the detail view to update with the corresponding child data.
string value = listBox. Items[index]. ToString(); If the things in the listbox are some sort of object, you may need to override ToString() to get the desired result, or cast the thing you get out of the listbox to the desired type and then access an appropriate property.
You're looking for the DataSource property
:
List<SomeType> someList = ...; myListBox.DataSource = someList;
You should also set the DisplayMember
property to the name of a property in the object that you want the listbox to display. If you don't, it will call ToString()
.
Binding a System.Windows.Forms.Listbox Control to a list of objects (here of type dynamic)
List<dynamic> dynList = new List<dynamic>() { new {Id = 1, Name = "Elevator", Company="Vertical Pop" }, new {Id = 2, Name = "Stairs", Company="Fitness" } }; listBox.DataSource = dynList; listBox.DisplayMember = "Name"; listBox.ValueMember = "Id";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With