Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding Listbox to List<object> in WinForms

What's the simplest way to bind a Listbox to a List of objects in Windows Forms?

like image 507
cam Avatar asked Apr 20 '10 12:04

cam


People also ask

How do I bind ListBox?

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.

What is Data Binding in WinForms?

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.

How do I get text from ListBox?

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.


2 Answers

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().

like image 146
SLaks Avatar answered Sep 27 '22 23:09

SLaks


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";   
like image 45
surfmuggle Avatar answered Sep 27 '22 23:09

surfmuggle