The ListBox control is used to give the user a set of items to select from. You may give the user the ability to select just one item or multiple items. As you might have seen before, many of the ASP.NET controls that you place on web pages have a collection of items (as an Item property), such as the ListBox control, the DropDownList control and others. Having a collection of items give you the ability to use the familiar and common methods of collections like Add() and Remove() on that collection; you can also use the foreach statement if your situation requires that.
The best way to explain how you can create, use, and understand this control is by example. Let's start with a simple example, in which we will be adding the items we want to have in the ListBox using the Properties window at design time.
Start by creating a new website, and then drag a ListBox control to the Default.aspx page from the Toolbox as shown in the screen shot below.
The ListBox control will be added to the page with its task menu displayed as shown next. The task menu is a new feature in ASP.NET 2.0 which you will find with many controls. It gives you a list of the operations you can perform on the control or the features you can set on the control.
Now we need to add a few items so click on Edit Items from the task menu
The ListItem Collection Editor is shown above. To add an item you need to click on the Add button, which provides you with text boxes to enter the list item text and value as shown in the next screen shot. Type Mick Joseph in the Text property, 10 in the Value property and True for the Selected property.
Now click on the add button to add this item. The markup of the control looks like the following after adding one item.
<asp:ListItem Value="13">Mark Roberts </asp:ListItem>
<asp:ListItem Value="14 ">Paul Bill </asp:ListItem>
</asp:ListBox>
As you can see in the markup, the list items are added as child elements to the ListBox control. If you run the page you would get the following HTML code for this control:
The ListBox control has been rendered as an html <select> element.
The items you have added to the ListBox control are actually added to its Items property which is of type ListItemCollection. The ListItemCollection stores objects of type ListItem; that's why you see the elements <asp:ListItem> that represent each item in the list.
Let's try another example that adds those items programmatically in the Page_Load() event handler method.
Delete this ListBox control and add another one to the page, or simply clear out the ListItem elements of the control's markup. Check the Enable AutoPostBack checkbox from the task menu as shown in the next screen shot.
Also set the Width and Height of the ListBox Control through the Properties window (or you can do it through the markup code) as shown below.
Write the following code in the Page_Load() event handler method.
// checking if this page is loading for the first item or it's
// postback. If it's not a postback and the page is loading for
// the first time then we populate the ListBox control with the
// Listitem objects and if it's a PostBack we simply do nothing
if (!IsPostBack)
{
//creating the ListItem objects
ListItem firstItem = new ListItem();
firstItem.Text = "Mick Joseph";
firstItem.Value = "10";
ListItem secondItem = new ListItem();
secondItem.Text = "Mary Johnson";
secondItem.Value = "11";
ListItem thirdItem = new ListItem();
thirdItem.Text = "David Johnson";
thirdItem.Value = "12";
ListItem FourthItem = new ListItem();
FourthItem.Text = "Mark Roberts";
FourthItem.Value = "13";
ListItem FifthItem = new ListItem();
FifthItem.Text = "Paul Bill";
FifthItem.Value = "14";
// adding the ListItem objects to the Item collection of the
ListBox Control
ListBox1.Items.Add(firstItem);
ListBox1.Items.Add(secondItem);
ListBox1.Items.Add(thirdItem);
ListBox1.Items.Add(FourthItem);
ListBox1.Items.Add(FifthItem);
And the markup of the ListBox control looks like this:
When you run the page you can select another item and the page will post back to the server. For now we don't do anything when posting back. The page looks like the following screen shot:
Next we'll take a look at what we just did with the above code.
As we observed before, the ListBox control has a collection of list items. The items presented by the ListBox control are instances of the ListItem class. The ListItem class is used by other controls, such as the DropDownList and the RadioButtonList controls, to represent a list item and the associated value for that item. The text of a ListItem instance is represented by the ListItem.Text property and the value associated with the item is represented by the ListItem.Value property.
Usually, this value represents something important to the application and may not be important for the user, or the user doesn't really care about this value. For example, say that you are retrieving an employee id and employee name from the database and populating a ListBox control. You would associate the employee id (through the ListItem.Value) with the employee name (through the ListItem.Text) so the user would see the employee names in the list. When he selects an employee, however, you can do your work using the employee id instead of the employee name by retrieving the Value property of the selected list item.
In the previous section, we created five ListItem objects, and then we assigned string values to both the ListItem.Text and ListItem.Value properties. Finally, we added those objects to the ListBox control by using the Add() method of the Items Property of the ListBox control. You will find this pattern in many of the controls in the .NET Framework, where you use the Add() method of a property of a collection type to add items to the control. In our case, the ListBox.Items property is of type ListItemCollection, which means that you can use common collection's methods like Add() or Remove() to add or remove items from a ListBox control, and that you can use a foreach statement to iterate over the ListItem objects of the ListBox.Items ListItemCollection property.
You can think of the Items property as a reference to the ListItemCollection of the ListBox control you are working on; that's why you can call the ListItemCollection.Add() method to add a new list item to the control. If you are not familiar with C# Collections, you must consult other articles about this subject, because it's very important to understand what collections are and how they work.
The above code could also have been written as follows:
// checking if this page is loading for the first item or it's
// postback. If it's not a postback and the page is loading for
// the first time then we populate the ListBox control with the
// Listitem objects and if it's a PostBack we simply do nothing
if (!IsPostBack)
{
//creating the ListItem objects and assigning the
// Text and Value Properties through the Constructor
ListItem firstItem = new ListItem("Mick Joseph", "10");
ListItem secondItem = new ListItem("Mary Johnson", "11");
ListItem thirdItem = new ListItem("David Johnson", "12");
ListItem FourthItem = new ListItem("Mark Roberts", "13");
ListItem FifthItem = new ListItem("Paul Bill", "14");
// adding the ListItem objects to the Item collection of the
ListBox Control
ListBox1.Items.Add(firstItem);
ListBox1.Items.Add(secondItem);
ListBox1.Items.Add(thirdItem);
ListBox1.Items.Add(FourthItem);
ListBox1.Items.Add(FifthItem);
}
This code uses the ListItem's Constructor that accepts two string values. The first is the Text of the ListItem and the second is the Value of the ListItem.
We can enable multiple selections using the ListBox.SelectionMode property which accepts values from the ListSelectionMode enumeration. The enumeration has two values, single and multiple. Let's see an example. First, enable Multiple Selection through the Properties Window as shown below.
Add a Label control to the page. Now the code looks like this:
// checking if this page is loading for the first item or it's
// postback. If it's not a postback and the page is loading for
// the first time then we populate the ListBox control with the
// Listitem objects and if it's a PostBack we simply do nothing
if (!IsPostBack)
{
// using a for statement to add ListItem objects to the ListBox control
for (int i = 1; i <= 10; i++)
{
ListItem item = new ListItem();
item.Text = "Item Number " + i.ToString();
item.Value = i.ToString();
ListBox1.Items.Add(item);
}
}
// looping through the ListBox.Items collection property
// to get the value of every ListItem.Selected property
// if it's true we will display that ListItem.Text in the Label Control
foreach (ListItem item in ListBox1.Items)
{ if (item.Selected)
Label1.Text += "<br />" + item.Text;
}
}
If you run the page you will be able to select multiple items by holding down the Shift Key and selecting the items. Each time the page posts back and the Label control prints out the selected ListItems (through using the ListItem.Text property).
In the page_Load() event handler we use a for statement to populate the ListBox control with items. Inside each iteration we instantiate a ListItem object and assign its Text property through concatenating the string "Item Number" to the value of the variable i. We also have assigned the value of the variable i to the ListItem.Value property. Before we end the iteration we add the ListItem to the ListBox.Items collection property through the use of ListBox.Items.Add() method.
We have placed this code inside an if statement that checks if this page is a post back or not. I think that by now you understand that we place code that populates controls inside an if statement that checks for the IsPostback property, because we depend on the ASP.NET ViewState capabilities to preserve the control's state across multiple postbacks.
The next block is the foreach statement. It is used to loop through a collection of objects. The object in a specific iteration is available inside the block. We simply check the value of the Selected property, which returns true or false, for every ListItem object in the ListBox.Items collection property. If it's true then this means that this ListItem is selected; if so we add the ListItem.Text property's value to Label.Text property. Also note that we have disabled the ViewState on the Label control because if we didn't disable it we would get a big string value in the Label.Text property that contains the selected items from this postback and for all the previous postbacks.
The following screen shot is taken before disabling the ViewState of the Label control. By selecting only the first three items we have all these entries in the Label.Text property.
You can also connect the ListBox control to a database to retrieve data. You can do this through ADO.NET code or by using a DataSource control like the SqlDataSource control.
Click on Choose Data Source from the task menu of the ListBox control. The Data Source Configuration Wizard window will be displayed. From the DropDownList "Select a Data Source" choose <New Data Source> and you will be taken to the next screen shot where you can select the data source to which you are connecting.
Select database and note that the SqlDataSource1 is given as an ID for the SqlDataSource control. When you connect to a database the SqlDataSource control is used and this is its id.
Click on OK and you will be taken to the wizard where you will configure your newly added SqlDataSource control. Now you can select a Connection that the SqlDataSource control will use to communicate with the database. We didn't add any connections so click on New Connection button and you will get the following screen shot:
Choose Microsoft SQL Server as your Data Source, then click Continue. Select your Server name (if you are connecting to your local server then you can type (local) as shown in the next screen shot) and Pubs as the database, and then click on Test Connection. If you have entered correct information you will get the following screen shot:
Now that the connection is good and working click on OK, and then click OK again on the Add Connection dialog. You will be taken back to the SqlDataSource configuration wizard. The connection has been set so click Next.
Now you are asked if you want to store the Connection String to the application's Configuration file; leave the check box checked because we want this behavior. Click on Next again; after the connection we have the command. Now you can select the fields you want to retrieve from the database. We need to write a custom T-SQL Query for this example so click on Specify a Custom SQL Statement and write the following query: SELECT au_id, au_lname + ' '+ au_fname AS full_name FROM authors
Click Next and you can test the query if you want to by clicking on Test Query. Now click on the Finish button. You will be taken back to the first wizard you started with. Now that we have a data source set up, by using the SqlDataSource control, we can select which field will be used as the ListItem.Text and which will be used as ListItem.Value. Of course we will select au_id for the Value and full_name for the Text as shown in the next screenshot.
Click on OK then run the page and you will get those values from the database table to the ListBox control without writing a single line of code. Please consult my articles about ADO.NET and SqlDataSource for more information and examples about using the ListBox control, creating database connections and executing T-SQL statements against a database table.