Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Windows Controls C# » ListBox in C#

ListBox in C#

In this tutorial, we will learn how to create a ListBox control at design-time as well as at run-time. We will also see how to create multiple columns ListBox control with single and multiple selections. This article also covers most of the properties and methods of the ListBox control.

Author Rank :
Page Views : 18143
Downloads : 207
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ListBoxSampleCSharp.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


ListBox in C#

A ListBox control provides an interface to display a list of items. Users can select one or multiple items form 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 ListBox control at design-time as well as at run-time. We will also see how to create multiple columns ListBox control with single and multiple selections. This article also covers most of the properties and methods of the ListBox control. 

Creating a 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.

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 and drop a ListBox control from Toolbox to a Form in Visual Studio. After you drag and drop a ListBox on a Form, the ListBox looks like Figure 1. Once a ListBox is on the Form, you can move it around and resize it using mouse and set its properties and events.

ListBoxImg1.jpg
Figure 1

Run-time

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 ListBox object to the Form controls.

First step to create a dynamic ListBox is to create an instance of ListBox class. The following code snippet creates a ListBox control object.

ListBox listBox1 = new ListBox();

 

In the next step, you may set properties of a ListBox control. The following code snippet sets location, width, height, background color, foreground color, Text, Name, and Font properties of a ListBox.

listBox1.Location = new System.Drawing.Point(12, 12);

listBox1.Name = "ListBox1";

listBox1.Size = new System.Drawing.Size(245, 200);

listBox1.BackColor = System.Drawing.Color.Orange;

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 Form.Controls.Add method that adds ListBox control to the Form controls and displays on the Form based on the location and size of the control. The following code snippet adds a ListBox control to the current Form.

 

Controls.Add(listBox1);

Setting ListBox Properties

The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 2.

ListBoxImg2.jpg
Figure 2

Name

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.

listBox1.Name = "ListBox1";

Location, Height, Width and Size

The Location property takes a Point that specifies the starting position of the ListBox on a Form. You may also use Left and Top properties to specify the location of a control from the left top corner of the Form.  The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a ListBox control.

listBox1.Location = new System.Drawing.Point(12, 12);

listBox1.Size = new System.Drawing.Size(245, 200);

Font

Font property represents the font of text of a ListBox control. If you click on the Font property in Properties window, you will see Font name, size and other font options. The following code snippet sets Font property at run-time.

listBox1.Font = new Font("Georgia", 16);

Background and Foreground

BackColor and ForeColor properties are used to set background and foreground color of a ListBox respectively. If you click on these properties in Properties window, the Color Dialog pops up.

Alternatively, you can set background and foreground colors at run-time. The following code snippet sets BackColor and ForeColor properties.

listBox1.BackColor = System.Drawing.Color.Orange;

listBox1.ForeColor = System.Drawing.Color.Black;

 

The new ListBox with background and foreground looks like Figure 3.

 

ListBoxImg3.jpg
Figure 3

You can also set 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 border style is Fixed3D. The following code snippet sets the border style of a ListBox to FixedSingle.
 

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 Properties Window by clicking on 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 like Figure 6.

ListBoxImg6.jpg
Figure 6

You can add same items at run-time by using the following code snippet.

listBox1.Items.Add("Mahesh Chand");

listBox1.Items.Add("Mike Gold");

listBox1.Items.Add("Praveen Kumar");

listBox1.Items.Add("Raj Beniwal");

Getting All Items

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 in a MessageBox.

private void GetItemsButton_Click(object sender, EventArgs e)

{

    System.Text.StringBuilder sb = new System.Text.StringBuilder();

    foreach (object item in listBox1.Items)

    {

        sb.Append(item.ToString());

        sb.Append(" ");

    }

    MessageBox.Show(sb.ToString());

}

Selected Text and Item

Text property is used to set and get text of a ListBox. The following code snippet sets and gets current text of a ListBox.

MessageBox.Show(listBox1.Text);

 

We can also get text associated with currently selected item by using Items property.

string selectedItem = listBox1.Items[listBox1.SelectedIndex].ToString();

Why the value of ListBox.SelectedText is Empty?
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, the value of SelectedText will be an empty string. To get current text in a ListBox when it does not have focus, use Text property.

Selection Mode and Selecting Items
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 item index and a true or false value where true value represent the item to be selected.
The following code snippet make a ListBox multiple selection and selects second and third item in the list.

listBox1.SelectionMode = SelectionMode.MultiSimple;

listBox1.SetSelected(1, true);

listBox1.SetSelected(2, true);

We can clear all selected items by calling ClearSelected method.

listBox1.ClearSelected();

How to disable item selection in a ListBox?
Just set SelectionMode property to None.

Sorting Items

The Sorted property set to true, the ListBox items are sorted. The following code snippet sorts the ListBox items.

listBox1.Sorted = true;

Find Items

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.

private void FindItemButton_Click(object sender, EventArgs e)

{

    listBox1.ClearSelected();

 

    int index = listBox1.FindString(textBox1.Text);

 

    if (index < 0)

    {

        MessageBox.Show("Item not found.");

        textBox1.Text = String.Empty;

    }

    else

    {

        listBox1.SelectedIndex = index;

    }

}

 

ListBox SelectedIndexChanged Event Hander

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 on Event icon and double click 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 event at run-time.

 

listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);

 

 

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)

{

    MessageBox.Show(listBox1.SelectedItem.ToString());

}

 

Now every time you change the selection in the ListBox, you will see the selected item displayed in a MessageBox.

 

Data Binding
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.

private void DataBindingButton_Click(object sender, EventArgs e)

{

    ArrayList authors = new ArrayList();

    authors.Add("Mahesh Chand");

    authors.Add("Mike Gold");

    authors.Add("Raj Kumar");

    authors.Add("Praveen Kumar");

 

    listBox1.Items.Clear();

    listBox1.DataSource = authors;

}

If you are binding an object with multiple properites, you must specify which property you are displaying by using the DisplayMember property.

listBox1.DataSource = GetData();

listBox1.DisplayMember = "Name";

 

Summary

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

Further Readings
Here are some more articles and tutorials in ListBox that you may want to read.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Surely This Article Will Help the Beginners by Manikavelu On August 31, 2010

Excellent article about List box. Top to bottom of Listbox is discussed here.

Reply | Email | Modify 
how to assign items value for each item and retrieve item with that value by Vishnu On February 4, 2011
hi, i am vishnu. i am an amatuer. please provide me help. how to assign items value for each item and retrieve item with that value
Reply | Email | Modify 
Deserve a Salute... by Sabraz Nawaz On April 12, 2011
Dear Mr. Mahesh, The service that you have rendered in this site with your amazingly composed articles cannot be compared with any others' works on the net, to be honest. From novice to advance, you have drawn a track to set foot on the way to C#... definitely deserve a salute sir. S. Sabraz Nawaz, Lecturer in MIT South Eastern University of Sri Lanka. sabraz@seu.ac.lk
Reply | Email | Modify 
Appreciate by Mahesh On April 12, 2011
I appreciate your kinds comments. Thank you!
Reply | Email | Modify 
Mindcracker MVP Summit 2012
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.