Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to load up a ListBox?

Tags:

c#

.net

winforms

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.

like image 465
BuddyJoe Avatar asked Nov 19 '08 20:11

BuddyJoe


People also ask

What is the correct syntax to insert item in a ListBox control in window form?

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.

How do I add a list to my ListBox?

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.


2 Answers

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.

like image 106
BFree Avatar answered Sep 29 '22 11:09

BFree


You can bind a DataTable directly...

listbox.ValueMember = "your_id_field"; listbox.DisplayMember = "your_display_field"; listbox.DataSource = dataTable; 
like image 26
Aaron Palmer Avatar answered Sep 29 '22 11:09

Aaron Palmer