Data Binding to Other Types of List Controls


So far, we've only used one basic type of list control in our examination of using data to create output in our ASP.NET pages. We used a DataGrid control in this chapter. In the previous chapters, we used an MxDataGrid, but (as we discovered) this is just a cleverer version of the DataGrid designed for use within Web Matrix. In this remaining section of the chapter, we'll look at the other list controls that we can data-bind to a data source such as a database table.

The ASP.NET List Controls

ASP.NET provides several types of list control that we can use to generate repeated content from a range of data sources:

  • CheckBoxList – Creates a list of checkboxes, from which more than one can be selected. We can specify which column from our data source will be used to set the caption of each checkbox by setting the DataTextField property to one of the column names.

  • RadioButtonList – Creates a list of radio (or option) buttons, from which only one can be selected. We can specify which column from our data source will be used to set the caption of each radio button by setting the DataTextField property to one of the column names, and which column will be used to set the value of each radio button by setting the DataValueField property to another of the column names.

  • DropDownList – Creates a drop-down selection list, from which only one item can be selected. This is useful when we want to minimize the space used on the page. We can specify which column from our data source will be used to set the visible text of each option in the list by setting the DataTextField property to one of the column names, and which column will be used to set the value of each option by setting the DataValueField property to another of the column names.

  • ListBox – Creates a list where more than one item is visible, and it can be configured so that users can select only one item, or so that they can select more than one item. We can specify which column from our data source will be used to set the visible text of each option in the list by setting the DataTextField property to one of the column names, and which column will be used to set the value of each option by setting the DataValueField property to another of the column names.

  • Repeater – Repeats any type of content that we specifically define, without the control applying any of its own structuring or formatting to the content. It is simpler, lighter, and more efficient than the DataList or DataGrid, but has fewer features. Templates are used to define the format and layout of the content, and any line breaks, paragraph divisions, and so on, must be specifically declared within these templates.

  • DataList – Lays out its content in the cells of a table, or repeated across or down the page in columns. This is a powerful list control, which is one step up from the Repeater in complexity and use of resources. By default, it lays out the content generated for each item in the data source within one cell of an HTML <table>, though it can also be used like the Repeater (without generating a <table> – called flow layout mode). It also provides a header and footer that can be formatted separately, and it can lay content out vertically or horizontally in columns when in table layout mode. Templates can be used to define the format and layout of the content, and any line breaks, paragraph divisions, and so on, must be specifically declared within these templates.

  • DataGrid – As we've already seen, this control builds an HTML table where each value is in a separate column, so that it looks like a grid. It provides the most control over content, and the most extra features. As well as headers and footers, the control can divide the list of items across multiple "pages", provide automatic inline editing features, easily link code to events raised by controls in each row, and even automatically generate the columns based on the data source contents. A wide range of formatting options allows attractive layouts to be constructed.

In the next example, we'll use one of each of these controls (except the DataGrid, which we've already examined in enough depth). We'll bind them to the result of a method that we build with the SELECT Data Method code builder, as we did in the first Try It Out in this chapter. While we don't have room to examine all of the features of these list controls, it will show you how they can be used with server-side data binding.

Using the ASP.NET List Controls

We start by creating the method that returns all the rows from the Publishers table in the example pubs database. The process is the same as we used in the first Try It Out in this chapter, just with a different table.

Try It Out—Data Binding with List Controls

  1. Start a new ASP.NET page called ListControls.aspx, and drag a SELECT Data Method into the editor window in Code view. Connect to the pubs database in the Connect to Database dialog. In the Query Builder dialog, select the Publishers table and then select the * entry in the list of columns to return all the columns:

    click to expand

  2. Click Next and test the query in the next page of the Query Builder dialog if you want to. Then click Next again, enter AllPublishers for the name of the method, and select a DataReader as the returned data object type. Then click Finish to create the data access method:

  3. Switch to Design view, and drag onto the page a CheckBoxList control, a RadioButtonList control, a DropDownList control, a ListBox control, a Repeater control, and a DataList control, with each control on its own line, by pressing Return:

    click to expand

  4. Select the CheckBoxList control in the page, and go to the Properties dialog. Enter the name of the data access method AllPublishers() for the DataSource, the name of the column containing the publisher's name, pub_name, as the DataTextField, and the name of the column containing the ID of the publisher, pub_id, as the DataValueField property:

  5. Now repeat these three property settings for the RadioButtonList control, DropDownList control, and ListBox control. You'll see as you do it that each control changes from displaying Unbound to Databound.

  6. The Repeater and DataList controls don't have DataTextField and DataValueField properties, because they expect us to provide a template that defines the output to be created. However, we can set the DataSource property. Do this now by selecting them in turn and entering AllPublishers() for the DataSource property of each of these controls.

  7. To generate output from a Repeater control, we have to define the templates that the control will use. There are no fancy UI widgets to help in this case; we have to resort to getting out hands dirty and typing it all into the HTML window. Switch to HTML view and enter the declaration of the <HeaderTemplate> and <ItemTemplate>:

    <asp:Repeater  runat="server"               DataSource="<%# AllPublishers() %>">  <HeaderTemplate>  <b>Publisher List:</b><br />  </HeaderTemplate>  <ItemTemplate>  <%# DataBinder.Eval(Container.DataItem, "pub_name") %>   (ID: <%# DataBinder.Eval(Container.DataItem, "pub_id") %>)   <font size="-1"><i>   <%# DataBinder.Eval(Container.DataItem, "city") %>,   <%# DataBinder.Eval(Container.DataItem, "state") %>,   <%# DataBinder.Eval(Container.DataItem, "country") %> <br />  </i></font>  </ItemTemplate> </asp:Repeater> 

    We're displaying some text in the header of the control, followed by a line break, and then for each item in the data source we're displaying the values of the five columns with some odd items of text, HTML formatting, and commas to make it look better. The Repeater control adds no layout or formatting itself so we have to define exactly what we want for each part of the output.

  8. Switch back to Design view, and you'll see the layout we specified, and the fixed text content, rendered in the page. You can see how the declarations we use are literally translated into the output generated by the control:

    click to expand

  9. Select the DataList control in the page, as shown in the previous screenshot. In this case we have a couple of choices for how we define the content that the control will display. We can right-click on the control and create templates, or we can use the Auto Format and/or Property Builder Wizards (the links to which appear at the foot of the Properties dialog. The Auto Format and/or Property Builder are broadly the same as we saw used with the DataGrid control earlier in this chapter, so instead we'll use templates this time. Right-click on the DataList control and select Edit Templates... from the menu that appears:

    click to expand

  10. The Edit DataList1 Templates dialog appears. The two drop-down lists at the top allow you to select the template you want to edit, and the box below this is actually a design surface – the same as the ASP.NET page itself in Design view. So, you can drag-and-drop controls onto it, just as you do in the main editor window. Drag a Label control from the Toolbox onto it:

    click to expand

  11. Go to the Properties dialog and enter List of publishers: for the Text property. You can also edit the properties that control the appearance of the Label. We've set the Font Name property to Tahoma, and specified that it should be displayed in bold italic font.

  12. The Label control is automatically updated to show the results of these property settings. Drag a Horizontal Rule control from the HTML Elements section of the Toolbar onto the design surface as well, then select the FooterTemplate in the right-hand drop-down list of the template editor:

    click to expand

  13. Drag a Horizontal Rule control onto the FooterTemplate, and then select ItemTemplates in the left-hand drop-down list:

    click to expand

  14. The ItemTemplate is the section that is repeated for each row in the data source. Add some text and drag five Label controls onto the surface as shown in the following screenshot. We'll be binding these Label controls to the five columns in the data source later on:

    click to expand

  15. To separate the content generated by each ItemTemplate, we can specify content for the SeparatorTemplate. Select this from the left-hand drop-down list and drag a Horizontal Rule control onto it.

  16. Now we can specify the data-binding properties that will display the values from the columns in the Label control we placed into the ItemTemplate. Switch back to the ItemTemplate, and select the first Label control (if it has seemingly disappeared, leaving just the three boxes at the top left corner, this could be a bug, and you will need to remove the labels, replace them with new labels, then work with these new labels). In the main Properties window, select the (DataBindings) entry and click the button that appears:

  17. This opens the Label1 DataBindings dialog. We want to bind the Text property of the Label to the value in the pub_id column. Select the Text property in the left hand list of Bindable Properties (we can bind other properties to the values in the row if we wish, as you can see from this list). The Simple Binding: list displays the objects in the data source that we can bind to:

    click to expand

  18. Because we are binding to a method, and not to a SqlDataSourceControl, the list cannot extract the actual column details. Instead, we can select the DataItem entry, then click the Custom binding expression: option button and edit the expression that this creates to suit our requirements. For the Label control that will contain the value from the pub_id column of the row, we need the following expression:

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

    click to expand

  19. Now repeat this process for the other four Label controls. Select each one in turn in the Edit Templates dialog and bind the Text property to the appropriate column in the data source. The four data binding expressions required for this are:

     DataBinder.Eval(Container.DataItem, "pub_name") DataBinder.Eval(Container.DataItem, "city") DataBinder.Eval(Container.DataItem, "state") DataBinder.Eval(Container.DataItem, "country") 
  20. Now close the Edit Templates dialog. The DataList control in the page is updated to show the new layout and format:

    click to expand

  21. The final task is to tell the page that it should call the DataBind() method of all the controls when opened, so that the values returned by the AllPublishers() method are displayed in the controls. Select the entry for the Page from the drop-down list at the top of the Properties window, click the Events icon to show the events for the page, and double-click on the Load event.

  22. In the outline event handler, we must add the calls to the DataBind() method for the controls. We could call the DataBind() method for each control in turn, but there is a quicker way. If we call the DataBind() method of the Page object itself, it automatically calls DataBind() for all the controls on the page. Enter the highlighted code shown below to do just this:

    Sub Page_Load(sender As Object, e As EventArgs)  Page.DataBind() End Sub
  23. Now click the Start icon to run the page, and you'll see the results appear in the browser. We'll look at the results next, and see what the various list controls have created.

How It Works

The output from our example is a long page, so we'll examine it in sections. At the top of the page are the CheckBoxList and RadioButtonList controls. You can see that both display a list with one control for each publisher:

click to expand

If you view the source of the page in the browser, you can see what the list controls have created. For the CheckBoxList, we get an HTML table that contains an <input type="checkbox"> and a <label> in each cell. The publisher name, which we specified as the DataTextField property of the control, is used to populate the <label> elements:

 <table  border="0">  <tr>  <td>  <input  type="checkbox" name="CheckBoxList1:0" />  <label for="CheckBoxList1_0">New Moon Books</label>  </td>  </tr>  <tr>  <td>  <input  type="checkbox" name="CheckBoxList1:1" />  <label for="CheckBoxList1_1">Binnet & Hardley</label>  </td>  </tr>  ... </table> 

However, despite the fact that we specified the pub_id column as the DataValueField property, there are no value attributes on the checkboxes. Most HTML controls send their values to the server, when the <form> they are on is submitted, as control name=control-value. However, by default, a checkbox submits only control-name=on if it is checked, or nothing at all if it is not checked. ASP.NET uses this default behavior, and doesn't bother filling it in.

The Results from the RadioButtonList Control

The second control in the page is the RadioButtonList control. In this case, the DataTextField property sets the caption of each control, using the values from the pub_name column as we specified, and the DataValueField property sets the value attribute of each control:

 <table  border="0">  <tr>  <td>  <input  type="radio" name="RadioButtonList1"  value="0736" />  <label for="RadioButtonList1_0">New Moon Books</label>  </td>  </tr>  <tr>  <td>  <input  type="radio" name="RadioButtonList1"  value="0877" />  <label for="RadioButtonList1_1">Binnet & Hardley</label>  </td>  </tr>  ... </table> 

When the <form> containing this control is submitted, the single selected radio button sends the value RadioButtonList1=control-value to the server.

The Results from the DropDownList and ListBox Controls

The next section of the page contains the DropDownList, ListBox, and Repeater controls:

click to expand

The output generated for the DropDownList control is exactly what we expect. The DataTextField property sets the text of each <option> element that is generated within the <select> element, using the values from the pub_name column. The DataValueField property sets the value attribute of each <option> element, using the values from the pub_id column:

 <select name="DropDownList1" >  <option value="0736">New Moon Books</option>  <option value="0877">Binnet &amp; Hardley</option>  <option value="1389">Algodata Infosystems</option>  <option value="1622">Five Lakes Publishing</option>  <option value="1756">Ramona Publishers</option>  <option value="9901">GGG&amp;G</option>  <option value="9952">Scootney Books</option>  <option value="9999">Lucerne Publishing</option> </select> 

The ListBox control produces the same output with one exception. The opening <select> tag contains a size attribute set to the default value 4, so that four rows are displayed in the list:

 <select name="ListBox1"  size="4">   <option value="0736">New Moon Books</option>   ... </select> 

The Results from the Repeater Control

The Repeater control output, shown at the bottom of the previous screenshot, contains only the elements we declared within the templates that we added to the control definition. All the repeater has done is output the content of each template – it adds no formatting or other content of its own. So, we get the heading Publisher List: enclosed in <b> tags and followed by the <br /> element we declared in the <HeaderTemplate>. This is followed by the values from each row in the data source, intermixed with the elements and text we declared in the <ItemTemplate>:

 <b>Publisher List:</b><br /> New Moon Books (ID: 0736) <font size="-1"><i> Boston, MA, USA<br /> </i></font> Binnet & Hardley (ID: 0877) <font size="-1"><i>  Washington, DC, USA<br /> </i></font>  ... 

The Results from the DataList Control

The third section of the page contains the output from the DataList control:

click to expand

A DataList control (by default) generates an HTML table with one cell for each row in the data source, and inserts the values from the data source into these cells. It also adds some formatting to the table and its content, depending on the selections we make in the various style properties after we've added the control to our page.

In the following listing of the output generated by the DataList control, you can see the enclosing HTML table, and each row and cell in the table. The first cell is the content generated from our <HeaderTemplate> – the Label control we placed here creates a <span> element when the page is executed. The other cells contain a series of <span> elements generated by the five Label controls we placed in the <ItemTemplate> of the control declaration, each displaying the values from the rows in the data source:

 <table  cellspacing="0" border="0"  style="border-collapse:collapse;">  <tr>  <td>  <span  style="font-family:Tahoma;  font-weight:bold;font-style:italic;">List of publishers:</span>  <hr />  </td>  </tr>  <tr>  <td>  <p>ID:  <span  style="font-weight:bold;">  0736  </span>  &nbsp; Name:  <span  style="font-weight:bold;">  New Moon Books  </span>  </p>  <p>  Address:  <span  style="font-weight:bold;">  Boston  </span>,  <span  style="font-weight:bold;">  MA  </span>,  <span  style="font-weight:bold;">  USA  </span>  </p>  </td>  </tr>   ... </table> 




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net