How to Use the ListBox Control in ASP.NET 2.0

Any developer who is using the Listbox control in his applications needs to be aware of how data binding has changed from VS 2003 to ADO.NET 2.0. This article will explain the changes. It appears to be an improvement over the previous techniques used.

Introduction

While the concept of data binding has not changed, the mechanics and objects involved in data binding have changed from VS2003 (.NET Framework 1.1x) to ADO.NET 2.0. This can be easily seen by comparing the Toolbox items in VS2003 and VS2005 as shown in the next two pictures. The connection, command, transactions, parameters have been replaced by the DataSource Controls. The data binding in ASP.NET 2.0 relies on the data binding expressions and the data source controls. This tutorial is about the ListBox control and how it is bound to data. It should interest those who might be using ListBox Control in their applications. You will see for yourselves how much better off you will be using the Data Source Controls in ADO.NET 2.0.

VS 2003

VS 2005

ListBox Control

The ListBox control displays items in a list appearing sequentially and vertically in a scrollable window. It may display single or multiple items. It usually displays items by pulling the information from memory and formatting them according to the way they are requested. The ListBox control as seen in the Object Browser of VS 2005 has its inheritance as shown in the next paragraph.

Public Class ListBox Inherits System.Web.UI.WebControls.ListControl Member of: System.Web.UI.WebControls Summary: Represents a list box control that allows single or multiple item selection.

This inheritance is common to the other type of list controls as well, such as DropDownList, CheckBoxList, RadioButtonList and the BulletItemList which is new in VS 2005.

Because of this inheritance one can access a large number of properties, methods and events of the list controls in applications shown in the Object Browser.

The ListBox control has additional properties for setting its BorderColor, BorderStyle, and BorderWidth. Also it has some properties not available in other types of list controls, namely Rows and SelectionMode properties shown in the object browser.

{mospagebreak title=Usage of the ListBox Control in web pages}

In an earlier article on VS2003 an example of binding a ListBox control using a DataReader was shown. ListBox can be used to display not only data from a backend database but also other kinds of lists. ListBox events can then be used for displaying list-related information. The following examples use either simple lists or data from a backend database. In the case of a backend database, however, any of the data source controls can be used. For the examples shown an AccessDataSource Control in the VS 2005 IDE is chosen.

On Using the AccessDataSource Control

The AccessDataSource control takes you the very center of RAD. Writing code is almost reduced to a single line. No more connection strings that tangle here, there and everywhere. Most of what you want to do can be done at design time. The IDE even gives you a query editor. An earlier article shows how you may use this data source control with a large number of screen shots. A few major screen shots are shown here.

Step 1

You must first add a source to the data connection, which will add the nwind.mdb file on your local drive as shown in the Server Explorer window. In this picture it is shown as being refreshed.


Step 2

Next you bring the connection to the App_Data folder of your website. When this is accomplished your website should appear as shown in the following picture.

{mospagebreak title=ListBox Examples}

Simple List

This example shows filling a ListBox with several items at design time. The next picture shows the ListBox on the design pane filled in with three items. The List Items Collection Editor dialog can be popped up by clicking on an empty space in the items collection property in the List Box properties window shown in the same picture on its right. In this Editor you can begin adding items by providing Key/ Value pairs as shown  for "New Jersey."

Another way of doing this is to follow the ListBox tasks as shown in the next picture by clicking the smart tags arrow attached to the ListBox. This will be discussed later in the tutorial.

By using the SelectedIndexChanged event you may be able to write a code so that the Key Value of selected items is displayed in the textbox as shown in the following snippet.

Partial Class Simplelist
   Inherits System.Web.UI.Page

   Protected Sub ListBox1_SelectedIndexChanged(ByVal sender _
   As Object, ByVal e As System.EventArgs) Handles _
   ListBox1.SelectedIndexChanged
     TextBox1.Text = ListBox1.SelectedValue.ToString 
   End Sub
End Class

The source code for this  program (SimpleList.aspx) is shown in the following listing.

<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="Simplelist.aspx.vb" Inherits="Simplelist" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   <title>Simple List</title>
</head>
<body>
   <form id="form1" runat="server">
   <div> 
     <asp:ListBox ID="ListBox1" runat="server"
AutoPostBack="true" >
        <asp:ListItem Value="NJ">New Jersey</asp:ListItem>
        <asp:ListItem Value="C0">Colorado</asp:ListItem>
        <asp:ListItem Value="NY">New York</asp:ListItem>
     </asp:ListBox>
     <asp:TextBox ID="TextBox1" runat="server" Text=”>
     </asp:TextBox></div>
  </form>
</body>
</html>

The result of opening this page in the browser and selecting any of the list items will display its key value in the textbox as shown in the next picture.

The selected item is bound to a textbox with a Binding expression.

This example is similar to the previous one, but the Selected Item’s value is bound to the textbox with a binding expression as shown in the code used for the "text" property of the textbox. Adding items to the ListBox is similar to the previous example. The ListBox and the textbox are tied up in the form1_load() event as shown in the following snippet for the code behind for this page, BindingExp.aspx.

Partial Class BindingExp Inherits System.Web.UI.Page Protected Sub form1_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles form1.Load DataBind() End Sub End Class

The source code for this page (BindingExp.aspx) is shown in the following listing.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="BindingExp.aspx.vb" Inherits="BindingExp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   <title>Bound List</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
     <asp:ListBox ID="ListBox1" runat="server"
AutoPostBack="true">
       <asp:ListItem Value="57">John</asp:ListItem>
       <asp:ListItem Value="35">Tom </asp:ListItem>
       <asp:ListItem Value="22">Lisa</asp:ListItem>
     </asp:ListBox>
     <asp:TextBox ID="TextBox1" runat="server" Text="<%#
ListBox1.SelectedValue %>">
    </asp:TextBox>
</div> 
   </form>
</body>
</html>

{mospagebreak title=Dynamic binding to data at run time}

There are two ways you can populate the list with backend data. Well, not exactly two ways so much as two procedures using  the same AccessDataSource Control.

Example 1: The Long hand

The first of these is a roundabout way of getting the result. It still uses the AccessDataSource control by starting off using its connectionString as shown in the following (litany?) snippet. This was how data was accessed using ADO.NET 1.0.

Imports System.Data.OleDb
Partial Class _Default
   Inherits System.Web.UI.Page

   Protected Sub Button1_Click(ByVal sender As Object, _
   ByVal e As System.EventArgs) Handles Button1.Click
     Dim ds As New AccessDataSource
     ds = AccessDataSource1
     Response.Write(ds.ConnectionString)
     Dim mycon As New OleDbConnection
     Dim conStr As String = ds.ConnectionString
     mycon.ConnectionString = conStr
     mycon.Open()
     Response.Write("<h2>" & mycon.State & "</h2>")
     Dim myCmd As New OleDbCommand
     myCmd.Connection = mycon
     myCmd.CommandType = Data.CommandType.Text
     myCmd.CommandText = ds.SelectCommand.ToString
     Try
       Dim dr As OleDbDataReader = myCmd.ExecuteReader
       Response.Write(dr.HasRows)
       ‘Dim str As String = "" 
       While dr.Read
         ListBox1.Items.Add(dr.Item("CustomerID") & _
         "," & dr.Item("CompanyName") & "," & _
                           dr.Item("LastName") & "," & _
                            dr.Item("City") & "," _
                            & dr.Item("HomePhone"))
         ‘Response.Write(str)
       End While
       dr.Close()
     Catch ex As System.Data.OleDb.OleDbException
       Response.Write(ex.Message)
     End Try

     mycon.Close()

   End Sub
End Class

You may recall that this code is similar to what was formerly used in the VS2003 and described in a previously referenced article. The Design pane of this page (Default.aspx) is shown in the next picture followed by the source code listing of the page. In the source code make sure that the SelectCommand is all in one line. It should work as is except that the VS2005 IDE editor may emit some errors (it will work in spite of the emitted HTML error).

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server"> 
   <title>Longwinded</title>
</head>
<body>
   <form id="form1" runat="server">
   <div id="DIV1" runat="server"> 
     <asp:ListBox ID="ListBox1" runat="server"
     AppendDataBoundItems="True" AutoPostBack="false"
     Height="172px" Width="650px" >

     </asp:ListBox><asp:AccessDataSource
       ID="AccessDataSource1" runat="server"
       DataFile="~/App_Data/nwind.mdb" 
       SelectCommand="SELECT Customers.CustomerID,
       Customers.CompanyName, Customers.ContactName,
       Employees.LastName, Employees.City, Employees.HomePhone,
       Orders.OrderDate
       FROM ((Customers INNER JOIN Orders ON
       Customers.CustomerID = Orders.CustomerID)
       INNER JOIN Employees ON
       Orders.EmployeeID = Employees.EmployeeID)
       WHERE (Orders.OrderDate > #5/1/1998#)"

       </asp:AccessDataSource> 
     <asp:Button ID="Button1" runat="server"
Text="Button" /></div>
   </form> 
</body>
</html>

Example 2: Using DataSource directly

The code behind shown for this CodeBound.aspx is simple and effortless  thanks to the ADO.NET 2.0 DataSource controls. Some of the AccessDataSource controls’ properties are used.  The source code listing is also simpler as shown. The design pane of this example is exactly the same as in the previous example (Default.aspx). For this example you add the ListBox to the design pane and attach the datasource; you can get drop-down hints for writing the code.

First, the code behind the click event of the button.

Imports System.Data.OleDb
Partial Class CodeBound
   Inherits System.Web.UI.Page

   Protected Sub Button1_Click(ByVal sender As Object, _
   ByVal e As System.EventArgs) Handles Button1.Click
     Dim ds As New AccessDataSource
     ds = AccessDataSource1
     Dim sqlstr As String = "Select * from Customers"
     ds.SelectCommand = sqlstr

     ListBox1.DataSource = ds
     ListBox1.DataValueField = "CustomerID"
     ListBox1.DataTextField = "CompanyName"
     ListBox1.DataBind()
   End Sub
End Class

The source code listing of CodeBound.aspx is much simpler than the previous case as shown below. Less code is the key word here.

<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="CodeBound.aspx.vb" Inherits="CodeBound" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   <title>Code Bound</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
     <asp:ListBox ID="ListBox1" runat="server" Height="177px"
Width="333px">
     </asp:ListBox><asp:AccessDataSource
       ID="AccessDataSource1" runat="server"
       DataFile="~/App_Data/nwind.mdb" 
       SelectCommand="SELECT [CustomerID], [CompanyName],
                   [City], [Phone] FROM [Customers]">
     </asp:AccessDataSource>
     <br />
     <br />
     <asp:Button ID="Button1" runat="server"
Text="Button" /></div>
    </form>
</body>
</html>

This page gets rendered as shown in the next picture when the button is clicked.

{mospagebreak title=Databound ListBox Example}

In the previous two examples the ListBox was not bound to data at design time (see the design pane). In the following example the ListBox is bound to the DataSource as seen in the design view of this page, BoundList.aspx.

The source code for this page is as shown here.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server"> 
   <title>Databound Expression</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
     <asp:ListBox ID="ListBox1" runat="server"
       DataSourceID="AccessDataSource1"
       DataTextField="ContactName"
       DataValueField="City"
       AutoPostBack="True" >

     </asp:ListBox><asp:AccessDataSource ID="AccessDataSource1"
       runat="server" DataFile="~/App_Data/nwind.mdb"
       SelectCommand="SELECT [CustomerID], [CompanyName],
           [ContactName],
           [Address], [City], [Phone] FROM [Customers]" >
     </asp:AccessDataSource>

   </div>
     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
   </form>
</body>
</html>

There is no code behind to populate the list. The list is bound to data at design time. This is indeed an excellent enhancement for those who do not want to use the code but who are adept at designing using the IDE. There is some code behind but that is only for displaying a selected value in a textbox as show here.

Partial Class BoundList
   Inherits System.Web.UI.Page

   Protected Sub ListBox1_SelectedIndexChanged(ByVal sender _
   As Object, ByVal e As System.EventArgs) Handles _
   ListBox1.SelectedIndexChanged
     TextBox1.Text = ListBox1.SelectedValue
   End Sub
End Class

The following picture shows how this page gets rendered when the button is clicked. Note that the ListBox’s Selected value really references the DataFieldValue in the source code.

{mospagebreak title=Steps in converting a Unbound ListBox to a Bound ListBox}

The starting point is to drop a ListBox control on the design pane. Then click the smart tag arrow attached to the ListBox at top right to open the tasks window as shown.

Now click the Choose Data Source… hyperlink to open the next page of the wizard.

In this wizard use the drop-down to choose AccessDataSource1. This may open up other drop-downs. Since you are not sure of the item and the dropdown does not show any items, just click OK.

This modifies the task list to add a new item, Configure Data Source… as shown.

Click on Configure Data Source settings, which opens up the next screen. This screen comes up with the datasource you have already configured as shown in the next picture.

Click on the Next button  to reveal the next screen, Configure the Select Statement. Here you can do a lot of filtering and sorting of data using all the clauses of the SQL SELECT statement. For this example only the "City" column is chosen.

A click on the next button takes you to the following screen, Test Query, where you can test the query as shown using the Test Query button.

When you click the Finish button you get bound to data as shown in the next picture. You may also enable AutoPostBack.

Summary

This tutorial described the various ways a ListBox server control in ASPNET 2.0 gets populated with either hard coded data or data from a backend database. An MS Access 2003 database was used. The ADO.NET 2.0 Data Source Controls makes the coding much easier. The GUI provides all the necessary items for fashioning appropriate queries.

The ListBox event can be put to good use in drilling down on the data. Much of the drudgery encountered in ADO.NET 1.0 is removed for good. When configuring tasks it is advisable to switch to the source code and verify that the elements are properly configured. If you still want to use the tortuous route, you can take the route suggested in one of the examples.

4 thoughts on “How to Use the ListBox Control in ASP.NET 2.0

  1. Declarative binding makes it very easy to work with databases even for those who are not very comfortable with the database servers. The reduction in routine and often repetitive code is significant. Smart tags keep marshal the configuration very effectively.

    Looking forward to comments and suggestions,

    Sincerely, Jay

  2. I am using the FormView control to create a form with a number of different type of form elements.
    I’m adding the form elements one at a time and testing my insert so that if something doesn’t work, I can identify the form element causing trouble.

    My first two form elements were drop down lists and work fine. Now I’ve added a ListBox where the user can select multiple items from the list. This form element is optional, so in my stored procedure I have set the parameters value to default to null in case the user skips this form element. It is expected that the user will select 0-3 itmes from this list, so I wrote 3 parameters in the stored proc to handle incoming choices from the list.

    Now when I submit the form, no matter whether I choose any items or not from the listbox, I get this error message:
    ‘Procedure or function sp_GPRA_InsertActivity has too many arguments specified.’

    At this point I have 6 parameters declared in my stored proc and 6 items in the source code of my aspx page.

    I am wondering how the asp engine handles the submital for items from a list box? Since I am using FormView there is no code behind for me to look at to see how things are being processed for me. As a classic .asp programmer this is frustrating for me because I feel like I don’t know what’s going on behind the scenes.I have searched the internet high and low for anything on how ListBox selections are sent as parameters and I can’t find a thing.

    Any ideas are greatly appreciated.

  3. A very useful collection of tips. Thanks for sharing with us. I had found another nice post over the internet which also explained very well about ListBox Control in ASP.Net and it helped me lot to complete my task….
    http://mindstick.com/Articles/

    Thanks everyone for your precious post!!

[gp-comments width="770" linklove="off" ]