How to Use the ListBox Control in ASP.NET 2.0 - Databound ListBox Example (Page 5 of 6 )
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.

Next: Steps in converting a Unbound ListBox to a Bound ListBox >>
More ASP.NET Code Articles
More By Jayaram Krishnaswamy