Chapter 12. Displaying Data with the DataList Control

In this chapter, you will learn how to use the DataList control to display and interact with database data. The DataList control is similar to the Repeater control. Like the Repeater control, the DataList control supports templates for formatting items from a data source.

However, the DataList control provides you with additional functionality. In this chapter, you’ll learn:

  • How to take advantage of auto formatting and style objects to format the content rendered by a DataList

  • How to use a DataList to display data in multiple columns

  • How to create interactive menus with a DataList

Binding the DataList Control to Database Data

The basic procedure for binding a DataList to database data is the same for the DataList control as for the Repeater control. You use the DataList control’s DataSource property to indicate a data source and then you call the DataList control’s DataBind() method to copy the items from the data source into the DataList control.

For example, suppose that you want to display the contents of the Authors database table with a DataList control. First, you’ll need to create the necessary database objects:

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

  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 DataList control to the page and bind the control to the Authors DataSet:

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

  2. Switch to the code-behind file for the DisplayAuthors.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)
    {
      sqlDataAdapter1.Fill( dataSet1 );
      DataList1.DataSource = dataSet1;
      DataList1.DataBind();
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      SqlDataAdapter1.Fill(DataSet1)
      DataList1.DataSource = DataSet1
      DataList1.DataBind()
    End Sub
    

Finally, you need to add at least one template to the DataList control. You’ll add an ItemTemplate to the control:

  1. Switch back to the Designer by selecting Designer from the View menu.

  2. Switch to HTML view by selecting the HTML tab on the bottom left of the window.

  3. Enter the following ItemTemplate between the opening and closing <asp:DataList> tags:

    <asp:DataList id="DataList1"
    style="Z-INDEX: 101; LEFT: 80px; POSITION: absolute; TOP: 60px"
    runat="server">
     <ItemTemplate>
       <%# DataBinder.Eval( Container, "DataItem.au_lname" )%>
     </ItemTemplate>
    </asp:DataList>
    
  4. Right-click the DisplayAuthors.aspx page in the Solution Explorer window and select Build and Browse.

After you complete these steps, the page displayed in Figure 12.1 will appear. Notice that each item from the data source is displayed in a new row. The DataList has automatically rendered an HTML table creating a new table row for each item.

Displaying database records with the DataList control.

Figure 12.1. Displaying database records with the DataList control.

Using Templates with the DataList Control

The DataList control supports exactly the same templates at the Repeater control:

  • HeaderTemplateContent contained in this template is displayed before any items from the data source.

  • ItemTemplateContent contained in this template is displayed for each item in the data source.

  • AlternatingItemTemplateContent contained in this template is displayed for alternating items in the data source.

  • SeparatorTemplateContent contained in this template is displayed between each item in the data source.

  • FooterTemplateContent contained in this template is displayed after any items from the data source.

In the previous section, you used the ItemTemplate to format how each item from the data source is displayed. The ItemTemplate formats each table row rendered by the DataList control.

There are actually two ways that you can add templates to a DataList. In the previous section, we added the ItemTemplate by switching to the HTML view of the page and entering the template by hand. Alternatively, you can right-click the DataList control on the Designer surface and select the Edit Template option (see Figure 12.2).

Editing templates with the Designer.

Figure 12.2. Editing templates with the Designer.

When you edit a template with the Designer, you can enter the contents of the template directly into the DataList control. When you are finished editing a template, you right-click the DataList and select End Template Editing.

The disadvantage of this second method of editing templates is that it does not allow you to enter freestanding databinding expressions. Also, you cannot type HTML tags directly into the template. However, you can drag and drop HTML elements and ASP.NET controls onto the template from the Toolbox.

Formatting the Appearance of a DataList

Because a DataList control uses an HTML table to display its data (which results in the data being displayed in a structured manner), you are provided with several formatting options when working with a DataList control. In the following sections, you’ll learn how to format the borders of a DataList control, use auto formatting with a DataList control, and display the data in a DataList control in multiple columns.

Formatting the Borders in a DataList Control

You can control the appearance of the borders rendered by a DataList control by modifying four of the DataList control’s properties:

  • GridLinesIndicates whether horizontal, vertical, or both horizontal and vertical lines appear between the cells rendered by a DataList control

  • BorderColorIndicates the color of the border lines around cells

  • BorderStyleIndicates the style of the outside border (for example, solid or dashed)

  • BorderWidthIndicates the pixel width of the outside border

You can modify these properties directly in the Properties window. Alternatively, you can open the Property Builder for the DataList by right-clicking the DataList, selecting Property Builder, and clicking the Borders tab.

Not all of these properties will render correctly in all browsers. Not surprisingly, all these properties work fine with recent versions of Microsoft Internet Explorer.

In the case of Netscape Navigator, however, you can only meaningfully assign the values Both or None to the GridLines property. Furthermore, the BorderStyle property is completely ignored.

Using Auto Formatting with the DataList Control

The DataList control supports Style objects for formatting the appearance of the control. You can edit the properties of the Style objects in the DataList control’s Property sheet, or you can apply styles to the DataList by taking advantage of auto formatting.

To take advantage of auto formatting, right-click the DataList control on the Designer surface and select the Auto Format option. Selecting this option opens the dialog box shown in Figure 12.3.

The Auto Format dialog box.

Figure 12.3. The Auto Format dialog box.

Notice that the Auto Format dialog box enables you to select among a variety of formatting schemes. For example, you can apply a Professional, Classic, or Colorful scheme to the DataList control.

If you don’t like any of the pre-made style schemes, you can directly edit the Style objects associated with the DataList control. You can edit any of the following Style objects:

  • AlternatingItemStyleFormats alternating items

  • EditItemStyleFormats items selected for editing

  • FooterStyleFormats row that appears below all items

  • HeaderStyleFormats row that appears above all items

  • ItemStyleFormats each item

  • SelectedItemStyleFormats currently selected item

  • SeparatorStyleFormats content that appears between each item

For example, to format every other item displayed by the DataList control with a gray background—and create a banding effect—do the following:

  1. Select the DataList control in the Properties window.

  2. Expand the AlternatingItemStyle property.

  3. Assign the value Gray to the BackColor property.

After you make these changes, the DataList will render the page in Figure 12.4.

Using the DataList control’s AlternatingItemStyle property.

Figure 12.4. Using the DataList control’s AlternatingItemStyle property.

Notice that the Style objects provide you with an alternative to using templates. If you want to display alternating items in a green font, you can create an AlternatingItemTemplate or you can edit the properties of the AlternatingItemStyle object.

Warning

Style objects do not function exactly like templates. For example, if you use a SelectedItemTemplate to format the currently selected item in a menu rendered with a DataList, you need to rebind the DataList to its DataSource. If you use the SelectedItemStyle object, on the other hand, you don’t need to rebind. Because a template might display a different databinding expression, you must always rebind to a datasource when formatting items with a template.

Creating a Multicolumn DataList

You can use two of the properties of the DataList control, the RepeatColumns and RepeatDirection properties, to render the items contained within a DataList in multiple columns. For example, creating multicolumn DataList controls is useful when creating single row tab strips and navigation menus.

The RepeatColumns property specifies the number of columns to display with the DataList control. The RepeatDirection property indicates whether items should be repeated in a horizontal or vertical direction.

Perform the following steps to display a three-column list of products from the Products database table (see Figure 12.5).

Rendering multiple columns with the DataList control.

Figure 12.5. Rendering multiple columns with the DataList control.

First, you’ll need to create a new Web Form Page and add the necessary database objects:

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

  2. In the Server Explorer window, under the Data Connections tab, navigate to the Products 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 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.

Next, you’ll need add the DataList control to the page and modify the control’s RepeatColumns property:

  1. Add a DataList control to the page.

  2. In the Properties window, select the DataList control and assign the value 3 to the RepeatColumns property.

  3. In the Properties window, assign the value Both to the GridLines property.

  4. Click the HTML tab on the bottom of the window and enter the following ItemTemplate between the opening and closing <asp:DataList> tags:

    <asp:DataList id="DataList1"
      style="Z-INDEX: 101; LEFT: 320px; POSITION: absolute; TOP: 140px"
      runat="server" RepeatColumns="3">
      <ItemTemplate>
        <%# DataBinder.Eval(Container, "DataItem.ProductName" )%>
      </ItemTemplate>
    </asp:DataList>
    

Finally, you need to bind the DataList control to the Products DataSet:

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

  2. Enter the following code for the Page_Load subroutine:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
      sqlDataAdapter1.Fill( dataSet1 );
      DataList1.DataSource = dataSet1;
      DataList1.DataBind();
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      SqlDataAdapter1.Fill(DataSet1)
      DataList1.DataSource = DataSet1
      DataList1.DataBind()
    End Sub
    
  3. Right-click the DisplayProducts.aspx page in Solution Explorer and select Build and Browse.

When the DisplayProducts.aspx page opens, the products are automatically displayed in three columns.

Creating a Menu with a DataList

You can use the DataList control to render an interactive menu of items. For example, you can use the DataList control to render a list of product category links. When a user clicks on a category link, you can display matching products.

To create an interactive menu of category links, we’ll need to take advantage of a feature of the DataList control called event-bubbling. When a control supports event-bubbling, you can create a single event handler that executes whenever a control contained within the control raises an event.

To create our interactive menu of product category links, we’ll need to add a LinkButton control to the DataList control’s ItemTemplate. Each LinkButton will display a particular category link. However, clicking any category link will execute the same event handler. The Click event raised by clicking a category LinkButton will bubble up to be captured by the DataList control.

First, we’ll need to create a new Web Form Page and add the necessary database objects:

  1. Add a Web Form Page named DisplayMenu.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, we need to create the DataList control and add an ItemTemplate that contains a LinkButton control:

  1. Add a DataList control to the page.

  2. Right-click the DataList control and select ItemTemplates from the Edit Template menu.

  3. Add a LinkButton control to the DataList control’s ItemTemplate by dragging the LinkButton control onto the ItemTemplate on the Designer surface.

  4. Select the LinkButton control in the Properties window and click the ellipsis that appears next to the DataBindings property.

  5. In the DataBindings dialog box, select the radio button labeled Custom Binding Expression and enter the following expression in the text box:

    C#

    DataBinder.Eval(Container, "DataItem.CategoryName")
    

    VB.NET

    DataBinder.Eval(Container, "DataItem.CategoryName")
    
  6. Click OK to close the DataBindings dialog box, right-click the DataList control, and select End Template Editing to stop editing the ItemTemplate.

Next, we need to bind the DataList control to the Categories DataSet:

  1. Switch to the code-behind file for the DisplayMenu.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);
        DataList1.DataSource=dataSet1;
        DataList1.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)
        DataList1.DataSource = DataSet1
        DataList1.DataBind()
      End If
    End Sub
    

The next step is to highlight the selected item in the menu with a yellow background color:

  1. Switch back to the Designer surface by selecting Designer from the View menu.

  2. Select the DataList control in the Properties window.

  3. Expand the SelectedItemStyle property.

  4. Assign the value Yellow to the SelectedItemStyle BackColor property.

Finally, we need to add an event-handler that executes whenever you click a menu item.

Procedure 12.1. C# Steps

  1. In the Properties window, select the DataList control.

  2. Click the Events icon at the top of the Properties window (the icon of the lightning bolt).

  3. Double-click next to the ItemCommand event (this will switch you to the Code Editor).

  4. Enter the following code for the DataList_ItemCommand handler:

    private void DataList1_ItemCommand(object source, System.Web.UI.WebControls
    C# Steps.DataListCommandEventArgs e)
    {
      DataList1.SelectedIndex = e.Item.ItemIndex;
    }
    
  5. Right-click the DisplayMenu.aspx page in Solution Explorer and select Build and Browse.

Procedure 12.2. VB.NET Steps

  1. Switch to the code-behind file for the DisplayMenu.aspx page by selecting View, Code.

  2. In the Class Name drop-down list (at the top left of the Code Editor), select the DataList1 control.

  3. In the Method Name drop-down list (at the top right of the Code Editor), select the ItemCommand method.

  4. Enter the following code for the DataList1_ItemCommand subroutine:

    Private Sub DataList1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI
    VB.NET Steps.WebControls.DataListCommandEventArgs) Handles DataList1.ItemCommand
      DataList1.SelectedIndex = e.Item.ItemIndex
    End Sub
    
  5. Right-click the DisplayMenu.aspx page in Solution Explorer and select Build and Browse.

After the DisplayMenu.aspx page opens, you can click a particular category name and the selected category name will be highlighted with a yellow background color.

This sample contains several steps, so it deserves some explanation. Let’s walk through the flow of events when you click a menu item:

  1. Clicking a menu item raises a LinkButton control’s Click event.

  2. The Click event bubbles up to the DataList control, which raises the DataList control’s ItemCommand event.

  3. The ItemCommand event is handled by an event-handler named DataList1_ItemCommand.

  4. The DataList1_ItemCommand handler assigns the index of the item clicked to the DataList control’s SelectedIndex property.

  5. The item that has the index of the SelectedIndex is rendered with the formatting properties of the SelectedItemStyle Style object.

  6. The selected menu item is rendered with a yellow background color.

By taking advantage of event-bubbling, you can create a single event handler—the DataList1_ItemCommand—that executes whenever someone clicks a LinkButton. If the DataList control did not support event bubbling, you would need to capture the Click event of each and every LinkButton control individually.

Using the DataKeys Collection

In the previous section, you created an interactive menu of product categories with the DataList control. When a menu item is clicked, the index of the selected item is passed to the DataList1_ItemCommand handler.

Unfortunately, the index of the selected item in a menu doesn’t usually do you any good. Typically, you don’t want the index of the selected item. Instead, you need to know the primary key associated with the menu item.

For example, if you want to display a list of matching products when you click a category, you will need the primary key associated with the category to select the matching products. The Categories and Products tables are joined on a common CategoryID key.

There is an easy way around this problem. The DataList control supports a special collection of items named the DataKeys collection. You can automatically populate the DataKeys collection with values from the primary key column from the DataList control’s data source.

To illustrate how the DataKeys collection works, you’ll create a menu of authors’ last names. When you select an author in the menu, the primary key associated with the author will be displayed in a Label control.

First, you need to create a new Web Form Page and the necessary database objects:

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

  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, we need to create the Label and DataList controls and add an ItemTemplate to the DataList that contains a LinkButton control:

  1. Add a Label control to the page.

  2. Add a DataList control to the page.

  3. Right-click the DataList control and select ItemTemplates from the Edit Template menu.

  4. Add a LinkButton control to the DataList control’s ItemTemplate by dragging the LinkButton control from under the Web Forms tab on the Toolbox onto the ItemTemplate on the Designer surface.

  5. Select the LinkButton control in the Properties window and click the ellipsis that appears next to the DataBindings property.

  6. In the DataBindings dialog box, select the Custom Binding Expression radio button and enter the following expression in the text box:

    C#

    DataBinder.Eval( Container, "DataItem.au_lname" )
    

    VB.NET

    DataBinder.Eval( Container, "DataItem.au_lname" )
    
  7. Click OK to close the DataBindings dialog box, right-click the DataList control, and select End Template Editing to stop editing the ItemTemplate.

Next, you need to bind the DataList control to the Authors DataSet. This time, however, you’ll assign a value to the DataList control’s DataKeyField property before binding the DataList. The DataKeyField indicates the name of the primary key from the Authors table.

  1. Switch to the code-behind file for the AuthorMenu.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);
      DataList1.DataSource = dataSet1;
      DataList1.DataKeyField = "au_id";
    DataList1.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)
        DataList1.DataSource = DataSet1
        DataList1.DataKeyField = "au_id"
        DataList1.DataBind()
      End If
    End Sub
    

The next step is to highlight the selected item in the menu. You’ll highlight the selected menu item by changing its font to bold and italic:

  1. Switch back to the Designer surface by selecting Designer from the View menu.

  2. Select the DataList control in the Properties window.

  3. Expand the SelectedItemStyle property.

  4. Expand the SelectedItemStyle Font property.

  5. Assign the value True to both the Bold and Italic properties.

Finally, we need to add a handler that executes whenever you click a menu item. This subroutine will assign the primary key of the selected item to the Label control.

Procedure 12.3. C# Steps

  1. In the Properties window, select the DataList control.

  2. Click the Events icon at the top of the Properties window (the icon of the lightning bolt).

  3. Double-click next to the ItemCommand event (this will switch you to the Code Editor).

  4. Enter the following code for the DataList_ItemCommand handler:

    private void DataList1_ItemCommand(object source, System.Web.UI.WebControls
    C# Steps.DataListCommandEventArgs e)
    {
      DataList1.SelectedIndex = e.Item.ItemIndex;
      Label1.Text = (string)DataList1.DataKeys[ e.Item.ItemIndex ];
    }
    
  5. Right-click the AuthorMenu.aspx page in Solution Explorer and select Build and Browse.

Procedure 12.4. VB.NET Steps

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

  2. In the Class Name drop-down list (at the top left of the code editor), select the DataList1 control.

  3. In the Method Name drop-down list (at the top right of the code editor), select the ItemCommand method.

  4. Enter the following code for the DataList1_ItemCommand subroutine:

    Private Sub DataList1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI
    VB.NET Steps.WebControls.DataListCommandEventArgs) Handles DataList1.ItemCommand
      DataList1.SelectedIndex = e.Item.ItemIndex
      Label1.Text = DataList1.DataKeys( e.Item.ItemIndex )
    End Sub
    
  5. Right-click the AuthorMenu.aspx page in Solution Explorer and select Build and Browse.

After the AuthorMenu.aspx page opens, you can select an author by clicking a menu item. When you select an author, the primary key associated with the author appears in the Label control. In the case of the Authors database table, the primary key contains the author’s Social Security number (see Figure 12.6).

Using the DataKeys collection.

Figure 12.6. Using the DataKeys collection.

Creating a Single-Page Master/Detail Form

In this final section, you’ll create a Web Form Page that uses both the DataList and Repeater controls. You’ll create a single-page master/detail form that uses a DataList to display a menu of product categories and a Repeater control to display a list of matching products.

First, you need to create the new Web Form Page and the necessary database objects. You’ll need to create one SqlDataAdapter for the Categories database table and a second SqlDataAdapter for the Products database table:

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

  2. In the Server Explorer window, under the Data Connections tab, expand the Tables folder 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. Drag and drop the Products database table from the Server Explorer window onto the Designer surface. This will add a second SqlDataAdapter object to your Web Form Page.

  5. In the Properties window, select the second SqlDataAdapter.

  6. Expand the SelectCommand property.

  7. Assign the following select statement to the CommandText property:

    SELECT
    ProductID, ProductName, UnitPrice
    FROM dbo.Products
    Where CategoryID = @CategoryID
    
  8. Add a DataSet to the page by dragging the DataSet object from under the Data tab on the Toolbox onto the Designer surface.

  9. When the Add DataSet dialog box appears, select the Untyped Dataset option and click OK.

Next, you need to add a DataList control that displays the menu of product categories:

  1. Add a DataList control to the page.

  2. Right-click the DataList control and select ItemTemplates from the Edit Template menu.

  3. Add a LinkButton control to the DataList control’s ItemTemplate by dragging the LinkButton control from under the Web Forms tab on the Toolbox onto the ItemTemplate on the Designer surface.

  4. Select the LinkButton control in the Properties window and click the ellipsis that appears next to the DataBindings property.

  5. In the DataBindings dialog box, select Custom Binding Expression radio button and enter the following expression in the text box:

    C#

    DataBinder.Eval(Container, "DataItem.CategoryName")
    

    VB.NET

    DataBinder.Eval(Container, "DataItem.CategoryName")
    
  6. Click OK to close the DataBindings dialog box, right-click the DataList control, and select End Template Editing to stop editing the ItemTemplate.

Next, you’ll modify the SelectedItemStyle object so the selected menu item will appear with a yellow background:

  1. In the Properties window, select the DataList control.

  2. Expand the SelectedItemStyle property.

  3. Assign the value Yellow to the SelectedItemStyle BackColor property.

Next, you must bind the DataList to the Categories DataSet:

  1. Switch to the code-behind file for the MasterDetail.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 );
      DataList1.DataSource = dataSet1;
      DataList1.DataKeyField = "CategoryID";
      DataList1.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)
        DataList1.DataSource = DataSet1
        DataList1.DataKeyField = "CategoryID"
        DataList1.DataBind()
      End If
    End Sub
    

Next, you need to add a Repeater control to display the products. You’ll display the name and price of each product:

  1. Switch back to the Designer by selecting Designer from the View menu.

  2. Add a Flow Layout Panel to the page by dragging the Flow Layout Panel from under the HTML tab in the Toolbox onto the Designer surface.

  3. Add a Repeater control to the Flow Layout Panel by dragging the Repeater control from under the Web Forms tab in the Toolbox onto the Flow Layout Panel.

  4. Switch to the HTML source for the page by clicking the HTML tab at the bottom of the Designer window.

  5. Enter the following ItemTemplate between the opening and closing <asp:Repeater> tags:

    <asp:Repeater id="Repeater1" runat="server">
      <ItemTemplate>
      <li>
      <%# DataBinder.Eval( Container, "DataItem.ProductName" )%> -
      <%# DataBinder.Eval( Container, "DataItem.UnitPrice", "{0:c}" )%>
      </li>
      </ItemTemplate>
    </asp:Repeater>
    

Finally, you need to retrieve the matching products when a product category is clicked in the DataList menu.

Procedure 12.5. C# Steps

  1. In the Properties window, select the DataList control.

  2. Click the Events icon at the top of the Properties window (the icon of the lightning bolt).

  3. Double-click next to the ItemCommand event (this will switch you to the code editor).

  4. Enter the following code for the DataList_ItemCommand handler:

    private void DataList1_ItemCommand(object source, System.Web.UI.WebControls
    C# Steps.DataListCommandEventArgs e)
    {
      DataList1.SelectedIndex = e.Item.ItemIndex;
      int intPrimaryKey = (int)DataList1.DataKeys[e.Item.ItemIndex];
      sqlDataAdapter2.SelectCommand.Parameters["@CategoryID"].Value  = intPrimaryKey;
      sqlDataAdapter2.Fill(dataSet1);
      Repeater1.DataSource = dataSet1;
      Repeater1.DataBind();
    }
    
  5. Right-click the MasterDetail.aspx page in Solution Explorer and select Build and Browse.

Procedure 12.6. VB.NET Steps

  1. Switch to the code-behind file for the MasterDetail.aspx page by selecting View, Code.

  2. In the Class Name drop-down list (located at the top left of the code editor), select DataList1.

  3. In the Method Name drop-down list (located at the top right of the code editor), select the ItemCommand method.

  4. Enter the following code for the DataList1_ItemCommand:

    Private Sub DataList1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI
    VB.NET Steps.WebControls.DataListCommandEventArgs) Handles DataList1.ItemCommand
      Dim intPrimaryKey As Integer
    
      DataList1.SelectedIndex = e.Item.ItemIndex
      intPrimaryKey = DataList1.DataKeys(e.Item.ItemIndex)
      SqlDataAdapter2.SelectCommand.Parameters("@CategoryID").Value  = intPrimaryKey
      SqlDataAdapter2.Fill(DataSet1)
      Repeater1.DataSource = DataSet1
      Repeater1.DataBind()
    End Sub
    
  5. Right-click the MasterDetail.aspx page in the Solution Explorer window and select Build and Browse.

When you finish these steps, the Designer surface should resemble Figure 12.7.

MasterDetail.aspx page in the Designer.

Figure 12.7. MasterDetail.aspx page in the Designer.

After you select Build and Browse and the MasterDetail.aspx page opens, you can click a category name and a list of matching products is displayed. The resulting page should resemble Figure 12.8.

MasterDetail page in a Web browser.

Figure 12.8. MasterDetail page in a Web browser.

Summary

In this chapter, you learned how to the DataList control to format and display database data. First, you learned how to use the DataList control to display database records in an HTML table. You learned how to apply advanced formatting to a DataList by taking advantage of auto formatting and Style objects. You also learned how to display the output of a DataList control in multiple columns.

Finally, you tackled an advanced Web Form Page that makes use of both the DataList and Repeater controls. You learned how to create a single page master/detail form that displays a menu of categories in a DataList control and a set of matching products in a Repeater control.

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

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