Home > Articles

This chapter is from the book

Using the ListBox Control

The ComboBox is ideal for applications in space-constrained environments, but the ListBox should be used if you have enough screen space to display several options to the user at once.

The ComboBox and ListBox share almost the same exact set of properties and methods. This includes the Items collection property and the Add, Remove, and Clear methods on the Items property. For example, the following code adds strings to a ListBox control at runtime. This code is nearly identical to the code used to add string to a ComboBox control.

C#
listBox1.Items.Add("Hi");
listBox1.Items.Add("Howdy");
listBox1.Items.Add("Wuz Up");
VB
listBox1.Items.Add("Hi")
listBox1.Items.Add("Howdy")
listBox1.Items.Add("Wuz Up")

You can also add items to the ListBox control at runtime by binding the ListBox to a collection. The process of binding a ListBox control is identical to binding a ComboBox control. First, set the DataSource to the collection. Then, set the DisplayMember to the source item property that will be used as the display string. The following code is another version of the LoadCustomers method from the "Using the ComboBox Control" section. Instead of binding to a ComboBox, a list of Customer objects is bound to a ListBox.

C#
private void LoadCustomers() {
 if(customers != null)
  return;

  customers = new Customer[6];
  customers[0] = new Customer("Ronnie", "Donnell", "Yates");
  customers[1] = new Customer("Moya", "Alicia", "Hines");
  customers[2] = new Customer("Veronica", "Christine", "Yates");
  customers[3] = new Customer("Diane", "", "Taylor");
  customers[4] = new Customer("Kindell", "Elisha", "Yates");
  customers[5] = new Customer("Zion", "Donnell", "Yates");

  this.listBox1.DataSource = customers;
  this.listBox1.DisplayMember = "FullName";
}
VB
Dim customers(6) As Customer
customers(0) = New Customer("Ronnie", "Donnell", "Yates")
customers(1) = New Customer("Moya", "Alicia", "Hines")
customers(2) = New Customer("Veronica", "Christine", "Yates")
customers(3) = New Customer("Diane", "", "Taylor")
customers(4) = New Customer("Kindell", "Elisha", "Yates")
customers(5) = New Customer("Zion", "Donnell", "Yates")

ListBox1.DataSource = customers
ListBox1.DisplayMember = "FullName"

The ListBox also exposes the SelectedIndex and SelectedItem properties. These properties provide access to the currently selected item in the ListBox control. These properties are used exactly as they are with the ComboBox control.

  • + Share This
  • 🔖 Save To Your Account