C# ListBox

ListBox stores several text items. It can interact with other controls, including Button controls. We use this control in Windows Forms. In the example program it interacts with two Buttons—through the Button Click event handler.

ListBox in Windows Forms

Tutorial

Steps

First, create a new Windows Forms C# project, and then open the Toolbox and double-click on the ListBox item. This will insert a new ListBox into your Windows Forms designer. If you want to use Buttons with the ListBox, add those too.

Next:Right-click on the Form in the Solution Explorer, and select "View Code." You will see a C# code file, very similar to the code that follows. Here, create a new List at the class level. This is what we will use for binding to the ListBox.

Example that creates List: C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication11
{
    public partial class Form1 : Form
    {
	List<string> _items = new List<string>(); // <-- Add this

	public Form1()
	{
	    InitializeComponent();

	    _items.Add("One"); // <-- Add these
	    _items.Add("Two");
	    _items.Add("Three");

	    listBox1.DataSource = _items;
	}
    }
}

In this example, we see a List of strings at the class level. This is a good place to store the lines you want to show in your ListBox. In the constructor, we add three elements to the List.

DataSource:At the final point in the constructor, we assign the DataSource from the listBox1 to the new List. Now, run the program and you will see the three strings in your ListBox.

DataSource

Button

Go back to your Designer window in Visual Studio where you see the image of the Form. Select the buttons and then add the text "Add" and "Remove" to their Text properties in the Properties pane. Run your program again and you will see this.

ListBox example

Adding the event handlers for the buttons. Here we double-click on each button in the Designer. You will immediately be taken to the C# code view and a new event handler will have been inserted.
In these event handlers,
we manipulate the List
and refresh the ListBox.

Click event handler: C#

private void button1_Click(object sender, EventArgs e)
{
    // The Add button was clicked.
    _items.Add("New item " + DateTime.Now.Second); // <-- Any string you want

    // Change the DataSource.
    listBox1.DataSource = null;
    listBox1.DataSource = _items;
}

private void button2_Click(object sender, EventArgs e)
{
    // The Remove button was clicked.
    int selectedIndex = listBox1.SelectedIndex;

    try
    {
	// Remove the item in the List.
	_items.RemoveAt(selectedIndex);
    }
    catch
    {
    }

    listBox1.DataSource = null;
    listBox1.DataSource = _items;
}

Form

Here we see the complete code for the Form.cs file, which acts on the ListBox and two Buttons in the Designer. It shows how to add and remove items to the ListBox with the buttons.

Example that uses DataSource: C#

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApplication11
{
    public partial class Form1 : Form
    {
	List<string> _items = new List<string>();

	public Form1()
	{
	    InitializeComponent();

	    _items.Add("One");
	    _items.Add("Two");
	    _items.Add("Three");

	    listBox1.DataSource = _items;
	}

	private void button1_Click(object sender, EventArgs e)
	{
	    // The Add button was clicked.
	    _items.Add("New item " + DateTime.Now.Second);

	    // Change the DataSource.
	    listBox1.DataSource = null;
	    listBox1.DataSource = _items;
	}

	private void button2_Click(object sender, EventArgs e)
	{
	    // The Remove button was clicked.
	    int selectedIndex = listBox1.SelectedIndex;

	    try
	    {
		// Remove the item in the List.
		_items.RemoveAt(selectedIndex);
	    }
	    catch
	    {
	    }

	    listBox1.DataSource = null;
	    listBox1.DataSource = _items;
	}
    }
}

The program's final appearance and usage. This program will allow you to add items to the ListBox by clicking the top button, and then remove the selected item by clicking the bottom button.

ListBox final example

Enabled

You can easily change the Enabled state of your Add and Remove buttons by setting the Enabled property equal to false or true when the List is full or empty. This example demonstrates setting Enabled.

Example that sets Enabled property: C#

private void button1_Click(object sender, EventArgs e)
{
    // The Add button was clicked.
    // ...

    button2.Enabled = true;
}

private void button2_Click(object sender, EventArgs e)
{
    // The Remove button was clicked.
    // ....

    if (listBox1.Items.Count == 0)
    {
	button2.Enabled = false;
    }
}

In this example, there are two button click event handlers. Button1 is the Add button, so it always sets the Enabled property of Add to true. Button2 is the Remove button, so it is disabled when there are no items in the ListBox.

Tip:You can find more details on Buttons here.

Button

Usage

Programming tip

You will want to persist the values in your ListBox to disk when your program exits. To do this, you can use the Settings.settings file in your project.

Often you can wire the events for keyboard comments straight to the button1_Click event handlers. This means the code paths are identical and less code needs to be tested.

SelectionMode:You can use this to eliminate the selection by setting it to None. This is useful for read-only displays that are common in programs.

IntegralHeight:This lets you specify that the control should show partial rows. If the size of your Form cannot fit six elements but can fit five, IntegralHeight will display only five. By setting IntegralHeight to False, you will display five and whatever remains.

HorizontalScrollbar:This property lets you specify if you want to be able to scroll horizontally on long items. If you have a big ListBox, use this, but if your ListBox is smaller, it could be better to truncate the value in your C# code.

Tooltip on toolTip1:This property on your ListBox allows you to specify the tool tip that the user gets when hovering. Note that you must have a toolTip1 in your Form first.

Anchor:You should always Anchor controls like the ListBox, so they can expand when the user is working and changing the window size. Even better, use the TableLayoutPanel control and Anchor inside of it.

TableLayoutPanelVisual Studio logo

In Visual Studio, it is possible to actually simply type the items you want to be present in the ListBox using the designer. Then, when the program is executed, the code generated by Visual Studio will insert these values.

Tip:You can do this by modifying the Items property through the appropriate dialog box.

Summary

The C# programming language

We added a ListBox and had other controls interact with it, with code in the C# programming language. It is important that you bind its DataSource through some mechanism.

Note:Adding items manually is harder to do correctly and would be much more complex.


C#: Windows