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
2010-04-20 12:34:52
How would I go about removing an item of SomeType from the Listbox via selection?
cam
2010-04-20 12:46:03
`someList.Remove((SomeType)myListBox.SelectedValue);` (In WinForms)
SLaks
2010-04-20 12:50:34
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
2010-04-20 12:35:38
+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
2010-04-20 12:42:01