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 thought I could bind it with a Dictionary
. No luck.
Do I have to write an class called KeyValuePair
, and then use List<KeyValuePair>
just to be able to load this thing with objects? Maybe I am missing something obvious. I want my display text and values to be different values.
To add items to a ListBox, select the ListBox control and get to the properties window, for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line.
Add Items in a Listbox You can use the Add or Insert method to add items to a list box. The Add method adds new items at the end of an unsorted list box. If the Sorted property of the C# ListBox is set to true, the item is inserted into the list alphabetically. Otherwise, the item is inserted at the end of the ListBox.
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
.
You can bind a DataTable directly...
listbox.ValueMember = "your_id_field"; listbox.DisplayMember = "your_display_field"; listbox.DataSource = dataTable;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With