IN THIS CHAPTER
In this chapter, you’ll learn how to work with the ASP.NET list controls. In particular, you’ll learn how to use the list controls to display database data. For example, you’ll learn how to display a set of database records that represent book titles in a DropDownList
control.
By the end of this chapter, you’ll know how to
Bind database data to the list controls
Work with multi-select list controls
Assign default values to a list control
Copy list items from one list control to another
You can use any of the list controls to enable users to select one or more items from a list of items. For example, in a registration form, you might want to display a list of countries displayed in a drop-down list.
The ASP.NET Framework includes the following list controls:
DropDownList
. Enables
you to select one item from a drop-down list of list items
ListBox
. Enables you
to select one or more items from a box of list items
RadioButtonList
. Enables
you to select one item from a list of mutually exclusive radio buttons
CheckBoxList
. Enables you
to select one or more items from a list of check boxes
All of the list controls inherit from the base .NET Framework ListControl
class. That means that if you understand how to use one list control, you understand how to use all the list controls because they all share the same base methods and properties.
You can add list items to any of the list controls in one of three ways: by using the ListItem Collection Editor, by adding list items programmatically, or by using databinding. In the following sections, you are provided with examples of each method of populating a list control.
If you need to add a small number of list items to a list control, and the list of items will remain relatively stable, then you can take advantage of the Visual Studio .NET ListItem Collection Editor (see Figure 10.1).
For example, perform the following these steps to add a ListBox
control to a form that contains three list items labeled California, Washington, and Ohio:
Add a Web Form Page to your project named SelectState.aspx
.
Drag a ListBox
control from under the Web Forms tab in the Toolbox onto the Designer surface.
Select the ListBox
control in the Properties window and select the Items
property.
Clicking the ellipsis next to the Items
property opens the ListItem Collection Editor.
Add three list items to the editor with the Text
values California
, Washington
, and Ohio
.
Click OK to close the ListItem Collection Editor.
After you complete these steps, the ListBox
will appear on the Designer surface with the new list items
that you added.
Instead of using the ListItem Collection Editor, you can add list items directly to the Items collection of a list control. This is useful, for example, when you need to generate the list items in your code.
For example, suppose that you want to display a list of one hundred options labeled option 1, option 2, and so on.
Add a Web Form Page to your project named SelectOption.aspx
.
Add a ListBox
control to the page.
Switch to the code-behind page for the SelectOption.aspx page by selecting Code from the View menu.
Enter the following code for the Page_Load
handler:
C#.
private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack ) { for ( int intCounter = 1;intCounter < 101;intCounter++) { ListBox1.Items.Add("option " + intCounter); } } }
VB.NET.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim intCounter As Integer If Not Page.IsPostBack Then For intCounter = 1 To 100 ListBox1.Items.Add("option " & intCounter) Next End If End Sub
Right-click the SelectOption.aspx page in the Solution Explorer window and select Build and Browse.
When the SelectOption.aspx page appears, a list of 100 options will appear (see Figure 10.2).
When adding items programmatically, you might want to specify different text and value properties for the list items. For example, you might want to display a list of product names in a list box, but retrieve a product code when someone selects an item in the list box.
The ListItem
class has both a Text
and Value
property. The Text
property contains what is actually displayed in the list control. The Value
property contains a hidden value for the list item.
You can programmatically add items to a list control by explicitly creating a ListItem
and adding the ListItem
to the control’s Items
collection. For example, the following code creates a ListItem
with the text Stereo and the
value P788:
C#.
ListBox1.Items.Add(new ListItem("Stereo", "P788"));
VB.NET.
ListBox1.Items.Add(New ListItem("Stereo", "P788"))
Finally, you can add list items to a list control by taking advantage of databinding. You can bind several different types of data to a list control including DataSets, DataReaders, collections, and enumerations.
For example, suppose that you want to display a drop-down list of colors. Included in the .NET Framework class library, in the System.Drawing
namespace, is an enumeration named the KnownColor
enumeration. Perform the following steps to bind the KnownColor
enumeration to a DropDownList
:
Add a Web Form Page to your project named SelectColor.aspx
.
Add a DropDownList
control to the page.
Switch to the code-behind page for the SelectColor.aspx page by selecting Code from the View menu.
Enter the following code for the Page_Load
subroutine:
C#.
private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { DropDownList1.DataSource = System.Enum.GetNames(typeof(System.Drawing.KnownColor)); DropDownList1.DataBind(); } }
VB.NET.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not Page.IsPostBack Then DropDownList1.DataSource = _ System.Enum.GetNames(GetType(System.Drawing.KnownColor)) DropDownList1.DataBind() End If End Sub
Right-click the SelectColor.aspx page in the Solution Explorer window and select Build and Browse.
When the page opens, all the colors included in the
KnownColor
enumeration are displayed in the DropDownList
box (see Figure 10.3).
You bind data to a control by using one property and one method. First, you use the DataSource
property to indicate the source of the data. In the previous example, the data source was the KnownColor
enumeration. However, it could have been a variety of different data sources including database data or an array list of country names.
Next, you need to call the DataBind()
method to retrieve the items from the data source into the control. When the DataBind()
method is called in the previous example, the items from the KnownColor
enumeration are copied into the DropDownList
control.
Later, you’ll learn how to bind database data to a list control by taking advantage of the DataSource
property and the DataBind()
method.
Regardless
of the method you use to add list items to a list control, you can determine the text and value of the currently selected item in the list control with the
SelectedItem
property. For example, you can display the text of the selected list item in a Label
control as follows:
C#.
Label1.Text = ListBox1.SelectedItem.Text;
VB.NET.
Label1.Text = ListBox1.SelectedItem.Text
And you can display the value of the currently selected item in a list control as follows:
C#.
Label1.Text = ListBox1.SelectedItem.Value;
VB.NET.
Label1.Text = ListBox1.SelectedItem.Value
Suppose that you want to display a list of products in a ListBox
control and you want to display the currently selected item in a Label
control.
Add a Web Form Page to your project named SelectProduct.aspx
.
Add a ListBox
control to the page.
Add a Button
control to the page.
Add a Label
control to the page.
Double-click the Button
control
on the Designer surface. This will switch you to the Code Editor.
Enter the following code for the Button1_Click
subroutine:
C#.
private void Button1_Click(object sender, System.EventArgs e) { Label1.Text = ListBox1.SelectedItem.Text; }
VB.NET.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Label1.Text = ListBox1.SelectedItem.Text End Sub
Enter the following code for the Page_Load
handler:
C#.
private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack ) { ArrayList colProducts = new ArrayList(); colProducts.Add("Apples"); colProducts.Add("Oranges"); colProducts.Add("Strawberries"); ListBox1.DataSource = colProducts; ListBox1.DataBind(); } }
VB.NET.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim colProducts As ArrayList If Not IsPostBack Then colProducts = New ArrayList() colProducts.Add("Apples") colProducts.Add("Oranges") colProducts.Add("Strawberries") ListBox1.DataSource = colProducts ListBox1.DataBind() End If End Sub
Right-click the SelectProduct.aspx page in the Solution Explorer window and select Build and Browse.
The ListBox
contained in SelectProduct.aspx is bound to an ArrayList
in the Page_Load
handler. The colProducts ArrayList
is assigned to the ListBox
control’s DataSource
property. When the DataBind()
method is called, the items from the ArrayList
are copied into the ListBox
and, when the page is rendered, the items are displayed in the Web Form Page.
When you select a list item in the ListBox
control and click the Button
control, the Button1_Click
handler executes. This method assigns the value of the Text
property of the selected list item to a Label
control
(see Figure 10.4).
If you
assign the value True
to a list control’s AutoPostBack
property, the form containing the list control will be automatically posted back to the server whenever a new item is selected in the list control. In other words, when you enable the AutoPostBack
property, you do not need to add a Button
control to the form because the form will post automatically whenever a new selection is made.
The AutoPostBack
property assumes that a Web browser supports client-side JavaScript. Because not all Web browsers support client-side JavaScript, you must be careful when using this property. If you attempt to use AutoPostBack
with a downlevel browser, nothing will happen when you select a new item.
For example, you can create a DropDownList
control that automatically posts to the server whenever you select a new item in a drop-down list. Follow these steps to enable the AutoPostBack
property with a DropDownList
control that contains a list of names of famous philosophers:
Add a Web Form Page named SelectPhilosopher.aspx
to your project.
Add a DropDownList
control to the page.
In the Properties window,
assign the value True
to the DropDownList
control’s AutoPostBack
property.
Add a Label
control to the page.
Double-click the DropDownList
control on the Designer surface. This will switch you to the Code Editor.
Enter the following code for the DropDownList1_SelectedIndexChanged
handler:
C#.
private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e) { Label1.Text = DropDownList1.SelectedItem.Text; }
VB.NET.
Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged Label1.Text = DropDownList1.SelectedItem.Text End Sub
Enter the following code for the Page_Load
handler:
C#.
private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { ArrayList colPhilosophers = new ArrayList(); colPhilosophers.Add("Frege"); colPhilosophers.Add("Russell"); colPhilosophers.Add("Quine"); DropDownList1.DataSource = colPhilosophers; DropDownList1.DataBind(); } }
VB.NET.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim colPhilosophers As ArrayList If Not Page.IsPostBack Then colPhilosophers = New ArrayList() colPhilosophers.Add("Frege") colPhilosophers.Add("Russell") colPhilosophers.Add("Quine") DropDownList1.DataSource = colPhilosophers DropDownList1.DataBind() End If End Sub
Right-click the SelectPhilosopher.aspx page in the Solution Explorer window and select Build and Browse.
When you select a new philosopher in the DropDownList
control, the form is automatically posted back to the server and the name of the new philosopher appears in the Label
control.
Notice that we did not place the logic for assigning the name of the philosopher to the Label
control within the Button1_Click
handler. Because there is no longer a Button
control on the page, we need to perform this operation within the DropDownList1_SelectedIndexChanged
handler. This handler is executed whenever a new item
is selected in the DropDownList
control.
In the previous section, you learned how to bind a data source—such as a collection or enumeration—to a list control. In this section, you’ll learn how to bind database data to a list control.
Suppose, for example, that you want to display a list of book titles from the Titles database table in a drop-down list. First, we need to create a DataSet that represents the contents of the database table.
Add a Web Form Page named SelectTitle.aspx
to your project.
In the Server Explorer window, under the Data Connections tab, navigate to the Titles database table located under the Pubs data connection. (If you don’t already have an existing data connection to the Pubs database, you’ll need to create one.)
Drag and drop the Titles database table from the Server Explorer window onto the Designer surface. This will add an SqlConnection
and SqlDataAdapter
object to your Web Form Page.
Add a DataSet to the page by dragging the DataSet
object from under the Data tab on the Toolbox onto the Designer surface.
When the Add DataSet dialog box appears, select the Untyped Dataset option and click OK.
After you complete these steps, you will have the necessary objects to represent the contents of the Titles database table. Next, you need to bind the Titles database table to a DropDownList
control.
Add a DropDownList
control to the SelectTitle.aspx page.
Switch to the code-behind file for the SelectTitle.aspx page by selecting Code from the View menu.
Enter the following code for
the Page_Load
handler:
C#.
private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { sqlDataAdapter1.Fill(dataSet1); DropDownList1.DataSource = dataSet1; DropDownList1.DataTextField = "Title"; DropDownList1.DataValueField = "Title_ID"; DropDownList1.DataBind(); } }
VB.NET.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not Page.IsPostBack Then SqlDataAdapter1.Fill(DataSet1) DropDownList1.DataSource = DataSet1 DropDownList1.DataTextField = "Title" DropDownList1.DataValueField = "Title_ID" DropDownList1.DataBind() End If End Sub
Right-click the SelectTitle.aspx page in the Solution Explorer window and select Build and Browse.
After you complete these steps, the DropDownList
control will display a list of all the titles in the Titles database table (see Figure 10.5).
Notice that we assigned the value Title
to the DataTextField
property of the DropDownList
control. The DataTextField
property indicates the column from the data source that is displayed in the drop-down list.
We also assigned a value to the
DataValueField
property. Including this property is optional. The column assigned to the DataValueField
is not displayed in the DropDownList
control. However, you can retrieve the value of the DataValueField
column when a user selects a list item in the DropDownList
control.
You can use the SelectedItem
property of the DropDownList
control to detect the selected list item.
Switch to the Designer view of the SelectTitle.aspx page by selecting View, Designer.
Add a Button
control to the page.
Add a Label
control to the page and assign the value lblTitle
to the control’s ID
property.
Add a second Label
control to the page and assign the value lblTitleID
to the control’s ID
property.
Double-click the Button
control on the Designer surface. This will switch you to the Code Editor.
Enter the following code for
the Button1_Click
handler:
C#.
private void Button1_Click(object sender, System.EventArgs e) { lblTitle.Text = DropDownList1.SelectedItem.Text; lblTitleID.Text = DropDownList1.SelectedItem.Value; }
VB.NET.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click lblTitle.Text = DropDownList1.SelectedItem.Text lblTitleID.Text = DropDownList1.SelectedItem.Value End Sub
Right-click the SelectTitle.aspx in the Solution Explorer window and select Build and Browse.
After you complete these steps, you can display titles and title IDs in the Label
controls by selecting a list item in the DropDownList
control and clicking the Button
control. Both the title and title ID are retrieved from the SelectedItem
property.
For the sake of clarity, we are being sloppy about database performance in this chapter’s code samples. If you drag the Titles table onto the designer surface, an SqlDataAdapter
is automatically created that retrieves all the rows and all the columns from the Titles database table. Because we are only using the Title and Title_ID columns from the Titles table, we don’t need all this column information. For the sake of performance, you should modify the SqlDataAdapter
so that it retrieves only the necessary columns (right-click the SqlDataAdapter
in the Web Form Page and select Configure Data Adapter to change the SQL Select
statement).
Two of the
list controls—the ListBox
and CheckBoxList
controls—enable you to select multiple list items at a time. You cannot use the SelectedItem
property of these list controls to determine the currently selected items because the SelectedItem
property only returns one list item.
To create a ListBox
control that enables you to select multiple list items, you need to assign the value Multiple
to the ListBox
control’s
SelectionMode
property.
If you want to detect the selected items, you need to iterate through the contents of the Items collection of the list control. For example, suppose that you want to display a list of products from the Products database table in the Northwind database in a CheckBoxList
control. Additionally, suppose that after a user selects one or more items from the check box list, you want the selected items to be displayed in a Label
control (see Figure 10.6).
To create the necessary database objects, do the following:
Add a Web Form Page to your project named SelectProducts.aspx
.
In the Server Explorer window, under the Data Connections tab, navigate to the Products database table under the Northwind data connection. (If you don’t already have an existing data connection to the Northwind database, you’ll need to create one.)
Drag and drop the Products database table
from the Server Explorer window onto the Designer surface. This will add an SqlConnection
and SqlDataAdapter
object to your Web Form Page.
Add a DataSet to the page by dragging the DataSet
object from under the Data tab on the Toolbox onto the Designer surface.
When the Add DataSet dialog box appears, select the Untyped Dataset option and click OK.
After you complete these steps, you’ll have an SqlDataAdapter
that can retrieve the Products database on your page. Furthermore, you will have a DataSet that can represent the contents of the Products database table.
Next, you’ll need to add and populate
the CheckBoxList
control.
Add a CheckBoxList
control to the page.
In the Properties window, select the CheckBoxList1
control and assign the value 2 to the CheckBoxList
control’s RepeatColumns
property. This will cause the CheckBoxList
to be rendered in two columns.
Switch to the code-behind file for the SelectProducts.aspx page by selecting Code from the View menu.
Enter the following code for the Page_Load
handler:
C#.
private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { sqlDataAdapter1.Fill(dataSet1); CheckBoxList1.DataSource = dataSet1; CheckBoxList1.DataTextField = "ProductName" CheckBoxList1.DataBind(); } }
VB.NET.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not Page.IsPostBack Then SqlDataAdapter1.Fill(DataSet1) CheckBoxList1.DataSource = DataSet1 CheckBoxList1.DataTextField = "ProductName" CheckBoxList1.DataBind() End If End Sub
Right-click the SelectProducts.aspx page in the Solution Explorer window and select Build and Browse.
When the SelectProducts.aspx page opens, the products from the Products database table will appear in a two-column check box list. Notice that you can check more than one item in the list.
Finally, we need to add the logic to our page to display the selected list items in the check box list in a
Label
control.
Add a Label
control to the SelectProducts.aspx page.
Add a Button
control to the page.
Double-click the Button
control on the Designer surface. This will switch you to the Code Editor.
Enter the following code for the Button1_Click
handler:
C#.
private void Button1_Click(object sender, System.EventArgs e) { Label1.Text = ""; foreach (ListItem objListItem in CheckBoxList1.Items) { if (objListItem.Selected) Label1.Text += "<li>" + objListItem.Text; } }
VB.NET.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim objListItem As ListItem Label1.Text = "" For Each objListItem In CheckBoxList1.Items If objListItem.Selected Then Label1.Text &= "<li>" & objListItem.Text End If Next End Sub
Right-click the SelectProducts.aspx page in the Solution Explorer window and select Build and Browse.
After the page opens, you can select multiple list items in the check box list and the selected items will appear in the Label
control when you click the Button
control.
Notice that each selected item is detected within the Button1_Click
handler by iterating through the Items
collection of the CheckBoxList
control. Whenever the list item’s selected property has
the value True
, the value of the Text
property is added to the Label
control.
You can follow a similar set of steps when retrieving multiple selected items from a ListBox
control. Simply step through each of the items in the ListBox
control and check whether the list item’s selected property has the value True
.
In this section, you’ll tackle three advanced topics that you’ll face when working with the list controls. First, you learn how to programmatically add a default list item to a databound list control. Next, you learn how to display a default list item in a list control. Finally, you’ll learn how to create interactions between multiple list controls.
When displaying a drop-down list of items, it is common to display the first list item with a message like “Please Select an Item.” When binding a list control to database data, you’ll need to add the first list item programmatically.
In this section, you’ll learn how to create a DropDownList
control that displays a list of authors. The first list item, which you will add programmatically, will display the message “Select an Author” (see Figure 10.7).
First, we need to create the page and add the necessary database objects.
Add a Web Form Page to your project named SelectAuthor.aspx
.
In the Server Explorer window, under the Data Connections tab, navigate to the Authors database table located under the Pubs data connection. (If you don’t already have an existing data connection to the Pubs database, you’ll need to create one.)
Drag and drop the Authors database table from the Server Explorer window onto the Designer surface. This will add an SqlConnection
and SqlDataAdapter
object to your Web Form Page.
Add a DataSet to the page by dragging the DataSet
object from under the Data tab on the Toolbox onto the Designer surface.
When the Add DataSet dialog box appears, select the Untyped Dataset option and click OK.
Next, you need to add the DropDownList
control to the page and bind the control to the Authors DataSet. You’ll also add a new list item that will be the first list item displayed by the DropDownList
control.
Add a DropDownList
control to the SelectAuthor.aspx page.
Switch to the code-behind file for the page by selecting Code from the View menu.
Enter the following code
for the Page_Load
handler:
C#.
private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { sqlDataAdapter1.Fill(dataSet1); DropDownList1.DataSource = dataSet1; DropDownList1.DataTextField = "au_lname"; DropDownList1.DataBind(); DropDownList1.Items.Insert(0, "Select an Author"); } }
VB.NET.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not Page.IsPostBack Then SqlDataAdapter1.Fill(DataSet1) DropDownList1.DataSource = DataSet1 DropDownList1.DataTextField = "au_lname" DropDownList1.DataBind() DropDownList1.Items.Insert(0, "Select an Author") End If End Sub
Right-click the SelectAuthor.aspx page in the Solution Explorer window and select Build and Browse.
When the page opens, notice that the first item displayed by the DropDownList
control is “Select an Author.” This list item was added programmatically to the DropDownList
control’s Items
collection with the Insert()
method. It appears at the top of the list because it was inserted at
position 0.
You might
encounter the problem of selecting an initial default item when working with list controls. For example, you might want to display an alphabetical list of countries in a ListBox
control. However, you might want to display U.S.A. as the default item, even if it appears toward the bottom of the list.
In this section, you’ll learn how to display a default category when binding a ListBox
control to the Categories database table. We’ll take advantage of two methods of the ListItemCollection
class named FindByText
and FindByValue
. The FindByText
method enables you to find a matching list item by its Text
property and the FindByValue
enables you to find a matching list item by its Value
property.
First, we need to create the necessary database objects:
Add a Web Form Page named SelectCategory.aspx
to your project.
In the Server Explorer window, under the Data Connections tab, navigate to the Categories database table located under the Northwind data connection. (If you don’t already have an existing data connection to the Northwind database, you’ll need to create one.)
Drag and drop the Categories database table from the Server Explorer window onto the Designer surface. This will add an SqlConnection
and SqlDataAdapter
object to your Web Form Page.
Add a DataSet to the page by dragging the DataSet
object from under the Data tab on the Toolbox onto the Designer surface.
When the Add DataSet dialog box appears, select the Untyped Dataset option and click OK.
Next, you’ll need to add a ListBox
control
to the page. We’ll display the category Seafood by default by taking advantage of the FindByText
method:
Add a ListBox
control to the page by dragging the ListBox
control from under the Web Forms tab onto the Designer surface.
Switch to the code-behind file for the page by selecting View, Code.
Enter the following code for the Page_Load
subroutine:
C#.
private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { sqlDataAdapter1.Fill(dataSet1); ListBox1.DataSource = dataSet1; ListBox1.DataTextField = "CategoryName"; ListBox1.DataBind(); ListBox1.Items.FindByText("Seafood").Selected=true; } }
VB.NET.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not Page.IsPostBack Then SqlDataAdapter1.Fill(DataSet1) ListBox1.DataSource = DataSet1 ListBox1.DataTextField = "CategoryName" ListBox1.DataBind() ListBox1.Items.FindByText("Seafood").Selected = True End If End Sub
Right-click the SelectCategory.aspx page in the Solution Explorer window and select Build and Browse.
Notice that when the SelectCategory.aspx page first opens, the Seafood category is selected by default in the list box. In the Page_Load
handler, the FindByText
method finds the list item with the Text
value Seafood and sets the Selected
property of the matching item to true
. You can use the FindByValue
method in an identical fashion to match a list item with a particular Value
property.
You can copy or move items from one list control to another. Creating these types of interactions between list controls is useful when you want to enable users to select a subset of items from a list control. For example, you might use one list control to represent a set of products and another list control to represent a shopping cart.
In this section, we’ll create a ListBox
control that represents the products from the Products database table. We’ll create a second ListBox
control that represents a shopping cart (see Figure 10.8).
First, you need to create the necessary database objects:
Add a Web Form
Page to your project named ShoppingCart.aspx
.
In the Server Explorer window, under the Data Connections tab, navigate to the Products database table under the Northwind data connection. (If you don’t already have an existing data connection to the Northwind database, you’ll need to create one.)
Drag and drop the Products database table from the Server Explorer window onto the Designer surface. This will add an SqlConnection
and SqlDataAdapter
object to your Web Form Page.
Add a DataSet to the page by dragging the DataSet
object from under the Data tab on the Toolbox onto the Designer surface.
When the Add DataSet dialog box appears, select the Untyped Dataset option and click OK.
After you complete these steps, you’ll have an SqlDataAdapter
that can retrieve the Products database on your page. Furthermore, you will have a DataSet that can represent the contents of the Products database table.
Next, you’ll need to add the ListBox
controls and Button
control to the page.
Add two ListBox
controls to the ShoppingCart.aspx page and assign the value lstProducts
to the first ListBox
control’s ID
property and the value lstCart
to the second ListBox
control’s ID
property.
Add a Button
control to the page and assign the value Select >>
to the Text
property of the Button
control.
Finally, you’ll need to add the
necessary application logic to the code-behind file to copy the items from the first list box to the second ListBox
control:
Switch to the code-behind file for the ShoppingCart.aspx page by selecting Code from the View menu.
Enter the following code for the Page_Load
handler:
C#.
private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { sqlDataAdapter1.Fill(dataSet1); lstProducts.DataSource = dataSet1; lstProducts.DataTextField = "ProductName"; lstProducts.DataBind(); } }
VB.NET.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not Page.IsPostBack Then SqlDataAdapter1.Fill(DataSet1) lstProducts.DataSource = DataSet1 lstProducts.DataTextField = "ProductName" lstProducts.DataBind() End If End Sub
Switch back to the Designer surface by selecting Designer from the View menu.
Double-click the Button
control.
Enter the following code
for the Button1_Click
subroutine:
C#.
private void Button1_Click(object sender, System.EventArgs e) { if (lstProducts.SelectedIndex != -1) { lstCart.Items.Add(lstProducts.SelectedItem.Text); lstProducts.Items.Remove(lstProducts.SelectedItem); } }
VB.NET.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If lstProducts.SelectedIndex <> -1 Then lstCart.Items.Add(lstProducts.SelectedItem.Text) lstProducts.Items.Remove(lstProducts.SelectedItem) End If End Sub
Right-click the ShoppingCart.aspx page in the Solution Explorer window and select Build and Browse.
After the page opens, you can copy list items from one ListBox
control to the next. Select a list item in the first list box and click the Button
control and the list item will appear in the second ListBox
control.
The list items are copied from one control to another in the Button1_Click
handler. The selected list item from the first control is added to the Items
collection of the second list control. Next,
the item is removed from the previous list.
In this chapter, you learned how to work with the ASP.NET list controls. First, you learned the three methods of adding list items to a list control—declaratively, programmatically, and through databinding.
Next, you learned how to bind database data to a list control. You learned how to bind both a single option list control and a multi-option list control to the contents of a database table.
Finally, we tackled several advanced topics encountered when programming with the list controls. You learned how to add and display a default list item, and you also learned how to copy items from one list control to another.