Chapter 10. Using List Controls

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

Overview of the List Controls

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:

  • DropDownListEnables you to select one item from a drop-down list of list items

  • ListBoxEnables you to select one or more items from a box of list items

  • RadioButtonListEnables you to select one item from a list of mutually exclusive radio buttons

  • CheckBoxListEnables 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.

Adding List Items with the ListItem Collection Editor

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).

Using the ListItem Collection Editor.

Figure 10.1. Using the ListItem Collection Editor.

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:

  1. Add a Web Form Page to your project named SelectState.aspx.

  2. Drag a ListBox control from under the Web Forms tab in the Toolbox onto the Designer surface.

  3. Select the ListBox control in the Properties window and select the Items property.

  4. Clicking the ellipsis next to the Items property opens the ListItem Collection Editor.

  5. Add three list items to the editor with the Text values California, Washington, and Ohio.

  6. 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.

Adding List Items Programmatically

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.

  1. Add a Web Form Page to your project named SelectOption.aspx.

  2. Add a ListBox control to the page.

  3. Switch to the code-behind page for the SelectOption.aspx page by selecting Code from the View menu.

  4. 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
    VB.NET 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
    
  5. 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).

Adding list items programmatically.

Figure 10.2. Adding list items programmatically.

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"))

Adding List Items with Databinding

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:

  1. Add a Web Form Page to your project named SelectColor.aspx.

  2. Add a DropDownList control to the page.

  3. Switch to the code-behind page for the SelectColor.aspx page by selecting Code from the View menu.

  4. 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
    VB.NET MyBase.Load
      If Not Page.IsPostBack Then
        DropDownList1.DataSource = _
          System.Enum.GetNames(GetType(System.Drawing.KnownColor))
        DropDownList1.DataBind()
      End If
    End Sub
    
  5. 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).

Adding list items with databinding.

Figure 10.3. Adding list items with databinding.

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.

Retrieving the Selected List Item

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.

  1. Add a Web Form Page to your project named SelectProduct.aspx.

  2. Add a ListBox control to the page.

  3. Add a Button control to the page.

  4. Add a Label control to the page.

  5. Double-click the Button control on the Designer surface. This will switch you to the Code Editor.

  6. 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)
    VB.NET Handles Button1.Click
      Label1.Text = ListBox1.SelectedItem.Text
    End Sub
    
  7. 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
    VB.NET 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
    
  8. 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).

Using the SelectedItem property.

Figure 10.4. Using the SelectedItem property.

Enabling AutoPostBack

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.

Warning

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:

  1. Add a Web Form Page named SelectPhilosopher.aspx to your project.

  2. Add a DropDownList control to the page.

  3. In the Properties window, assign the value True to the DropDownList control’s AutoPostBack property.

  4. Add a Label control to the page.

  5. Double-click the DropDownList control on the Designer surface. This will switch you to the Code Editor.

  6. 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
    VB.NET System.EventArgs) Handles DropDownList1.SelectedIndexChanged
      Label1.Text = DropDownList1.SelectedItem.Text
    End Sub
    
  7. 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
    VB.NET 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
    
  8. 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.

Displaying Database Data in a List 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.

  1. Add a Web Form Page named SelectTitle.aspx to your project.

  2. 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.)

  3. 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.

  4. Add a DataSet to the page by dragging the DataSet object from under the Data tab on the Toolbox onto the Designer surface.

  5. 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.

  1. Add a DropDownList control to the SelectTitle.aspx page.

  2. Switch to the code-behind file for the SelectTitle.aspx page by selecting Code from the View menu.

  3. 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
    VB.NET 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
    
  4. 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).

Binding the Titles table to a DropDownList control.

Figure 10.5. Binding the Titles table to a DropDownList control.

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.

  1. Switch to the Designer view of the SelectTitle.aspx page by selecting View, Designer.

  2. Add a Button control to the page.

  3. Add a Label control to the page and assign the value lblTitle to the control’s ID property.

  4. Add a second Label control to the page and assign the value lblTitleID to the control’s ID property.

  5. Double-click the Button control on the Designer surface. This will switch you to the Code Editor.

  6. 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)
    VB.NET Handles Button1.Click
      lblTitle.Text = DropDownList1.SelectedItem.Text
      lblTitleID.Text = DropDownList1.SelectedItem.Value
    End Sub
    
  7. 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.

Warning

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).

Working with Multi-Select List Controls

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.

Note

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).

Working with the CheckBoxList control.

Figure 10.6. Working with the CheckBoxList control.

To create the necessary database objects, do the following:

  1. Add a Web Form Page to your project named SelectProducts.aspx.

  2. 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.)

  3. 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.

  4. Add a DataSet to the page by dragging the DataSet object from under the Data tab on the Toolbox onto the Designer surface.

  5. 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.

  1. Add a CheckBoxList control to the page.

  2. 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.

  3. Switch to the code-behind file for the SelectProducts.aspx page by selecting Code from the View menu.

  4. 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
    VB.NET MyBase.Load
      If Not Page.IsPostBack Then
        SqlDataAdapter1.Fill(DataSet1)
        CheckBoxList1.DataSource = DataSet1
        CheckBoxList1.DataTextField = "ProductName"
        CheckBoxList1.DataBind()
      End If
    End Sub
    
  5. 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.

  1. Add a Label control to the SelectProducts.aspx page.

  2. Add a Button control to the page.

  3. Double-click the Button control on the Designer surface. This will switch you to the Code Editor.

  4. 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)
    VB.NET 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
    
  5. 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.

Advanced List Control Topics

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.

Adding a Default List Item

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).

Adding a default item.

Figure 10.7. Adding a default item.

First, we need to create the page and add the necessary database objects.

  1. Add a Web Form Page to your project named SelectAuthor.aspx.

  2. 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.)

  3. 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.

  4. Add a DataSet to the page by dragging the DataSet object from under the Data tab on the Toolbox onto the Designer surface.

  5. 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.

  1. Add a DropDownList control to the SelectAuthor.aspx page.

  2. Switch to the code-behind file for the page by selecting Code from the View menu.

  3. 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
    VB.NET 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
    
  4. 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.

Displaying a Default List Item

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:

  1. Add a Web Form Page named SelectCategory.aspx to your project.

  2. 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.)

  3. 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.

  4. Add a DataSet to the page by dragging the DataSet object from under the Data tab on the Toolbox onto the Designer surface.

  5. 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:

  1. Add a ListBox control to the page by dragging the ListBox control from under the Web Forms tab onto the Designer surface.

  2. Switch to the code-behind file for the page by selecting View, Code.

  3. 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
    VB.NET 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
    
  4. 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.

Creating Interactions Between List Controls

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).

Copying items between list controls.

Figure 10.8. Copying items between list controls.

First, you need to create the necessary database objects:

  1. Add a Web Form Page to your project named ShoppingCart.aspx.

  2. 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.)

  3. 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.

  4. Add a DataSet to the page by dragging the DataSet object from under the Data tab on the Toolbox onto the Designer surface.

  5. 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.

  1. 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.

  2. 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:

  1. Switch to the code-behind file for the ShoppingCart.aspx page by selecting Code from the View menu.

  2. 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
    VB.NET MyBase.Load
      If Not Page.IsPostBack Then
        SqlDataAdapter1.Fill(DataSet1)
        lstProducts.DataSource = DataSet1
        lstProducts.DataTextField = "ProductName"
        lstProducts.DataBind()
      End If
    End Sub
    
  3. Switch back to the Designer surface by selecting Designer from the View menu.

  4. Double-click the Button control.

  5. 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)
    VB.NET Handles Button1.Click
      If lstProducts.SelectedIndex <> -1 Then
        lstCart.Items.Add(lstProducts.SelectedItem.Text)
        lstProducts.Items.Remove(lstProducts.SelectedItem)
      End If
    End Sub
    
  6. 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.

Summary

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset