In the following sections, you learn how to use data binding with several ASP.NET controls, such as the Repeater , DropDownList , RadioButtonList , and ListBox controls. You learn how to use the DataSource property to bind the items from a data source such as a database table or an ArrayList to a control. You also learn how to use templates to format how the data is displayed. Binding to the Repeater ControlThe Repeater control does not display anything unless it is bound to a data source. Typically, you use the Repeater control to display the records from a database table, although you can also bind the control to other data sources such as collections. Imagine that you have a database table named Authors and you want to display all the rows from this database table within an ASP.NET page. The page in Listing 10.5 demonstrates how you can display the rows by using a Repeater control (see Figure 10.4). Listing 10.5 Repeater.aspx<%@ Import Namespace="System.Data.SqlClient" %> <Script Runat="Server"> Sub Page_Load Dim conPubs As SqlConnection Dim cmdSelect As SqlCommand Dim dtrAuthors As SqlDataReader ' Retrieve records from database conPubs = New SqlConnection( "Server=localhost;UID=sa;PWD=secret;Database=Pubs" ) cmdSelect = New SqlCommand( "Select * From Authors", conPubs ) conPubs.Open() dtrAuthors = cmdSelect.ExecuteReader() ' Bind to Repeater rptAuthors.DataSource = dtrAuthors rptAuthors.DataBind() dtrAuthors.Close() conPubs.Close() End Sub </Script> <html> <head><title>Repeater.aspx</title></head> <body> <form Runat="Server"> <asp:Repeater ID="rptAuthors" Runat="Server"> <ItemTemplate> <%# Container.DataItem( "au_lname" ) %> </ItemTemplate> </asp:Repeater> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Figure 10.4. The Repeater control.
All the work in Listing 10.5 is accomplished within the Page_Load subroutine. This subroutine opens a connection to a Microsoft SQL Server database and retrieves all the records from the Authors database table into a SqlDataReader . Next, the SqlDataReader is assigned to the DataSource property of the Repeater control. Finally, the DataBind() method is called, and the items from the SqlDataReader are bound to the Repeater control. The Repeater control is declared with the following tags: <asp:Repeater ID="dtrAuthors" Runat="Server"> <ItemTemplate> <%# Container.DataItem( "au_lname" ) %> </ItemTemplate> </asp:Repeater> The au_lname column for each of the records retrieved from the Authors table is displayed by the Repeater control. The following data binding expression represents the au_lname column: <%# Container.DataItem( "au_lname" ) %> Notice that this expression uses the data binding tags <%# and %> . This expression does not have a value until the Repeater control's DataBind() method is called. Using TemplatesIf you look closely at the ASP.NET page in Listing 10.5, you notice that the Repeater control uses a tag named <ItemTemplate> . The ItemTemplate is one example of a template. The Repeater control uses templates to control formatting. Templates enable you to apply complicated formatting to each of the items displayed by a control. You can place any HTML tags that you please within a template. A template can also contain other controls and even inline ASP.NET code. The Repeater control actually supports five types of templates:
Now, imagine that you want every other item displayed by the Repeater control to have a purple and italic font, and you want a horizontal rule to separate the items (see Figure 10.5). You can make these changes by using the following Repeater control declaration: <asp:Repeater ID="rptAuthors" Runat="Server"> <ItemTemplate> <%# Container.DataItem( "au_lname" ) %> </ItemTemplate> <AlternatingItemTemplate> <font color="purple"><i> <%# Container.DataItem( "au_lname" ) %> </i></font> </AlternatingItemTemplate> <SeparatorTemplate> <hr> </SeparatorTemplate> </asp:Repeater> Figure 10.5. Using templates with a Repeater control.
You also can use templates with a Repeater control to format the items displayed by the control in an HTML table, as illustrated by the page in Listing 10.6. Listing 10.6 RepeaterTable.aspx<%@ Import Namespace="System.Data.SqlClient" %> <Script Runat="Server"> Sub Page_Load Dim conPubs As SqlConnection Dim cmdSelect As SqlCommand Dim dtrAuthors As SqlDataReader ' Retrieve records from database conPubs = New SqlConnection( "Server=localhost;UID=sa;PWD=secret;Database=Pubs" ) cmdSelect = New SqlCommand( "Select * From Authors", conPubs ) conPubs.Open() dtrAuthors = cmdSelect.ExecuteReader() ' Bind to Repeater rptAuthors.DataSource = dtrAuthors rptAuthors.DataBind() dtrAuthors.Close() conPubs.Close() End Sub </Script> <html> <head><title>RepeaterTable.aspx</title></head> <body> <form Runat="Server"> <asp:Repeater ID="rptAuthors" Runat="Server"> <HeaderTemplate> <table border=1 cellpadding=4> <tr bgcolor="#eeeeee"> <th>First Name</th> <th>Last Name</th> <th>Phone</th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td><%# Container.DataItem( "au_fname" ) %></td> <td><%# Container.DataItem( "au_lname" ) %></td> <td><%# Container.DataItem( "phone" ) %></td> </tr> </ItemTemplate> <AlternatingItemTemplate> <tr bgcolor="lightyellow"> <td><%# Container.DataItem( "au_fname" ) %></td> <td><%# Container.DataItem( "au_lname" ) %></td> <td><%# Container.DataItem( "phone" ) %></td> </tr> </AlternatingItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </form> </body> </html> The C# version of this code can be found on the CD-ROM. In the page in Listing 10.6, the opening HTML <table> tag is created in the Repeater control's HeaderTemplate . Each table row is displayed by either the ItemTemplate (with a white background) or the AlternatingItemTemplate (with a yellow background). Finally, the FooterTemplate closes the HTML table (see Figure 10.6). Figure 10.6. Displaying an HTML table with the Repeater control.
View State and the Repeater ControlThe Repeater control, like other server controls, participates in a page's view state. By default, this means that every time you create a Repeater control on a page, all the information for each item in the control is copied into the hidden VIEWSTATE form field. Typically, you use the Repeater control simply to display a list of items, and you are not interested in preserving its view state across multiple page submissions. Because preserving a Repeater control's view state can slow down the rendering of a page, it is wise to disable view state for this control when you don't need it. To disable view state for an individual control, set the EnableViewState property to the value False like this: <asp:Repeater ID="rptAuthors" EnableViewState="False" Runat="Server"> Binding to the DropDownList ControlBinding data to a DropDownList control is similar to binding data to a Repeater control. The general technique is to assign a data source to the DropDownList control's DataSource property and call the DataBind() method. NOTE For more information on the DropDownList control, see Chapter 2, "Building Forms with Web Server Controls." You must set one additional property with the DropDownList control. You must set its DataTextField property to indicate the column that you want to bind to the control. NOTE The DropDownList control has a DataValueField property. You need to set this property when you want different Value and Text properties associated with each item in a DropDownList control. The page in Listing 10.7, for example, contains a DropDownList control that is bound to the au_lname column in the Authors database table (see Figure 10.7). Listing 10.7 DropDownList.aspx<%@ Import Namespace="System.Data.SqlClient" %> <Script Runat="Server"> Sub Page_Load If Not IsPostBack Then Dim conPubs As SqlConnection Dim cmdSelect As SqlCommand Dim dtrAuthors As SqlDataReader conPubs = New SqlConnection( "Server=localhost;UID=sa;PWD=secret;Database=Pubs" ) conPubs.Open() cmdSelect = New SqlCommand( "Select au_lname From Authors", conPubs ) dtrAuthors = cmdSelect.ExecuteReader() dropAuthors.DataSource = dtrAuthors dropAuthors.DataTextField = "au_lname" dropAuthors.DataBind() dtrAuthors.Close() conPubs.Close() End If End Sub </Script> <html> <head><title>DropDownList.aspx</title></head> <body> <form Runat="Server"> <asp:DropDownList ID="dropAuthors" Runat="Server" /> <asp:Button Text="Pick Author!" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Figure 10.7. Binding data to a DropDownList control.
In Listing 10.7, the database connection is opened, and the records from the Authors database table are retrieved into the DataReader in the Page_Load subroutine. The DataReader is bound to the DropDownList control's DataSource property, the DataTextField is assigned the value au_lname , and the DataBind() method is called. One thing you should notice about the Page_Load subroutine is that it uses the IsPostBack property to check whether the page has already been submitted. The database records are retrieved and bound to the DropDownList control when the page is first opened, but not thereafter. The list of author last names is preserved in the page's view state when the page is posted back to the server. You need to retrieve the records from the database only the first time the page is opened, and the records will be preserved in the page's hidden __VIEWSTATE form field. Neglecting to check the IsPostBack property produces two bad results. First, it hurts the performance of the page because the records need to be retrieved from the database every time the page is opened. Retrieving records from a database is a resource- intensive task. Second, if a user selects an author from the DropDownList control, and you rebind the DropDownList to the database table, the user's selection is lost. Binding a DropDownList resets the SelectedIndex and SelectedItem properties of the control. Binding to the RadioButtonList ControlYou can bind a RadioButtonList control to a data source by setting its DataSource and DataTextField properties and calling its DataBind() method. NOTE For more information on the RadioButtonList control, see Chapter 2. The page in Listing 10.8, for example, contains a RadioButtonList control that is bound to the Categories table in the Northwind database (see Figure 10.8). Listing 10.8 RadioButtonList.aspx [View full width] <%@ Import Namespace="System.Data.SqlClient" %> <Script Runat="Server"> Sub Page_Load If Not IsPostBack Then Dim conNorthwind As SqlConnection Dim cmdSelect As SqlCommand Dim dtrCategories As SqlDataReader conNorthwind = New SqlConnection( "Server=localhost;UID=sa;PWD=secret;Database=Northwind" ) cmdSelect = New SqlCommand( "Select CategoryName From Categories", conNorthwind ) conNorthwind.Open() dtrCategories = cmdSelect.ExecuteReader() radlCategories.DataSource = dtrCategories radlCategories.DataTextField = "CategoryName" radlCategories.DataBind() dtrCategories.Close() conNorthwind.Close() End If End Sub </Script> <html> <head><title>RadioButtonList.aspx</title></head> <body> <form Runat="Server"> <asp:RadioButtonList ID="radlCategories" Runat="Server" /> <p> <asp:Button Text="Select A Category!" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Figure 10.8. Binding data to a RadioButtonList control.
Remember to use the IsPostBack property to bind the RadioButtonList to the DataReader only when the page is opened the first time. If you neglect to do so, the selected radio button is lost every time the page is submitted. NOTE The RadioButtonList control has a DataValueField property. You need to set this property when you want different Value and Text properties associated with each item in a RadioButtonList control. Binding to the CheckBoxList ControlYou can bind a data source, such as a database table, to a CheckBoxList control by setting the control's DataSource and DataTextField properties and calling its DataBind() method. NOTE For more information on the CheckBoxList control, see Chapter 2. The page in Listing 10.9 illustrates how you can bind a CheckBoxList control to the Titles table in the Pubs database (see Figure 10.9). Listing 10.9 CheckBoxList.aspx<%@ Import Namespace="System.Data.SqlClient" %> <Script Runat="Server"> Sub Page_Load If Not IsPostBack Then Dim conPubs As SqlConnection Dim cmdSelect As SqlCommand Dim dtrTitles As SqlDataReader conPubs = New SqlConnection( "Server=localhost;UID=sa;PWD=secret;Database=Pubs" ) cmdSelect = New SqlCommand( "Select Title From Titles", conPubs ) conPubs.Open() dtrTitles = cmdSelect.ExecuteReader() chklTitles.DataSource = dtrTitles chklTitles.DataTextField = "Title" chklTitles.DataBind() dtrTitles.Close() conPubs.Close() End If End Sub </Script> <html> <head><title>CheckBoxList.aspx</title></head> <body> <form Runat="Server"> <asp:CheckBoxList ID="chklTitles" Runat="Server" /> <p> <asp:Button Text="Select A Title!" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Figure 10.9. Binding data to a CheckBoxList control.
Again, remember to check the IsPostBack property so that you bind the CheckBoxList control only the first time the page is opened. If you neglect to do so, the selected check boxes are lost when the form is submitted. NOTE The CheckBoxList control has a DataValueField property. You need to set this property when you want different Value and Text properties associated with each item in a CheckBoxList control. Binding to a ListBox ControlThe procedure for binding to a ListBox control is the same as for the other list controls. To bind a data source ”such as a database table or ArrayList ”to a ListBox control, set the control's DataSource and DataTextField properties and call the control's DataBind() method. NOTE For more information on the ListBox control, see Chapter 2. The page in Listing 10.10 illustrates how you can bind a ListBox control to the Products table in the Northwind database (see Figure 10.10). Listing 10.10 ListBox.aspx [View full width] <%@ Import Namespace="System.Data.SqlClient" %> <Script Runat="Server"> Sub Page_Load If Not IsPostBack Then Dim conNorthwind As SqlConnection Dim cmdSelect As SqlCommand Dim dtrProducts As SqlDataReader conNorthwind = New SqlConnection( "Server=localhost;UID=sa;PWD=secret;Database=Northwind" ) conNorthwind.Open() cmdSelect = New SqlCommand( "Select ProductName From Products", conNorthwind ) dtrProducts = cmdSelect.ExecuteReader() lstProducts.DataSource = dtrProducts lstProducts.DataTextField = "ProductName" lstProducts.DataBind() dtrProducts.Close() conNorthwind.Close() End If End Sub </Script> <html> <head><title>ListBox.aspx</title></head> <body> <form Runat="Server"> <asp:ListBox ID="lstProducts" Runat="Server" /> <p> <asp:Button Text="Select A Product!" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Figure 10.10. Binding data to a ListBox control.
Remember to check the IsPostBack property before binding to the ListBox control. If you bind it after the page is submitted, the selected list item is lost. NOTE The ListBox control has a DataValueField property. You need to set this property when you want different Value and Text properties associated with each item in a ListBox control. Binding to Other ControlsThe following sections describe methods of binding to controls that do not have a DataSource property. You learn how to bind to a list of Image , HyperLink , Button , and LinkButton controls. Binding to Image ControlsThe trick to binding to a list of Image controls to a data source is to place the controls in a Repeater control. You can bind the Repeater control to a data source, thereby indirectly binding all the Image controls to the data source. Imagine that you have a list of image URLs stored in a database table and you want to display these images in an ASP.NET page (see Figure 10.11). The page in Listing 10.11 illustrates how you can do so. Listing 10.11 ImageList.aspx<%@ Import Namespace="System.Data.SqlClient" %> <Script Runat="Server"> Sub Page_Load If Not IsPostBack Then Dim conMyData As SqlConnection Dim cmdSelect As SqlCommand Dim dtrImages As SqlDataReader conMyData = New SqlConnection( "Server=localhost;UID=sa;PWD=secret;Database=myData" ) conMyData.Open() cmdSelect = New SqlCommand( "Select image_url From myImages", conMyData ) dtrImages = cmdSelect.ExecuteReader() rptImages.DataSource = dtrImages rptImages.DataBind() dtrImages.Close() conMyData.Close() End If End Sub </Script> <html> <head><title>ImageList.aspx</title></head> <body> <form Runat="Server"> <asp:Repeater ID="rptImages" Runat="Server"> <ItemTemplate> <br> <asp:Image ImageURL='<%# Container.DataItem( "image_url" ) %>' Runat="Server" /> </ItemTemplate> </asp:Repeater> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Figure 10.11. Displaying a list of images.
In the Page_Load subroutine in this listing, the image URLs are retrieved into a DataReader from the myImages database table. The DataReader is bound to the DataSource property of the Repeater control, which displays all the images from the database table by rendering an Image control for each image URL. The Image control's ImageUrl property is bound to the image _ url column of the data source, and the image is displayed. NOTE You can create the myImages database table by executing the following statements from SQL Query Analyzer: Create Table myImages ( Image_URL Varchar( 200 ) ) go Insert myImages Values ( 'starburst.gif' ) Insert myImages Values ( 'gear.gif' ) Insert myImages Values ( 'flower.gif' ) go You'll need to change the database parameter in the SQL connection string to the proper value for your database before you can use this table. Instead of using Image controls to display images, you also can use the HTML <img> tag. Using the <img> tag instead of the Image control requires fewer server resources. Here's how you would bind to an HTML <img> tag in a Repeater control: <asp:Repeater ID="rptImages" Runat="Server"> <ItemTemplate> <br> <img src='<%# Container.DataItem( "image_url" ) %>'> </ItemTemplate> </asp:Repeater> Binding to HyperLink ControlsYou can display a list of HyperLink controls with the Repeater control. To do so, simply place the HyperLink control within the ItemTemplate of the Repeater control. The page in Listing 10.12 illustrates how to use the Repeater control to display a list of favorite links (see Figure 10.12). Listing 10.12 HyperLinkList.aspx<%@ Import Namespace="System.Data.SqlClient" %> <Script Runat="Server"> Sub Page_Load If Not IsPostBack Then Dim conMyData As SqlConnection Dim cmdSelect As SqlCommand Dim dtrLinks As SqlDataReader conMyData = New SqlConnection( "Server=localhost;UID=sa;PWD=secret;Database=myData" ) cmdSelect = New SqlCommand( "Select * From FavLinks", conMyData ) conMyData.Open() dtrLinks = cmdSelect.ExecuteReader() rptLinks.DataSource = dtrLinks rptLinks.DataBind() dtrLinks.Close() conMyData.Close() End If End Sub </Script> <html> <head><title>HyperLinkList.aspx</title></head> <body> <form Runat="Server"> <asp:Repeater ID="rptLinks" Runat="Server"> <ItemTemplate> <li> <ASP:HyperLink Text='<%# Container.DataItem( "link_title" ) %>' NavigateURL='<%# Container.DataItem( "link_url" ) %>' Runat="Server" /> </ItemTemplate> </asp:Repeater> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Figure 10.12. Displaying a list of hyperlinks .
The Repeater control in Listing 10.12 displays a list of links from a table named FavLinks . NOTE You can create the FavLinks table by executing the following statements from SQL Query Analyzer: Create Table FavLinks ( Link_Title Varchar( 200 ), Link_URL Varchar( 200 ) ) go Insert FavLinks Values ( 'Superexpert', 'http://www.Superexpert.com' ) Insert FavLinks Values ( 'AspWorkshops', 'http://www.AspWorkshops.com' ) Instead of using HyperLink controls to display hyperlinks, you can use the HTML anchor tag. Using the anchor tag instead of the HyperLink control requires slightly fewer server resources. Here's how you would bind to an HTML anchor tag in a Repeater control: [View full width]
Binding to Button and LinkButton ControlsYou can bind Button and LinkButton controls to a data source by using the Repeater control. To do so, simply place a Button or LinkButton control within the ItemTemplate of the Repeater control. The page in Listing 10.13 illustrates how to bind LinkButton controls to a data source (see Figure 10.13). Listing 10.13 LinkButtonList.aspx [View full width] <%@ Import Namespace="System.Data.SqlClient" %> <Script Runat="Server"> Sub Page_Load If Not IsPostBack Then Dim conNorthwind As SqlConnection Dim cmdSelect As SqlCommand Dim dtrCategories As SqlDataReader conNorthwind = New SqlConnection( "Server=localhost;UID=sa;PWD=secret;Database=Northwind" ) cmdSelect = New SqlCommand( "Select CategoryName From Categories", conNorthwind ) conNorthwind.Open() dtrCategories = cmdSelect.ExecuteReader() rptCategories.DataSource = dtrCategories rptCategories.DataBind() dtrCategories.Close() conNorthwind.Close() End If End Sub Sub Button_Click( s As Object, e As RepeaterCommandEventArgs ) Dim lbtnSelected As LinkButton lbtnSelected = e.Item.Controls( 1 ) lblCategory.Text = "You selected " & lbtnSelected.Text End Sub </Script> <html> <head><title>LinkButtonList.aspx</title></head> <body> <form Runat="Server"> <asp:Repeater ID="rptCategories" OnItemCommand="Button_Click" Runat="Server"> <ItemTemplate> <li> <asp:LinkButton Text='<%# Container.DataItem( "CategoryName" ) %>' Runat="Server" /> </ItemTemplate> </asp:Repeater> <p> <asp:Label ID="lblCategory" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Figure 10.13. Displaying a list of LinkButton controls.
One question that arises when working with Button and LinkButton controls is how to discover which control is clicked within the Repeater control. The page in Listing 10.13 captures and displays the LinkButton control that was clicked by taking advantage of event bubbling. Event bubbling enables you to create one subroutine that handles all the events raised by the controls contained within a control. When you click a LinkButton control in the Repeater control, the subroutine associated with the Repeater control's OnItemCommand is executed. In the page in Listing 10.13, the Button_Click subroutine is executed when you click a LinkButton . Within the Button_Click subroutine, the Text property of the selected LinkButton is retrieved and displayed in a Label control. Event bubbling is discussed in detail in Chapter 11, "Using the DataList and DataGrid Controls." |