
C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#
.pdfintQty(0)=300
intQty(1)=500
intQty(2)=150
intQty(3)=250
intQty(4)=350
'create a DataTable
DataTable1 = New DataTable
DataTable1.Columns.Add(New DataColumn("ProdName", GetType(String)))
DataTable1.Columns.Add(New DataColumn("ProdQty", GetType(Integer)))
'Create rows and put in sample data
For I=0 To 4
DataRow1 = DataTable1.NewRow()
DataRow1(0) = strProd(I)
DataRow1(1) = intQty(I)
DataTable1.Rows.Add(DataRow1)
Next
Repeater1.DataSource = new DataView(DataTable1)
Repeater1.DataBind()
End If
End Sub
</Script>
After you have created the data source and bound the Repeater control with it, you can create templates. As mentioned before, you must create at least ItemTemplate to render the control on the page. Use the following code to create ItemTemplate:
<asp:Repeater ID=Repeater1 runat="Server">
<ItemTemplate>
<tr>
<td>
<%# DataBinder.Eval(Container.DataItem, "ProdName") %>
</td>
<td> <%# DataBinder.Eval(Container.DataItem, "ProdQty") %>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>

In the preceding code, the item is bound to the ProdName and ProdQty fields of the data source. Because the Repeater control has no layout of its own, the bound data appears in a row, as shown in Figure 11-2.
Figure 11-2: Repeater control implementing ItemTemplate
You can create HeaderTemplate to render text or controls before data item fields. The following code creates a table with two columns with the headings "Product" and "Quantity":
<HeaderTemplate>
<table border=1>
<tr>
<td>
<b>Product</b>
</td>
<td>
<b>Quantity</b>
</td>
</tr>
</HeaderTemplate>
In the preceding code, the <table> element has not been closed, because the HeaderTemplate elements are rendered even before the ItemTemplate elements, which use the <tr> and <td> elements that need to be displayed within the table. You can close the <table> element in FooterTemplate as follows:
<FooterTemplate>
</table>
</FooterTemplate>
You can apply special formatting to the alternating items by creating AlternatingItemTemplate. The following AlternatingItemTemplate sets the background color of the alternating rows to light blue:
<AlternatingItemTemplate>
<tr>
<td bgcolor="lightblue">
<%# DataBinder.Eval(Container.DataItem, "ProdName") %>

</td>
<td bgcolor="lightblue">
<%# DataBinder.Eval(Container.DataItem, "ProdQty") %>
</td>
</tr>
</AlternatingItemTemplate>
After creating all the previous templates, the Repeater control is rendered on the page, as shown in Figure 11-3.
Figure 11-3: A Repeater control after implementing the templates
Combining templates with the DataList control
The DataList control supports two more templates in addition to the templates supported by the Repeater control:
§SelectedItemTemplate: Enables users to select items
§EditItemTemplate: Enables users to edit items
You must bind the DataList control to a data source and create at least ItemTemplate to render the control on a page. To understand templates with the DataList control, you'll use the same data source as you used for the Repeater control. First, you need to add a DataList control to a form.
Note You can add the DataList control in the same form, or you can add another Web form and add the control in the new form.
In the HTML view of the ASPX file, you need to import the System.Data namespace, and bind the DataList control with the DataView object in the Page_Load method. After you've bound the DataList control to the DataView object, you need to create ItemTemplate and bind to the individual data fields in the data source. You can create a similar ItemTemplate for the DataList control, as follows:
<ItemTemplate>
<tr>
<td>
<%# DataBinder.Eval(Container.DataItem, "ProdName") %>
</td>
<td>
<%# DataBinder.Eval(Container.DataItem, "ProdQty") %>
</td>
</tr>
</ItemTemplate>
By default, the DataList control displays data items in a single vertical column, as shown in Figure 11-4.

Figure 11-4: A DataList control implementing ItemTemplate
You can override the default single vertical column layout. To do so, create HeaderTemplate, AlternatingItemTemplate, and FooterTemplate in the same way you created them for the Repeater control. After you create these templates, the DataList control appears similar to the Repeater control.
Implementing item selection functionality
You can also add the functionality to allow users to select and edit items. To implement the functionality of item selection, you need to follow these steps:
1.Create SelectedItemTemplate. You can add text, elements, and controls to be rendered on the page when an item is selected.
2.Add a Button or LinkButton Server control in ItemTemplate. Using the following code, set the CommandName property of the Button or
LinkButton control to "select":
3.<asp:LinkButton ID=LinkButton1 runat="Server" Text="Select"
CommandName="select" />
4. Rebind the list when an item is selected. To do so, create an event handler for the control's SelectedIndexChanged event. The complete code is given as follows:
5.Private Sub DataList1_SelectedIndexChanged(ByVal sender As
6.System.Object, ByVal e As System.EventArgs) Handles DataList1.
7.SelectedIndexChanged
8.DataList1.DataBind()
End Sub
9. You can unselect an item by setting the control's SelectedIndex property to -1. To do so, you can add a Button control in the SelectedItemTemplate of the DataList control and set the CommandName property to unselect. Then, add the event handler for the ItemCommand event of the DataList control. The complete code is given as follows:
10.Private Sub DataList1_ItemCommand(ByVal source
11.As Object, ByVal e As System.Web.UI.WebControls.
12.DataListCommandEventArgs) Handles DataList1.ItemCommand
13.If e.CommandName = "unselect" Then
14.DataList1.SelectedIndex = -1
15.End If
16.DataList1.DataBind()
End Sub
Implementing item editing functionality
To implement the functionality of item editing, follow these steps:
1. Add a Button or LinkButton Server control in ItemTemplate. Using the following code, set the CommandName property of the Button or LinkButton control to "edit":
2. <asp:LinkButton ID=LinkButton3 runat="Server" Text="Edit" commandName="edit"/ >
3. Create EditItemTemplate. You can add text, elements, and controls to be rendered on the page when an item needs to be edited. The template should contain the controls for all the values that need to be edited, along with two buttons. Both the buttons are either Button or LinkButton controls. One button should have the Text property set to "Update" and the CommandName property set to "update". This button is used to implement the functionality of saving the changes to the data source. The other button should have the Text property set to "Cancel" and the CommandName property set to "cancel". This button is used to implement the functionality of quitting without saving the changes to the data source. The following code snippet shows a typical EditItemTemplate that displays the Update and Cancel buttons and other controls to display the bound data in Edit mode:
4.<EditItemTemplate>
5.<tr>
6.<td>
7.<asp:LinkButton ID=LinkButton1 runat="Server"
8.Text="Update" CommandName="update" />
9.</td>
10.<td>
11.<asp:LinkButton Id=LinkButton2 runat="Server"
12.Text="Cancel" CommandName="cancel" />
13.</td>
14.<td>
15.<! Other controls go here >
16.</td>
</EditItemTemplate>
17.Create an event handler for the EditCommand event of the control to implement item editing. In this event handler, set the EditItemIndex property of the control to the index of the item to be edited. Also, call the DataBind() method of the control, using the following code:
18.DataList1.EditItemIndex = e.Item.ItemIndex
DataList1.DataBind()
19.Create an event handler for the UpdateCommand event of the control to update the data source with the edited values. In the

event handler, after you update the data source, you need to come out of the Edit mode and bind data to DataList:
20.DataList1.EditItemIndex = -1
DataList1.DataBind()
21.Create an event handler for the CancelCommand event of the control to cancel the changes in the edited values. In this event handler, you simply need to come out of the Edit mode and bind data to DataList.
Combining templates with the DataGrid control
The DataGrid control usually has bound columns. However, different types of columns, such as Hyperlink columns, Button columns, and Template columns, can provide additional functionality. Template columns enable you to create many templates, such as ItemTemplate, HeaderTemplate, FooterTemplate, and EditItemTemplate. Therefore, Template columns provide complete flexibility to present data.
You can create different types of columns by using the DataGrid Properties window. In the Properties window, click the ellipsis in the Columns property to open the Properties dialog box, as shown in Figure 11-5.
Figure 11-5: The Properties dialog box
Button columns provide functionality for selecting, editing, and deleting items. You can create three types of Button columns: Select, Edit, and Delete. If you create the Edit button column, the Edit button is created in each row. To add the functionality to the Edit button, create the event handler for the EditCommand event of the DataGrid control in the same way you created the event handler for the EditCommand event of the DataList control. Then, to update the changes in the data source, you need to create the event handler for the UpdateCommand event. And, to cancel any changes made by users, you need to create the event handler for the CancelCommand event of the DataGrid control.
Cross- For information on button columns, refer to Chapter 12.
Reference
Template columns provide complete flexibility to give a custom layout to the column. When you add a Template column, you can specify the header and footer text, and a header image in the Properties dialog box. You can also specify a sort expression. After adding a template column, when you switch to the HTML view, the following code automatically appears in the file:
<asp:TemplateColumn> <asp:/TemplateColumn>
You can create HeaderTemplate, FooterTemplate, ItemTemplate, and EditItemTemplate in the TemplateColumn element. To display values in the Template column, you must create at least the ItemTemplate.
You'll implement the same example that you implemented for the Repeater and DataList controls. First, you need to add a DataGrid control to the form.
Note You can add the DataGrid control in the same form, or you can add another Web form and add the control in the new form.
After adding the DataGrid control to the form, follow these steps to add the Template column:
1.Display the Properties window for the DataGrid control by right-clicking the control and choosing Properties from the shortcut menu.
2.Display the Properties dialog box by clicking the ellipsis in the Columns property.
3.Click Columns in the left pane.
4.Select TemplateColumn from the Available Columns list and click the > button to add TemplateColumn to the Selected Columns list.
5.In the Header Text box, enter Product Category and click OK.
Note |
You can also specify the header image, footer text, and a sort |
|
expression. |
||
|
After adding the Template column to the DataGrid control, you can create templates. To do so, switch to the HTML view of the ASPX file. Because you'll be using the DataView object to bind data to the DataGrid control, import the System.Data namespace in the page using the following code:
<%@ Import namespace="System.Data" %>
Then, in the Page_Load method, write the code to create the DataView object and bind the DataGrid control with it. To create the DataView object, use the same code you used for the Repeater and DataList controls.
Finally, create the ItemTemplate in the Template column as follows:
<asp:TemplateColumn HeaderText="Product Category">
<ItemTemplate>
<asp:Image ID=Image1 runat="Server" ImageUrl="category.tif" />
</ItemTemplate>
<asp:/TemplateColumn>
Note Because the image file Category.tif has been added to the project, the ImageUrl property is set to the filename instead of the complete URL.
In the preceding code, an Image control is created as an item in the Template column. The ImageUrl property of the Image control is set to the image to be displayed in the column. Figure 11-6 shows the DataGrid control after creating the ItemTemplate for the Template column.

Figure 11-6: DataGrid implementing a Template column
Summary
This chapter introduced you to the ASP.NET Server control templates. First, you learned the different types of templates that can be created. You identified the Server controls that support templates. Then, you learned the basic features of the Repeater, DataList, and DataGrid controls and identified the templates that each of these controls supports. Finally, you learned how to create templates for the Repeater, DataList, and DataGrid controls to customize their look and layout.
Chapter 12: Using SQL Server with ASP.NET
Overview
With more and more applications shifting to the Internet, e-business is booming. To conduct business on the Internet, Web applications need to access data stored on a server. Thus, data access is most critical to real-world applications.
Visual Studio .NET provides Web Forms controls, such as the DataGrid control that you can use to access data from various data sources, such as a SQL server or a Jet database. This chapter introduces you to the Structured Query Language (SQL), which is used to access data stored on a SQL server through Web Forms. You'll also learn how to use ADO Extensions to create and manage different schema objects, such as databases and tables.
Introduction to Server-Side Data Access from a SQL Server
Server-side data access is critical to all real-world applications. Therefore, these applications must address server-side data access to implement business solutions. This section introduces you to the SQL server data access through Web Forms.
Microsoft SQL Server is a Relational Database Management System (RDBMS) that is used to store and organize related data — the collection of related data is called a database. Microsoft SQL Server is based on the client/server architecture, in which data is stored on a centralized computer called a server. Other computers, called clients, can access the data stored on the server through a network. The client/server architecture prevents data inconsistency.
You can access data stored on a SQL server through Web Forms. To do so, you can create Web applications that have data access controls. These data access Web controls present the data in a consistent manner irrespective of the actual source, such as Microsoft SQL Server or MS Access. Therefore, while creating a Web application, you do not need to worry about the format of the data. However, before you can access or manipulate data from a SQL server, you need to perform the following steps in the specified sequence:
1.Establish a connection with the SQL Server.
2.Write the actual command to access or manipulate data.
3.Create a result set of the data from the data source with which the application can work. This result set is called the data set and is disconnected from the actual source. The application accesses and updates data in the data set, which is later reconciled with the actual data source.
To achieve this functionality, you first need to import two namespaces, System.Data and System.Data.SqlClient, into your Web Forms page. The syntax is given as follows:
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
The two namespaces are described as follows:
§System.Data: A collection of classes that are based on the ADO.NET architecture. The ADO.NET architecture allows for efficient data management and manipulation from multiple data sources. ADO.NET provides tools to request and update data in a data set, and reconcile data in the actual data source. Some of the classes included in this namespace are described as follows:
oDataSet: Represents the data set cached in memory with which applications work.
o DataTable: Represents a table of data in a data set. o DataRow: Represents a row of data in a data table.
oDataColumn: Represents a column of data in a data table.
§System.Data.SqlClient: A collection of classes that are used to access SQL server data sources. Some of the classes are listed as follows:
o SqlConnection: Represents a connection with a SQL
server data source. The first step to access data from a SQL server database is to create an object of this class.
o SqlDataAdapter: Represents a set of data commands and a database connection that are used to access or manipulate data. After creating a SqlConnection object, you need to create an object of the SqlDataAdapter class to populate the data set and update the data source.
o SqlCommand: Represents the SQL command to perform data operations in a SQL server data source.
You use the following code to import the two namespaces if you want to use the Visual Basic code file instead of the ASPX file:
Imports System.Data
Imports System.Data.SqlClient
You can use the different classes to create and manipulate database objects. For example, the following code illustrates how to create a table called "Products" in a SQL server database "Sales."
Dim MyCommand As SqlCommand
Dim MyConnection As SqlConnection
MyConnection = New SqlConnection("server=localhost;uid=sa;
pwd=;database=Sales")
Dim CreateCmd As String = " Create Table Products (ProductID
VarChar (4) Primary Key, ProductName VarChar (20), UnitPrice Money,
QtyAvailable Integer)"
'Passing the SQL query in the SQLqlCommand object
MyCommand = New SqlCommand(CreateCmd, MyConnection)
'Opening the active connection
MyCommand.Connection.Open()
'Executing the command
MyCommand.ExecuteNonQuery()
'Closing the connection
MyCommand.Connection.Close()
Before delving into the details of implementing the different ADO.NET classes in your Web applications, let's have a recap session for T-SQL.
Revising T-SQL
A SQL database stores data in tables, which consist of rows and columns. A column stores the information regarding properties of an item, while a row stores the complete information of an item. For example, consider a Products table. The columns store information, such as product identification number, product name, and quantity available. The rows store information about different products. Each column stores data of a specific type. Therefore, each column has a specific data type. Table 12-1 describes some of the SQL data types.
|
Table 12-1: SQL data types |
|
|
|
|
|
|
|
|
|
Data Type |
|
Description |
|
|
|
|
|
|
|
Integer |
|
Used to |
|
|
|
|
store whole |
|
|
|
|
numbers. |
|
|
|
|
|
|
|
Float |
|
Used to |
|
|
|
|
store |
|
|
|
|
decimal |
|
|
|
|
numbers. |
|
|
|
|
|
|
|
Char(n) |
|
Used to |
|
|
|
|
store |
|
|
|
|
character |
|
|
|
|
data that |
|
|
|
|
can be |
|
|
|
|
letters, |
|
|
|
|
numbers, or |
|
|
|
|
|
|