Using ASP.NET List Controls

potpiedicedInternet and Web Development

Jul 5, 2012 (5 years and 3 months ago)

282 views

Using ASP.NET List Controls
Kevin Marshall

Using ASP.NET List Controls

This tutorial will explain how to correctly use the ASP.NET List Controls. These comprise of three types of
control, DropDownList, ListBox and HTMLSelect. During the course of this tutorial you will learn how to bind
dynamic data such as Database contents and how these controls can interact with events and other
controls on your page. A common problem associated with using these controls in Dreamweaver where the
selected item often ends up being the first item in the list after a postback is solved. How to manually insert,
delete and pre-select items in a list controls is also shown.

• An introduction to the available list controls
• An introduction to the ListItem class
• The DropDownList Control
• The ListBox Control
• The HTMLSelect Control
• Defining the items of a list control
• Programmatically Adding items to a list control
• Programmatically Inserting items into a list control
• Programmatically Selecting items in a list control
• Programmatically Removing items from a list control
• Binding Database content to a list control
• Binding collections (Arrays) to a list control
• A Common problem and solution
An introduction to the available list controls
There are three list controls built into the .NET Framework, these are:

• System.Web.UI.WebControls.DropDownList
this control renders a drop-down list in the page at runtime. Only the selected item is visible when the
user is not interacting with the list, and the other items become visible when the user clicks the control
to see the items that can be selected. Only one item can be selected in this control. This control must
be inserted into a server side form (runat="server") applied.



Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 1 of 13
Using ASP.NET List Controls
Kevin Marshall

• System.Web.UI.WebControls.ListBox
this control renders a list of items within a scrolling box, multiple items can be selected in this control if
required. This control must be inserted into a server side form (runat="server") applied.



• System.Web.UI.HTMLControls.HTMLSelect
this control can be used to render a drop-down list or a scrolling list of items. This control has less built
in functionality when compared with controls above (It lacks many of the properties that can be
used to influence the display style such as ForeColor and BackColor to name a couple) ,but it is still
capable of performing most common uses of a list control. This control can be inserted anywhere,
and does not require a server side form.


An introduction to the ListItem class
All of the mentioned list controls contain a property called Items; this property is a collection property
containing all of the items in the list. Each item in the list is an instance of the ListItem class, which contains
the following properties:

• Text
this represents the text displayed for the item in the list.

• Value
this represents the value displayed for the item in the list.

• Selected
this represents whether the item is selected or not.

A ListItem is rendered as an <option> tag in the HTML output - for example a ListItem with a value of "Item 1"
for its Text property and "1" for its Value property would result in the following HTML within the list:

<option value="1">Item 1</option>

It's possible to loop through all the ListItems in the Items property using the following code. Please note this is
assuming a non-existent list control LstCtl and is only an example of how it's done.

Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 2 of 13
C#
Using ASP.NET List Controls
Kevin Marshall

for(int i=0; i<LstCtl.Items.Count; i++)
{
Response.Write(LstCtl.Items[0].Text)
}

VB
Dim i As Integer
For i = 0 To LstCtl.Items.Count - 1
Response.Write(LstCtl.Items[0].Text)
Next

Or if you prefer a more object-oriented approach, the following code does precisely the same as the
previous code and is more readable, but not as efficient because an object reference variable is created
and is then changed on each pass though the loop. (The difference is not going to be noticeable with only
a few items in the list, but thousands of items would make the performance difference noticeable.)

C#
foreach(ListItem Lst in LstCtl.Items)
{
Response.Write(Lst.Text)
}

VB
Dim Lst As ListItem
For Each Lst In LstCtl.Items
Response.Write(Lst.Text)
Next
The DropDownList Control
The DropDownList control is used to provide a selectable list of options for the user to select from. It contains
many properties that you can use to populate its Items collection and affect how it functions on the page.
The most common properties are:

• AutoPostBack
This is a bool/Boolean value used to control whether the DropDownList causes a post back of the
page as soon as the user changes the SelectedItem. Be careful if you use this with a ListBox or an
HtmlSelect showing more than one ListItem, as it can make the page end up as an accessibility and
usability nightmare, because the Onchange event fires each time the user selects a different option,
so a user without a mouse (using the arrow keys) can never get further than one item away from the
default before the automatic Postback.

A drop down is dropped down in a way that the user can move through the options fine using the
arrow keys; the page does not post back till the enter key is pressed or you tab away from the
control. (For more information on accessibility, see the
Forms and Accessibility
tutorial and others in
the
Accessibility and Web Standards category
).

• DataSource
This is used to define a dynamic DataSource used to populate the Items collection, typically the most
common type of DataSource used is a DataSet but others types such as collection types are also
supported.

• DataTextField
This is used to specify which field of the DataSource should be used for the Text property of each
Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 3 of 13
Using ASP.NET List Controls
Kevin Marshall

ListItem displayed in the list.

• DataValueField
This specifies which field of the DataSource should be used for the Value property of each ListItem
displayed in the list.

• Items
this is the collection of ListItems. Using this property you can access/edit each of the ListItems in the
list.

• SelectedItem
This represents the currently selected ListItem of the list. This property itself has its own properties, Text
and Value which can be used to find out more about which option the user has selected.

The DropDownList control is inserted into the page using a server control tag, a simple example of which is
shown below:

<asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>

When the page is viewed in a browser the following HTML is output by the control:

<select name="DropDownList1" id="DropDownList1">
</select>

This simple example shows a DropDownList without any ListItems for now.
The ListBox Control
The ListBox control is used to provide a selectable list of options for the user to select from, multiple items can
be selected in a ListBox, and the ListBox contains the same properties as DropDownList. The main difference
is the Rows property which is used to specify how many ListItems are visible; other ListItems not visible can be
scrolled into view.

The ListBox control is inserted into the page using a server control tag, a simple example is shown below:

<asp:ListBox id="ListBox1" Rows="5" runat="server"></asp:ListBox>

When the page is viewed in a browser the following HTML is output by the control:

<select name="ListBox1" size="5" id="ListBox1">
</select>

This simple example shows a ListBox without any ListItems for now, the thing to note is the use of the Rows
property affects the size attribute of the rendered <select> tag.
The HTMLSelect Control
The HTMLSelect control is used to provide a selectable list of options for the user to select from; multiple items
can be selected in an HTMLSelect if the multiple attribute is defined. The HTMLSelect contains all of the
previously mentioned properties as DropDownList and ListBox with the exception of AutoPostBack.

Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 4 of 13
Using ASP.NET List Controls
Kevin Marshall

The HTMLSelect control is inserted into the page using a normal <select> tag with the runat="server" attribute
applied, a simple example is shown below:

<select id="Select1" runat="server"></select>

When the page is viewed in a browser the following HTML is output by the control:

<select name="Select1" id="Select1">
</select>

This simple example shows an HTMLSelect without any ListItems for now, note how the name attribute is
assigned the same value as the id attribute if it's not already defined.
Defining the items of a list control
There are many ways to populate a list control with ListItems. You can hard code them as nested tags of the
main List Control tag, you can insert then programmatically or you can bind dynamic data from a
DataSource to the list. First we will look at hard coding them.

The following example of a DropDownList Server control tag defines five ListItems; the third item is defined as
being pre-selected by setting its Selected property.

Example 1
<asp:DropDownList id="DropDownList1" runat="server">
<asp:ListItem Value="1">Item 1</asp:ListItem>
<asp:ListItem Value="2">Item 2</asp:ListItem>
<asp:ListItem Value="3" Selected="True">Item 3</asp:ListItem>
<asp:ListItem Value="4">Item 4</asp:ListItem>
<asp:ListItem Value="5">Item 5</asp:ListItem>
</asp:DropDownList>

The following HTML <select> element is outputted by the control when the page is viewed in a browser.

<select name="DropDownList1" id="DropDownList1">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3" selected="selected">Item 3</option>
<option value="4">Item 4</option>
<option value="5">Item 5</option>
</select>

The list will look similar to the following image when viewed in a browser.

Please note the styling shown in this image is down to the page being viewed on a Windows XP machine, if
you're not using Windows XP yours will not look exactly like this so don't panic, there is nothing wrong with
your page.
Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 5 of 13
Using ASP.NET List Controls
Kevin Marshall

Programmatically Adding items to a list control
You can add new ListItems to the Items collection of a List Control from your server side code. This example
shows the code required to insert a new ListItem into the DropDownList of the previous example.

Example 2
C#
DropDownList1.Items.Add(new ListItem("Item 6", "6"));

VB
DropDownList1.Items.Add(New ListItem("Item 6", "6"))

This line of code uses the Add method of the Items property and passes a new ListItem as the argument
which is created with the new constructor. The Text and Value properties for the new ListItem are passed as
arguments of the constructor.
Programmatically Inserting items into a list control
As the previous example shows, adding new ListItems to the Items collection of a List Control is relatively
straightforward. One gotcha is that they always get added to the end of the collection. What if you want to
have the new item as the first in the list or even in the middle? This can be achieved using the Insert method
of the Items property and is shown in example 3:

Example 3
C#
DropDownList1.Items.Insert(4, new ListItem("Please Select", ""));

VB
DropDownList1.Items.Insert(4, New ListItem("Please Select", ""))

This is very similar to the previous example using the Add method, but when using the Insert method there are
two arguments required - the first is the ordinal position in the list to insert the new ListItem, the second
argument is the new ListItem to insert. This example inserts it at position 5.
Programmatically Selecting items in a list control
You can pre-select ListItems to in a List Control from your server side code by setting the desired ListItem's
Selected property to true; the following example shows this in action.

Edit the DropDownList tag to remove the Selected="True" attribute; this is marked in bold in the following
code.

<asp:DropDownList id="DropDownList1" runat="server">
<asp:ListItem Value="1">Item 1</asp:ListItem>
<asp:ListItem Value="2">Item 2</asp:ListItem>
<asp:ListItem Value="3" Selected="True">Item 3</asp:ListItem>
<asp:ListItem Value="4">Item 4</asp:ListItem>
<asp:ListItem Value="5">Item 5</asp:ListItem>
</asp:DropDownList>

The Code should now look like the following code.

<asp:DropDownList id="DropDownList1" runat="server">
<asp:ListItem Value="1">Item 1</asp:ListItem>
<asp:ListItem Value="2">Item 2</asp:ListItem>
Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 6 of 13
<asp:ListItem Value="3">Item 3</asp:ListItem>
Using ASP.NET List Controls
Kevin Marshall

<asp:ListItem Value="4">Item 4</asp:ListItem>
<asp:ListItem Value="5">Item 5</asp:ListItem>
</asp:DropDownList>

The following code shows how to pre-select that same ListItem programmatically.

Example 4
C#
DropDownList1.Items[2].Selected = true;

VB
DropDownList1.Items(2).Selected = True

You may find yourself having to do it from code in this manner when the list items themselves have not been
hard-coded but are populated dynamically, you can't manually add the Selected attribute in this scenario.

It worth pointing out that the Items Collection is zero based, this means that the first Item is not at position 1
but is in fact found at position 0; position 1 contains the second ListItem.
Programmatically Removing items from a list control
You can remove ListItems from List Control using server side code; this involves using the RemoveAt method
of the Items property, this is shown in the following example.

Example 5
C#
DropDownList1.Items.RemoveAt(2);

VB
DropDownList1.Items.RemoveAt(2)


This line is removing the third (zero based remember) ListItem from the list.

This may not be of much use in a dynamically filled List Control because you can't be expected to know
beforehand the index number of each ListItem in the list. For example, if you wanted to remove a ListItem
that has the Text value of "Item 3" you need to find the index number of that item. The following code shows
how this can be done.

Example 6
C#
for(int i=DropDownList1.Items.Count-1; i>-1; i--)
{
if(DropDownList1.Items[i].Text == "Item 3")
{
DropDownList1.Items.RemoveAt(i);
break;
}
}

VB
Dim i As Integer
For i = DropDownList1.Items.Count - 1 To 0 Step -1
If DropDownList1.Items(i).Text = "Item 3" Then
DropDownList1.Items.RemoveAt(i)
Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 7 of 13
Using ASP.NET List Controls
Kevin Marshall

Exit For
End If
Next

Each line of this example is explained on an individual basis below:

VB
Dim i As Integer
This VB line declares an integer variable called i that will be used when looping through the ListItems in the
Items collection.

C#
for(int i=DropDownList1.Items.Count-1; i>-1; i--)

VB
For i = DropDownList1.Items.Count - 1 To 0 Step -1
This line begins a for loop to loop through the Items collection. The loop starts on the last ListItem and loop
backwards from there to the first item. The reason for this is when you delete an item from a collection
you'recurrently looping through, an error will occur due to possibility of the loop continuing past the new
collection count (this changes when you remove an item); by looping backwards this is not a problem.

C#
if(DropDownList1.Items(i).Text == "Item 3)
DropDownList1.Items.RemoveAt(i);
break;

VB
If DropDownList1.Items(i).Text = "Item 3" Then
DropDownList1.Items.RemoveAt(i)
Exit For
Within each pass through the loop, the Text value of the current ListItem is checked to see if it equals "Item 3".
If it does, the items is removed using the RemoveAt method, passing the index number to remove using the i
variable as an argument. Once the ListItem is removed the break (Exit For in VB) is called to exit the loop, as
there is no point continuing if our work here is already done.
Binding Database content to a list control
Now we will look at how you can bind List Controls to dynamic data such as Databases and Arrays. For the
Database example, you will need a copy of the Northwinds Traders MS Access Database, if you don't
already have this it can be downloaded for free at the following URL:

http://www.microsoft.com/downloads/details.aspx?FamilyID=C6661372-8DBE-422B-8676-
C632D66C529C&displaylang=EN


The first example will fill the DropDownList with content from the Database; you will have to change the
DropDownList tag again this time removing all the hard coded ListItems as shown below:

<asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>

The following code block connects to the database and fills the dropdown list with a list of employee names
from the Employees table.
Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 8 of 13
Using ASP.NET List Controls
Kevin Marshall



Example 7
C#
if(!Page.IsPostBack)
{
OleDbConnection Conn;
OleDbCommand Cmd;
Conn = new OleDbConnection("Connection String");
Cmd = new OleDbCommand("SELECT EmployeeID,LastName FROM Employees", Conn);
Conn.Open();
DropDownList1.DataSource = Cmd.ExecuteReader();
DropDownList1.DataTextField = "LastName";
DropDownList1.DataValueField = "EmployeeID";
DropDownList1.DataBind();
Conn.Close();
}

VB
If Not Page.IsPostBack Then
Dim Conn As OleDbConnection
Dim Cmd As OleDbCommand
Conn = New OleDbConnection("Connection String")
Cmd = New OleDbCommand("SELECT EmployeeID,LastName FROM Employees", Conn)
Conn.Open()
DropDownList1.DataSource = Cmd.ExecuteReader()
DropDownList1.DataTextField = "LastName"
DropDownList1.DataValueField = "EmployeeID"
DropDownList1.DataBind()
Conn.Close()
End If

Now each line if the code will be explained in greater detail.

C#
if(!Page.IsPostBack)

VB
If Not Page.IsPostBack Then
This line checks to make sure the page is not the result of a PostBack, as we only want to fill the list the first
time the page loads as subsequently, the ListItems will be preserved on PostBack.

C#
OleDbConnection Conn;
OleDbCommand Cmd;

VB
Dim Conn As OleDbConnection
Dim Cmd As OleDbCommand
These two lines are declaring OleDbConnection and OleDbCommand object variables that we'll use.



C#
Conn = new OleDbConnection("Connection String");
Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 9 of 13

Using ASP.NET List Controls
Kevin Marshall

VB
Conn = New OleDbConnection("Connection String")
This line creates an OleDbConnection object that connects to the database. "Connection String" should be
changed to a valid connection string for the database being used, for example to connect to your
northwinds access database if you saved it to the location of "c:\mysite\Db" you would use the following
connection string:

C#
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\mysite\\Db\\NWIND.MDB;Persist Security
Info=False

VB
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mysite\Db\NWIND.MDB;Persist Security
Info=False
An alternative method is to store this connection string in the sites web.config file so it's easily accessible to all
the pages in your site. This is done by placing the following keys into your web.config file:

<configuration>
<appSettings>
<add key="ConnStr" value=" Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\mysite\Db\NWIND.MDB;Persist Security Info=False" />
</appSettings>
</configuration>

The "Connection String" part of our database connection line could now be changed to:

C#
Configuration.ConfigurationSettings.AppSettings["ConnStr"]

VB
Configuration.ConfigurationSettings.AppSettings.Item("ConnStr")

C#
Cmd = new OleDbCommand("SELECT EmployeeID,LastName FROM Employees", Conn);

VB
Cmd = New OleDbCommand("SELECT EmployeeID,LastName FROM Employees", Conn)
This line creates a new OleDbCommand object and assigns it to the Cmd object variable. The
OleDbCommand constructor accepts two arguments, the first is the SQL query to execute and the second is
the OleDbConnection object to use.

C#
Conn.Open();

VB
Conn.Open()
This line opens the OleDbConnection (connects to the database).

C#
DropDownList1.DataSource = Cmd.ExecuteReader();

VB
DropDownList1.DataSource = Cmd.ExecuteReader()
Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 10 of 13
Using ASP.NET List Controls
Kevin Marshall

This line sets the DataSource of our DropDownList to the return value of the call to OleDbCommand's
ExecuteReader method which returns an OleDbDataReader object which is used to loop through the results
returned from executing the SQL query on the database.

C#
DropDownList1.DataTextField = "LastName";
DropDownList1.DataValueField = "EmployeeID";

VB
DropDownList1.DataTextField = "LastName"
DropDownList1.DataValueField = "EmployeeID"
These two lines are used to define which field values from the database are used for the Text and Value
properties of the ListItems.

C#
DropDownList1.DataBind();

VB
DropDownList1.DataBind()
This line called the DataBind method of the DropDownList which actually takes the data and inserts the
ListItems.

C#
Conn.Close();

VB
Conn.Close()
This line closes the database connection.
Binding collections (Arrays) to a list control
You can also bind the contents of a collection (array) to List Controls; the following example shows an
ArrayList being created and filled with elements. The contents of the ArrayList is then bound to the
DropDownList.

Example 8
C#
ArrayList MyArray = new ArrayList();
MyArray.Add("Item 1");
MyArray.Add("Item 2");
MyArray.Add("Item 3");
MyArray.Add("Item 4");
MyArray.Add("Item 5");

DropDownList1.DataSource = MyArray;
DropDownList1.DataBind();

VB
Dim MyArray As New ArrayList
MyArray.Add("Item 1")
MyArray.Add("Item 2")
MyArray.Add("Item 3")
MyArray.Add("Item 4")
MyArray.Add("Item 5")

Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 11 of 13
DropDownList1.DataSource = MyArray
Using ASP.NET List Controls
Kevin Marshall

DropDownList1.DataBind()

Now each line of the code will be explained in greater detail.

C#
ArrayList MyArray = new ArrayList();

VB
Dim MyArray As New ArrayList
This line creates a new ArrayList and assigns it to the MyArray object variable.

C#
MyArray.Add("Item 1");
MyArray.Add("Item 2");
MyArray.Add("Item 3");
MyArray.Add("Item 4");
MyArray.Add("Item 5");

VB
MyArray.Add("Item 1")
MyArray.Add("Item 2")
MyArray.Add("Item 3")
MyArray.Add("Item 4")
MyArray.Add("Item 5")
These lines add elements to the ArrayList using the Add method of the ArrayList.

C#
DropDownList1.DataSource = MyArray;

VB
DropDownList1.DataSource = MyArray
This line sets the ArrayList as DataSource of the DropDownList.

C#
DropDownList1.DataBind();

VB
DropDownList1.DataBind()
This line populates the DropDownList with the ArrayList contents.
A Common problem and solution
One of the most common problems I have observed Dreamweaver users complaining about is List Controls
not keeping the SelectedItem on a PostBack, exlaiming "It only returns the value of the first ListItem". The
reason for this is the method used by Dreamweaver to fill list controls is flawed. The DataSource of the List
Control is set using an expression on the List Controls tag, like the following example.

<asp:DropDownList
id="DropDownList1"
DataSource="<%# DataSet1.DefaultView %>"
DataTextField="LastName"
DataValueField="EmployeeID"
runat="server">
</asp:DropDownList>

Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 12 of 13
Using ASP.NET List Controls
Kevin Marshall

Copyright © 2004 DNzone.com All Rights Reserved
to get more go to DNzone.com
Page 13 of 13
What happened when you use this code it that the DataSource is evaluated each and every time the page
runs, and because the MM:DataSet control used by Dreamweaver always calls the page's DataBind method
regardless of whether the page is the result of a PostBack or not, so the List Control is re-bound every page
view – and this loses the SelectedItem. Understanding what causes the problem really helps you to work out
how to resolve it, don't worry if you haven't thought of the solution because here it is (drumroll!):

The Solution

Remove the DataSource attribute from the tag as shown below.

<asp:DropDownList
id="DropDownList1"
DataTextField="LastName"
DataValueField="EmployeeID"
runat="server">
</asp:DropDownList>

Then add the following code to the pages Page_Load procedure.

Example 9
C#
if(!Page.IsPostBack)
{
DropDownList1.DataSource = DataSet1.DefaultView;
DropDownList1.DataBind();
}

VB
If Not Page.IsPostBack Then
DropDownList1.DataSource = DataSet1.DefaultView
DropDownList1.DataBind()
End If
This code first checks that the page is not the result of a PostBack. If it is, nothing is done because re-binding
the DropDownList would lose the SelectedItem. If the page is not the result of a PostBack, but is in fact a fresh
load, then the DataSource of the DropDownList is set to the DataSet's Default view and its DataBind method
is called.

As you can see the solution to this common problem is simply moving the expression that sets the List Controls
DataSource out of the controls tag and into a conditional code block that only executes the first time the
page loads.
Summary
During the course of this tutorial you learned about the List Controls available and the differences between
them, you then learned how to fill these List Controls using various methods such as hard coding and
dynamically from a DataSource. You also learned how to Add, Insert, Select and Remove ListItems
programmatically. Finally you learned how to cure the common problem of the SelectedItem being lost on
PostBack caused by Dreamweavers implementation of List Controls.