tags:

views:

100

answers:

3

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

+3  A: 

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

SLaks
How would I go about removing an item of SomeType from the Listbox via selection?
cam
`someList.Remove((SomeType)myListBox.SelectedValue);` (In WinForms)
SLaks
A: 

Granted, this isn't going to provide you anything truly meaningful unless the objects have properly overriden ToString() (or you're not really working with a generic list of objects and can bind to specific fields):

List<object> objList = new List<object>();

// Fill the list

someListBox.DataSource = objList;
Justin Niessner
+3  A: 

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

Ray