What is the proper way to load a ListBox
in C# .NET 2.0 Winforms?
I thought I could just bind it to a DataTable
. No such luck.
I though
Using the DataSource paramater used to suck performance wise - on ComboBoxes at least,
I am now heavily conditioned to override ToString() on the object and just adding the objects using the Items.AddRange() method, as another commenter above describes.
You can bind a DataTable directly...
listbox.ValueMember = "your_id_field";
listbox.DisplayMember = "your_display_field";
listbox.DataSource = dataTable;
Simple code example. Say you have a Person
class with 3 properties. FirstName
, LastName
and Age
. Say you want to bind your listbox to a collection of Person
objects. You want the display to show the first name, but the value to be the age. Here's how you would do it:
List<Person> people = new List<Person>();
people.Add(new Person { Age = 25, FirstName = "Alex", LastName = "Johnson" });
people.Add(new Person { Age = 23, FirstName = "Jack", LastName = "Jones" });
people.Add(new Person { Age = 35, FirstName = "Mike", LastName = "Williams" });
people.Add(new Person { Age = 25, FirstName = "Gill", LastName = "JAckson" });
this.listBox1.DataSource = people;
this.listBox1.DisplayMember = "FirstName";
this.listBox1.ValueMember = "Age";
The trick is the DisplayMember
, and the ValueMember
.
Lets assume your data type is called MyDataType. Implement ToString() on that datatype to determine the display text. e.g.:
class MyDataType
{
public string ToString()
{
//return the text you want to display
}
}
Then you can take a list consisting of your datatype and cram it into the ListBox via AddRange() as follows:
ListBox l;
List<MyDataType> myItems = new List<MyDataType>(); // populate this however you like
l.AddRange(myItems.ToArray());
Let me know if you need more help - it would help to know what datatype you are trying to display in the listbox.
You can set the datasource to whatever datasource you like that implements the IList or IListSource.
You will also need to set the DisplayMember and the ValueMember properties to the fields you want to display and have the values associated with respectively.
To bind to a dictionary you have to wrap it in a new BindingSource object.
MyListBox.DataSource = New BindingSource(Dict, Nothing)
MyListBox.DisplayMember = "Value"
MyListBox.ValueMember = "Key"