ListBox in C#

A C# ListBox control provides a user interface to display a list of items. Users can select one or more items from the list. A ListBox may be used to display multiple columns and these columns may have images and other controls.
 
In this tutorial, we will learn how to create a C# ListBox control at design-time as well as at run-time. We will also see how to create a multiple-column ListBox control with single and multiple selections. This article also covers most of the properties and methods of the ListBox control.
 

Creating a C# ListBox

 
There are two approaches to create a ListBox control in Windows Forms. Either we can use the Forms designer to create a control at design-time or we can use the ListBox class to create a control at run-time.
 

Create a ListBox at Design-time

 
In our first approach, we are going to create a ListBox control at design-time using the Forms designer.
 
To create a ListBox control at design-time, we simply drag a ListBox control from the Toolbox and drop it to a Form in Visual Studio. After you drag and drop a ListBox onto a Form, the ListBox looks as in Figure 1. Once a ListBox is on the Form, you can move it around and resize it using the mouse and set its properties and events.
 
ListBoxImg1.jpg 
Figure 1
 

Create a ListBox Dynamically

 
The ListBox class represents a ListBox control in Windows Forms. To create a ListBox control at run-time, we create an instance of the ListBox class, set its properties and add a ListBox object to the Form controls.
 
The first step to create a dynamic ListBox is to create an instance of the ListBox class. The following code snippet creates a ListBox control object:
  1. ListBox listBox1 = new ListBox();  
In the next step, you may set the properties of a ListBox control. The following code snippet sets the location, width, height, background color, foreground color, Text, Name, and Font properties of a ListBox:
  1. listBox1.Location = new System.Drawing.Point(12, 12);  
  2. listBox1.Name = "ListBox1";  
  3. listBox1.Size = new System.Drawing.Size(245, 200);  
  4. listBox1.BackColor = System.Drawing.Color.Orange;  
  5. listBox1.ForeColor = System.Drawing.Color.Black;  
Once the ListBox control is ready with its properties, the next step is to add the ListBox to a Form. To do so, we use the Form.Controls.Add method that adds a ListBox control to the Form controls and displays it on the Form based on the location and size of the control. The following code snippet adds a ListBox control to the current Form: 
  1. Controls.Add(listBox1);  

C# ListBox Properties

 
The easiest way to set properties is from the Properties Window. You can open the Properties window by pressing F4 or by right-clicking on a control and selecting the "Properties" menu item. The Properties window looks as in Figure 2.
 
ListBoxImg2.jpg 
Figure 2
 

ListBox Name Property

 
The Name property represents a unique name of a ListBox control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a ListBox control:
  1. listBox1.Name = "ListBox1";  

ListBox Location, Height, Width and Size Properties

 
The Location property takes a Point that specifies the starting position of the ListBox on a Form. You may also use the Left and Top properties to specify the location of a control from the top-left corner of the Form.  The Size property specifies the size of the control. We can also use the Width and Height properties instead of the Size property. The following code snippet sets the Location, Width, and Height properties of a ListBox control:
  1. listBox1.Location = new System.Drawing.Point(12, 12);  
  2. listBox1.Size = new System.Drawing.Size(245, 200);  

ListBox Font

 
The Font property represents the font of the text of a ListBox control. If you click on the Font property in Properties window, you will see the Font name, size and other font options. The following code snippet sets the Font property at run-time:
  1. listBox1.Font = new Font("Georgia", 16);  

ListBox Background Color and Foreground Color

 
The BackColor and ForeColor properties are used to set the background and foreground colors of a ListBox respectively. If you click on these properties in the Properties window, then the Color Dialog pops up.
 
Alternatively, you can set background and foreground colors at run-time. The following code snippet sets the BackColor and ForeColor properties:
  1. listBox1.BackColor = System.Drawing.Color.Orange;  
  2. listBox1.ForeColor = System.Drawing.Color.Black;  
The new ListBox with background and foreground looks as in Figure 3.
 
ListBoxImg3.jpg 
Figure 3
 
You can also set the borders style of a ListBox by using the BorderStyle property. The BorderStyle property is represented by a BorderStyle enumeration that has three values: FixedSingle, Fixed3D, and None.The default value of the border style is Fixed3D. The following code snippet sets the border style of a ListBox to FixedSingle:
  1. listBox1.BorderStyle = BorderStyle.FixedSingle;  

ListBox Items

 
The Items property is used to add and work with items in a ListBox. We can add items to a ListBox at design-time from the Properties Window by clicking on the Items Collection as you can see in Figure 4.
 
ListBoxImg4.jpg 
Figure 4
 
When you click on the Collections, the String Collection Editor window will pop up where you can type strings. Each line added to this collection will become a ListBox item. I add four items as you can see from Figure 5.
 
ListBoxImg5.jpg 
Figure 5
 
The ListBox looks as in Figure 6.
 
ListBoxImg6.jpg 
Figure 6
 
You can add the same items at run-time by using the following code snippet:
  1. listBox1.Items.Add("Mahesh Chand");  
  2. listBox1.Items.Add("Mike Gold");  
  3. listBox1.Items.Add("Praveen Kumar");  
  4. listBox1.Items.Add("Raj Beniwal");  

Getting All Items of a ListBox

 
To get all items, we use the Items property and loop through it to read all the items. The following code snippet loops through all items and adds item contents to a StringBuilder and displays it in a MessageBox:
  1. private void GetItemsButton_Click(object sender, EventArgs e)  
  2. {  
  3.     System.Text.StringBuilder sb = new System.Text.StringBuilder();  
  4.     foreach (object item in listBox1.Items)  
  5.     {  
  6.         sb.Append(item.ToString());  
  7.         sb.Append(" ");  
  8.     }  
  9.     MessageBox.Show(sb.ToString());  
  10. }  

Selected Text and Item of a ListBox

 
The Text property is used to set and get text of a ListBox. The following code snippet sets and gets the current text of a ListBox:
  1. MessageBox.Show(listBox1.Text);  
We can also get text associated with the currently selected item using the Items property: 
  1. string selectedItem = listBox1.Items[listBox1.SelectedIndex].ToString();  

Why is the value of ListBox.SelectedText Empty?

 
The SelectedText property gets and sets the selected text in a ListBox only when a ListBox has focus on it. If the focus moves away from a ListBox then the value of SelectedText will be an empty string. To get the current text in a ListBox when it does not have focus, use the Text property.
 

C# ListBox Selection Mode and Selecting Items

 
The SelectionMode property defines how items are selected in a ListBox. The SelectionMode value can be one of the following four SelectionMode enumeration values:
  • None: No item can be selected.
  • One: Only one item can be selected.
  • MultiSimple: Multiple items can be selected. 
  • MultiExtended: Multiple items can be selected, and the user can use the SHIFT, CTRL, and arrow keys to make selections.
To select an item in a ListBox, we can use the SetSelect method that takes an item index and a true or false value where the true value represents the item to be selected.
 
The following code snippet sets a ListBox to allow multiple selection and selects the second and third items in the list:
  1. listBox1.SelectionMode = SelectionMode.MultiSimple;  
  2. listBox1.SetSelected(1, true);  
  3. listBox1.SetSelected(2, true);   
We can clear all selected items by calling the ClearSelected method, as in:
  1. listBox1.ClearSelected();  

How to disable item selection in a ListBox?

 
Just set the SelectionMode property to None.
 

Sorting Items of a ListBox

 
If the Sorted property is set to true then the ListBox items are sorted. The following code snippet sorts the ListBox items:
  1. listBox1.Sorted = true;  

Find Items in a ListBox

 
The FindString method is used to find a string or substring in a ListBox. The following code snippet finds a string in a ListBox and selects it if found:
  1. private void FindItemButton_Click(object sender, EventArgs e)  
  2. {  
  3.     listBox1.ClearSelected();  
  4.    
  5.     int index = listBox1.FindString(textBox1.Text);  
  6.    
  7.     if (index < 0)  
  8.     {  
  9.         MessageBox.Show("Item not found.");  
  10.         textBox1.Text = String.Empty;  
  11.     }  
  12.     else  
  13.     {  
  14.         listBox1.SelectedIndex = index;  
  15.     }  
  16. }  

ListBox SelectedIndexChanged Event Hander

 
The SelectedIndexChanged event is fired when the item selection is changed in a ListBox. You can add the event handler using the Properties Widow and selecting the Event icon and double-clicking on SelectedIndexChanged as you can see in Figure 7. 
 
ListBoxImg7.jpg 
Figure 7
 
The following code snippet defines and implements these events and their respective event handlers. You can use this same code to implement an event at run-time. 
  1. listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);   
  2.    
  3. private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)  
  4. {  
  5.     MessageBox.Show(listBox1.SelectedItem.ToString());  
  6. }  
Now every time you change the selection in the ListBox, you will see the selected item displayed in a MessageBox.
 

Data Binding in ListBox

 
The DataSource property is used to bind a collection of items to a ListBox.
 
The following code snippet is a simple data binding example where an ArrayList is bound to a ListBox: 
  1. private void DataBindingButton_Click(object sender, EventArgs e)  
  2. {  
  3.     ArrayList authors = new ArrayList();  
  4.     authors.Add("Mahesh Chand");  
  5.     authors.Add("Mike Gold");  
  6.     authors.Add("Raj Kumar");  
  7.     authors.Add("Praveen Kumar");  
  8.    
  9.     listBox1.Items.Clear();  
  10.     listBox1.DataSource = authors;  
  11. }   
If you are binding an object with multiple properites, you must specify which property you are displaying by using the DisplayMember property, as in:
  1. listBox1.DataSource = GetData();  
  2. listBox1.DisplayMember = "Name";  

Summary

 
In this article, we discussed how to create a ListBox control in Windows Forms. After that, we saw how to use various properties and methods. See the following list of articles to learn more about the ListBox control.
 

Further Readings

 
Here are some more articles and tutorials about ListBox that you may want to read:


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.