C# ListBox Control

The ListBox control enables you to display a list of items to the user that the user can select by clicking.

C# listbox

Setting ListBox Properties

You can set ListBox properties by using Properties Window. In order to get Properties window you can Press F4 or by right-clicking on a control to get the "Properties" menu item.

C# listbox properties

You can set property values in the right side column of the property window.

C# Listbox example

Add Items in a Listbox

Syntax
public int Add (object item);

In addition to display and selection functionality, the ListBox also provides features that enable you to efficiently add items to the ListBox and to find text within the items of the list. 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.

listBox1.Items.Add("Sunday");

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.

Insert Items in a Listbox

Syntax
public void Insert (int index, object item);

You can inserts an item into the list box at the specified index.

listBox1.Items.Insert(0, "First"); listBox1.Items.Insert(1, "Second"); listBox1.Items.Insert(2, "Third"); listBox1.Items.Insert(3, "Forth");

Listbox Selected Item

If you want to retrieve a single selected item to a variable , use the following code.

string item = listBox1.GetItemText(listBox1.SelectedItem);

Or you can use

string item = listBox1.SelectedItem.ToString();

Or

string item= listBox1.Text;

Selecting Multiple Items from Listbox

The SelectionMode property determines how many items in the list can be selected at a time. A ListBox control can provide single or multiple selections using the SelectionMode property . If you change the selection mode property to multiple select , then you will retrieve a collection of items from ListBox1.SelectedItems property.

listBox1.SelectionMode = SelectionMode.MultiSimple;

The ListBox class has two SelectionMode. Multiple or Extended .

In Multiple mode , you can select or deselect any item in a ListBox by clicking it. In Extended mode, you need to hold down the Ctrl key to select additional items or the Shift key to select a range of items.

The following C# program initially fill seven days in a week while in the form load event and set the selection mode property to MultiSimple . At the Button click event it will display the selected items.

using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { listBox1.Items.Add("Sunday"); listBox1.Items.Add("Monday"); listBox1.Items.Add("Tuesday"); listBox1.Items.Add("Wednesday"); listBox1.Items.Add("Thursday"); listBox1.Items.Add("Friday"); listBox1.Items.Add("Saturday"); listBox1.SelectionMode = SelectionMode.MultiSimple; } private void button1_Click(object sender, EventArgs e) { foreach (Object obj in listBox1.SelectedItems ) { MessageBox.Show(obj.ToString ()); } } } }

Getting All Items from List box

The Items collection of C# Winforms Listbox returns a Collection type of Object so you can use ToString() on each item to display its text value as below:


Retrieve All Items from List box
private void button1_Click_1(object sender, EventArgs e) { string items = ""; foreach (var item in listBox1.Items) { items += item.ToString() + ", "; } MessageBox.Show(items); }

How to bind a ListBox to a List ?

You can bind a List to a ListBox control by create a fresh List Object and add items to the List.

Creating a List

List<string> nList = new List<string>(); nList.Add("January"); nList.Add("February"); nList.Add("March"); nList.Add("April");

Binding to List

The next step is to bind this List to the Listbox. In order to do that you should set datasource of the Listbox.

listBox1.DataSource = nList;

C# Listbox binding to List
private void button1_Click(object sender, EventArgs e) { List<string> nList = new List<string>(); nList.Add("January"); nList.Add("February"); nList.Add("March"); nList.Add("April"); listBox1.DataSource = nList; }

How to bind a listbox to database values ?

First of all, you could create a connection string and fetch data from database to a Dataset.

connetionString = "Data Source=ServerName;Initial Catalog=databasename;User ID=userid;Password=yourpassword"; sql = "select au_id,au_lname from authors";

Set Datasource for ListBox

Next step is that you have set Listbox datasoure as Dataset.

listBox1.DataSource = ds.Tables[0]; listBox1.ValueMember = "au_id"; listBox1.DisplayMember = "au_lname";

populate C# listbox from datatable
using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connetionString = null; SqlConnection connection; SqlCommand command; SqlDataAdapter adapter = new SqlDataAdapter(); DataSet ds = new DataSet(); int i = 0; string sql = null; //connetionString = "Data Source=ServerName;Initial Catalog=databasename;User ID=userid;Password=yourpassword"; //sql = "select au_id,au_lname from authors"; connection = new SqlConnection(connetionString); try { connection.Open(); command = new SqlCommand(sql, connection); adapter.SelectCommand = command; adapter.Fill(ds); adapter.Dispose(); command.Dispose(); connection.Close(); listBox1.DataSource = ds.Tables[0]; listBox1.ValueMember = "au_id"; listBox1.DisplayMember = "au_lname"; } catch (Exception ex) { MessageBox.Show("Cannot open connection ! "); } } } }

How to refresh DataSource of a ListBox ?

How to clear the Listbox if its already binded with datasource ?

When you want to clear the Listbox, if the ListBox already binded with Datasource , you have to set the Datasource of Listbox as null.

listBox1.DataSource = null;

How to SelectedIndexChanged event in ListBox ?

This event is fired when the item selection is changed in a ListBox . You can use this event in a situation that you want select an item from your listbox and accodring to this selection you can perform other programming needs.

You can add the event handler using the Properties Window and selecting the Event icon and double-clicking on SelectedIndexChanged as you can see in following image.


C# listbox SelectedIndexChanged event

The event will fire again when you select a new item. You can write your code within SelectedIndexChanged event . When you double click on ListBox the code will automatically come in you code editor like the following image.


Listbox SelectedIndexChanged

From the following example you can understand how to fire the SelectedIndexChanged event.


Listbox SelectedIndexChanged event

First you should drag two listboxes on your Form. First listbox you should set the List as Datasource , the List contents follows:

List<string> nList = new List<string>(); nList.Add("First Quarter"); nList.Add("Second Quarter");

When you load this form you can see the listbox is populated with List and displayed first quarter and second quarter. When you click the "Fist Quarter" the next listbox is populated with first quarter months and when you click "Second Quarter" you can see the second listbox is changed to second quarter months. From the following program you can understand how this happened.

using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; using System.Collections.Generic; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } List < string > fQ = new List < string > (); List < string > sQ = new List < string > (); private void Form1_Load(object sender, EventArgs e) { fQ.Add("January"); fQ.Add("February"); fQ.Add("March"); sQ.Add("April"); sQ.Add("May"); sQ.Add("June"); List < string > nList = new List < string > (); nList.Add("First Quarter"); nList.Add("Second Quarter"); listBox1.DataSource = nList; } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (listBox1.SelectedIndex == 0) { listBox2.DataSource = null; listBox2.DataSource = fQ; } else if (listBox1.SelectedIndex == 1) { listBox2.DataSource = null; listBox2.DataSource = sQ; } } } }

C# Listbox Column

A multicolumn ListBox places items into as many columns as are needed to make vertical scrolling unnecessary. The user can use the keyboard to navigate to columns that are not currently visible. First of all, you have Gets or sets a value indicating whether the ListBox supports multiple columns .

public bool MultiColumn { get; set; }

C# Listbox Columns colum headers

The following C# code example demonstrates a simple muliple column ListBox.

private void button1_Click_1(object sender, EventArgs e) { listBox1.HorizontalScrollbar = true; listBox1.MultiColumn = true; listBox1.ScrollAlwaysVisible = true; listBox1.Items.AddRange(new object[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}); }

Listbox Item Double Click Event

Add an event handler for the Control.DoubleClick event for your ListBox.


C# Listbox Double Click Event

The following program shows when you double click the Listbox Item that event handler open up a MessageBox displaying the selected item.

private void listBox1_DoubleClick(object sender, EventArgs e) { if (listBox1.SelectedItem != null) { MessageBox.Show(listBox1.SelectedItem.ToString()); } }

Listbox vertical scrollbar

ListBox only shows a vertical scroll bar when there are more items then the displaying area. You can fix with ListBox.ScrollAlwaysVisible Property if you want the bar to be visible all the time. If ListBox.ScrollAlwaysVisible Property is true if the vertical scroll bar should always be displayed; otherwise, false. The default is false.

// Turn off the scrollbar. ListBox1.ScrollAlwaysVisible = false;

Background and Foreground

The Listbox BackColor and ForeColor properties are used to set the background and foreground colors respectively. If you click on these properties in the Properties window, then the Color Dialog pops up and you can select the color you want.

Alternatively, you can set background and foreground colors from source code. The following code sets the BackColor and ForeColor properties:


C# Listbox background color
listBox1.BackColor = System.Drawing.Color.Aqua; listBox1.ForeColor = System.Drawing.Color.Black;

How to clear all data in a listBox?

Listbox Items.Clear() method clear all the items from ListBox.

private void button1_Click_1(object sender, EventArgs e) { listBox1.Items.Clear(); }

ListBox.ClearSelected Method Unselects all items in the ListBox.

// Clear all selections in the ListBox. listBox1.ClearSelected();

Remove item from Listbox

public void RemoveAt (int index);

RemoveAt method removes the item at the specified index within the collection. When you remove an item from the list, the indexes change for subsequent items in the list. All information about the removed item is deleted.

Listbox Vs ListView Vs GridView

C# ListBox has many similarities with ListView or GridView (they share the parent class ItemsControl), but each control is oriented towards different situations. ListBox is best for general UI composition, particularly when the elements are always intended to be selectable, whereas ListView or GridView are best for data binding scenarios, particularly if virtualization or large data sets are involved. One most important difference is listview uses the extended selection mode by default .