Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ASP .NET Web Developer s Guide - Mesbah Ahmed, Chris Garrett

.pdf
Скачиваний:
37
Добавлен:
24.05.2014
Размер:
7.32 Mб
Скачать

130 Chapter 3 • ASP Server Controls

</form></body></html> The

Databound ListControls Family

In this section, we will discuss the Databound ListControls.This family of controls is new to ASP developers.These controls provide rapid application development to display and manipulate data from any data source.The following controls shown in Table 3.3 belong to this family.

Table 3.3 The Databound ListControls Family

CheckBoxList

DataGrid

DataList

DropDownList

HtmlSelect

ListBox

RadioButtonList

Repeater

In earlier sections of this chapter, we illustrated data binding examples on HtmlSelectControl (Figure 3.36), and asp:ListBox control (Figure 3.48).We may use similar techniques to bind data to a CheckBoxList, DropDownList, or a RadioButtonList control. In this section, we will instead introduce three of the most prominent members of this family: Repeater, DataList, and DataGrid.

In our demonstrations, we will use a sample database named Products.mdb, which you can find on the CD accompanying this book. It is a Microsoft Access 2000 database. It contains only one table, named Products. Figure 3.66 shows some sample records in this table. Basically, the table has four columns: ProductId (AutoNumbered Long Integer), ProductName (Text 50), ImagePath (Text 150) and Price (Currency).The ImagePath column contains the name and location of an image relative to a virtual directory.

Figure 3.66 Sample Records in the Products Table

You will learn database connectivity issues in Chapter 7.When we connect to a database, we typically run a query and populate a data table of a data set with the results of the query. In this chapter, we will not discuss the mechanics of how to connect to a database.To understand the remainder of this chapter, it will be sufficient to know that we can bind a ListControl to a data table of a data set. In most of the examples, we will use a subprocedure to populate a DataSet named

www.syngress.com

ASP Server Controls • Chapter 3

131

myDataSet. The listing of a similar subprocedure is shown in Figure 3.67. Temporarily, we will treat this code as a black box (until you have read Chapter 7).This code will populate a data set and subsequently bind a specific ListControl to the data set.

Figure 3.67 Populating myDataSet and Binding a ListControl

1.Sub bindListControl()

2.Dim myConn As OleDbConnection

3.Dim myOleDbAdapter As OleDbDataAdapter

4.Dim connStr, sqlStr As String

5.Dim myDataSet As New Dataset

6.connStr="Provider=Microsoft.Jet.OLEDB.4.0;" _

7.+ "Data Source=D:\Products.mdb"

8.sqlStr="SELECT ProductId, ProductName, Price, ImagePath " _

9.+ "FROM Products WHERE Price>45.00 ORDER BY Price"

10.myConn= New OleDbConnection(connStr)

11.myConn.Open()

12.myOleDbAdapter =New OleDbDataAdapter(sqlStr,myConn)

13.myOleDbAdapter.Fill(myDataSet,"dtProducts")

14.repeater1.DataSource=myDataSet.Tables("dtProducts")

15.repeater1.DataBind()

16.End Sub

NOTE

To try the examples in the remainder of this chapter, you will need to do the following:

1.Copy the Products.mdb in your hard drive. In each sample program, locate the bindListControl subprocedure (shown in Figure 3.67), and adjust its line number 7 to specify your drive. For example, if you have loaded Products.mdb in your C drive, then change line number 7 of the bindListControl procedure to Data Source=C:\Products.mdb.

2.Copy the image files from Chapter3/Images directory of the CD and paste them in the Images subdirectory of your virtual directory.

www.syngress.com

132 Chapter 3 • ASP Server Controls

Actually, the preceding code is not difficult to understand. First we have defined the necessary object variables to connect to a database. In lines 6 and 7, we have provided the information about the driver to be used, and the location of the database. A SQL statement is constructed in lines 8 and 9.We have instantiated the connection object in line 10, and opened the connection in line 11. An OleDbDataAdapter object was instantiated using the SQL string and connection string.The dtProducts data table of the myDataSet data set is populated in line 14. Then we set the DataSource property of a repeater control to the dtProducts. Finally, in line 15, we have bound the repeater to its data source.We will be using similar logic in each of our ListControl examples with minor variations in the SQL statement.

Using the Repeater Server Control

The Repeater is essentially a template-driven data-bound list.The Repeater control allows fragments of html tags inside the templates. For example, we may start a <table> in the Header template and end the table (</table>) in the Footer template, if necessary.The control binds its Item collection to the its DataSource.We may use the Item Command event to process events that are raised from the templates of the control.

We may specify the following templates for a Repeater control:

Item Template Specifies the DataItem fields to be displayed, and the layout (required).

AlternatingItemTemplate Defines the layout of the zero-based odd indexed items (optional).

SeparatorTemplate In this template, we can specify the separator such as <hr> or <br> between repeating items (optional).

HeaderTemplate Specifies the header of the list (optional).

FooterTemplate Specifies the footer of the list (optional).

We will provide two examples to illustrate the behavior of a repeater control. In the first example, we will display our product information using a repeater control. In the second example, we will illustrate how to capture an event from a control residing inside a repeater control (known as Event Bubbling).

Displaying Data in a Repeater Control

Suppose that we want to display our products data for the products that cost more than $45.00.The expected display for this application is shown in Figure 3.68.The

www.syngress.com

ASP Server Controls • Chapter 3

133

code for this application is shown in Figure 3.69 and is also available in the accompanying CD in a file named Repeater1.aspx.

Figure 3.68 Displaying Data in a Repeater Control

In this application we have defined three templates for our repeater.The Header template starts an HTML table with a <table> tag.The Footer template completes the table with a </table> tag.The ItemTemplate contains the table cells to house the data values.We will extract data from the Products table from the Products.mdb database. First we will populate a data set object, and then we will bind the repeater to this data set. Detailed code for populating the data set and binding the repeater is shown in Figure 3.69.

Figure 3.69 Repeater1.aspx

<!— Chapter3/Repeater1.aspx —>

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.OleDb" %> <html><head></head>

<script language="VB" Debug="true" runat="server"> Sub Page_Load(src As Object, e As EventArgs)

If Not IsPostBack

bindListControl

End If

End Sub

Sub bindListControl()

Dim myConn As OleDbConnection

Continued

www.syngress.com

134 Chapter 3 • ASP Server Controls

Figure 3.69 Continued

Dim myOleDbAdapter As OleDbDataAdapter

Dim connStr, sqlStr As String

Dim myDataSet As New Dataset connStr="Provider=Microsoft.Jet.OLEDB.4.0;" _

+ "Data Source=D:\Products.mdb"

sqlStr="SELECT ProductId, ProductName, Price, ImagePath " _ + "FROM Products WHERE Price>45.00 ORDER BY Price"

myConn= New OleDbConnection(connStr) myConn.Open()

myOleDbAdapter =New OleDbDataAdapter(sqlStr,myConn) myOleDbAdapter.Fill(myDataSet,"dtProducts") repeater1.DataSource=myDataSet.Tables("dtProducts") repeater1.DataBind()

End Sub </script>

<body><h2><center>Cathy's E-Shop</h2>

<asp:Repeater id="repeater1" runat="server" >

<HeaderTemplate><table></HeaderTemplate>

<ItemTemplate><tr>

<td><asp:Image height=100 width=100

Img src='<%# Container.DataItem("ImagePath")%>' runat="server"/>

</td> <td>Product ID:

<%# Container.DataItem("ProductId")%><br>

Description: <b><i>

<%# Container.DataItem("ProductName")%></b><i><br>

<b>Unit Price:

<%# FormatCurrency(Container.DataItem("Price"))%></b><br> </td></tr>

</ItemTemplate>

<FooterTemplate>

</table>

Continued

www.syngress.com

ASP Server Controls • Chapter 3

135

Figure 3.69 Continued

</FooterTemplate>

</asp:Repeater>

</center></body></html>

Once a data table has been populated, only two statements are required to bind a repeater.We need to set its DataSource property to the appropriate data table, and then we can apply its DataBind() method to accomplish the job.These two statements are as follows:

repeater1.DataSource=myDataSet.Tables("dtProducts").DefaultView

repeater1.DataBind()

We know that the dtProducts table of our data set will contain columns like ProductId, ProductName, etc. Our objective is to develop an ItemTemplate where we want to specify which column should be shown in what format. For each row of the table in the data set, the repeater will employ this template to display the data. A typical way to display a desired field is to use the <%# Container

.DataItem(“columnName”)%> syntax. For example, the following ItemTemplate will display the ProductId in a cell of a table (assuming that the <table> tag has been specified in the HeaderTemplate):

<ItemTemplate>

<tr><td><%# Container.DataItem("ProductId") %>

</td></tr>

</ItemTemplate>

Similarly, as shown in the following statement, an Img control can also be specified to render an image:

Img src='<%# Container.DataItem("ImagePath") %>'

Using Event Bubbling and Capturing

Events in a Repeater Control

You can use the Repeatercontrol to accomplish much more than just displaying data. In its templates, we may insert other controls. In this example, we will place an asp:Button control in the ItemTemplate of our repeater. As shown in Figure 3.70, the repeater will display a button for every record in its data source.We may capture the click event of this button and perform appropriate processing. In this

www.syngress.com

136 Chapter 3 • ASP Server Controls

example, we will just display the selected ProductId.Would it not be an excellent way to enable the users to select items in a shopping cart application? On each selection, we could have written the selected data in a database.

Figure 3.70 Event Bubbling in a Repeater Control

The complete code for this application is shown in Figure 3.71 (and is also available in a file named Repeater2.aspx, in the accompanying CD). A repeater is essentially a container control.When we defined the repeater, we set its OnItemSelection attribute to a function named “showSelection” as follows:

<asp:Repeater id=repeater1 OnItemCommand="showSelection" runat="server">

Whenever a child control in a repeater raises an event, it will report it to its parent, the repeater.The repeater will fire the showSelection function.This phenomenon of a child reporting an event to its parent is known as Event Bubbling. A Repeater (or any such parent) may receive events from many embedded child controls; hence, it may not clearly identify which of the children raised the event. Therefore, the child needs to pass certain information about itself when reporting an event.This is accomplished by the second parameter of the event procedure. The second parameter is defined as e As RepeaterCommandEventArgs. Naturally, the parameter e will be of a RepeaterCommandEventArgs object type (data type), and its CommandSource will identify the child raising the event. Similar event bubbling is employed in many cases where a parent control contains child controls.That is how, as shown in the following code excerpt, we are displaying the value of the ProductId in our message:

Sub showSelection(s As Object, e As RepeaterCommandEventArgs)

lblMessage.Text="You have selected ProductID : " _

www.syngress.com

ASP Server Controls • Chapter 3

137

+ e.CommandSource.Text

End Sub

But, wait a minute! How did we get the ProductId value displayed on a button anyway? Well, that is actually very easy. As shown in the following code excerpt, the button was placed inside the ItemTemplate, and we set its text property to the “<%# Container.DataItem(“ProductId”)%>”.

<ItemTemplate><tr>

<td>Product ID:

<asp:Button text=<%# Container.DataItem("ProductId")%>

runat="server"/>

</ItmpTemplate

The remainder of the code is self-explanatory.

Figure 3.71 Repeater2.aspx

<!— Chapter3/Repeater2.aspx —>

<%@ Import Namespace="System.Data"%>

<%@ Import Namespace="System.Data.OleDb"%> <html><head></head>

<script language="VB" Debug="true" runat="server"> Sub Page_Load(src As Object, e As EventArgs)

If Not IsPostBack Then

bindListControl

End If

End Sub

Sub bindListControl()

Dim myConn As OleDbConnection

Dim myOleDbAdapter As OleDbDataAdapter

Dim connStr, sqlStr As String

Dim myDataSet As New Dataset connStr="Provider=Microsoft.Jet.OLEDB.4.0; " _

+ "Data Source=D:\Products.mdb"

sqlStr="SELECT ProductId, ProductName, Price, ImagePath " _ + "FROM Products WHERE Price>79.00 ORDER BY Price"

myConn= New OleDbConnection(connStr)

Continued

www.syngress.com

138 Chapter 3 • ASP Server Controls

Figure 3.71 Continued

myConn.Open()

myOleDbAdapter =New OleDbDataAdapter(sqlStr,myConn)

myOleDbAdapter.Fill(myDataSet,"dtProducts")

repeater1.DataSource=myDataSet.Tables("dtProducts")

repeater1.DataBind()

End Sub

Sub showSelection(s As Object, e As RepeaterCommandEventArgs)

lblMessage.Text="You have selected ProductID : " _

+e.CommandSource.Text

'Some references convert the CommandSource object to a button object

'first as shown below. It is not necessary though.

'CType(e.CommandSource, Button).Text

End Sub </script>

<body><form runat= "server"><center>

<asp:Repeater id=repeater1 OnItemCommand="showSelection" runat="server"> <HeaderTemplate><table></HeaderTemplate>

<ItemTemplate><tr>

<td><asp:Image height=100 width=100

Img src='<%# Container.DataItem("ImagePath") %>' runat="server"/> </td><td> Product ID:

<asp:Button text=<%# Container.DataItem("ProductId")%> runat="server"/> <br>Description: <b><i>

<%# Container.DataItem("ProductName")%></b></i><br> <b>Unit Price:

<%# FormatCurrency(Container.DataItem("Price"))%></b><br> <td></tr>

</ItemTemplate>

<FooterTemplate></table></FooterTemplate>

</asp:Repeater>

<asp:Label id=lblMessage runat="server" ForeColor="Brown" Font-Size="14pt" Font-Weight="700" Font-Name="Arial Black,Arial">

</asp:Label></center>

</form></body></html>

www.syngress.com

ASP Server Controls • Chapter 3

139

Using the DataList Control

The DataList control is similar to the Repeater control. However, it has some additional properties and templates that you can use to display its data in a diverse fashion.The Repeater control does not have any built-in layout or style.We are forced to specify all formatting-related HTML elements and style tags. On the other hand, a DataList control provides more flexibility to display data in a desired layout. It also provides data selection and editing capabilities. How does it do it? Well, in addition to the five templates that a repeater has, the DataList control has two more templates: SelectedItemTemplate, and EditItemTemplate. These templates are useful for allowing data selection and data editing functionalities. Furthermore, the RepeatDirection and RepeatColumns properties of a DataList control can be exploited to lay out the data in horizontal or vertical fashions.

In this section, we will present two examples.The first example will illustrate the use of the RepeatDirection and RepeatColumns properties.The second example will demonstrate how to enable the user to select a particular data being displayed using a DataList.

Using RepeatDirection and RepeatColumn

Properties of a DataList

In this example, our objective is to display the product’s data in a fashion as shown in Figure 3.72. A data table in a data set is essentially a relational databaselike table in the computer’s cache. It has rows (records) and columns (fields) of data extracted from the database.When we bind a ListControl to a data table, each record of the data table becomes an Item in the ItemList collection of the ListControl. In this particular example, we want to display three of these Items in each row of our display (horizontally).This is why we have defined the

DataControl as follows:

<asp:DataList id="dataList1" border=0

RepeatDirection="Horizontal" RepeatColumns="3" runat="server">

The remainder of the code for this application, as shown in Figure 3.73, is straightforward.The code is also available in a file named DataList1.aspx in the accompanying CD.

www.syngress.com