Binding Listbox to List<object> in WinForms
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()
.
Pretending you are displaying a list of customer objects with "customerName" and "customerId" properties:
listBox.DataSource = customerListObject;
listBox.DataTextField = "customerName";
listBox.DataValueField = "customerId";
listBox.DataBind();
Edit: I know this works in asp.net - if you are doing a winforms app, it should be pretty similar (I hope...)
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";