
C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#
.pdfchoice among data stores provides high flexibility, and thus enables you to bind a control to any data store based on your need.
The Web Forms controls that are bound to a data store access data through the properties of specific classes, categorized as data classes. Data classes typically include methods that can be used for updating the underlying data stores. Because the term "data" is used in a broad sense, the class category "data classes" is also used in a generic, broad sense. These classes differ depending on the data store. Some data classes provide more functionality than others — you can use any one of these classes depending on your need.
You can bind a control to different data stores, such as properties, methods, or collections. These different data stores can be bound to a control property by using data binding expressions. While binding, the data is always bound to a particular property of the control (the property name might differ for various controls). When a data binding expression is evaluated, the resulting value is loaded in the control's bound property. You can bind simple controls to public properties. A public property can be of a control on a page or the page itself.
Note Simple controls are the controls that can bind only to a single value. Some simple controls include Label, TextBox, and Button controls.
You can bind complex controls to any structure by using a data class that implements the ICollection interface, which ensures that the data classes provide the basic functionality of data access and navigation. For example, you can bind a DropDownList control to an array by using the ArrayList class, which implements the ICollection
interface. |
|
Note |
Complex controls are the controls that contain embedded controls. |
|
Some complex controls include DataList, Repeater, and DataGrid |
|
controls. |
When you bind a control property to a data store, the Web Forms Framework cannot evaluate data binding expressions automatically. To display the evaluated value in the control's bound property, you need to call the DataBind() method explicitly. The page and each control on the page support this method. When you call the DataBind() method for a control, it is cascaded to all its child controls. For example, if you call the DataBind() method for the page control, the method is automatically called for all the controls on the page.
The explicit method for data binding enables you to control when to load the bound controls with data. Therefore, calling the DataBind() method explicitly should not be seen as a disadvantage. You can load the bound controls with data in one of the following situations:
§When you need to display data in the bound controls as soon as the page is loaded. In such a situation, you can call the DataBind() method at the Page_Load stage. You can call the DataBind() method for the page or for a specific control, depending on your requirement.
§When data in the dataset is updated and you want to display the updated data in the bound controls. In such a situation, you need to call the DataBind() method in the event -handling methods that resulted in the change to the dataset. Again, you can call the DataBind() method for the page or for specific controls depending on whether you want to refresh the complete page or specific controls.
Data Source Binding
You can use the ASP.NET syntax to bind data to the ASP.NET server controls. To bind these controls to data, you first need to open the ASPX file for the Web Forms page. Then, you can use the appropriate syntax for data binding for different controls. To bind a property of a control to some data represented by an expression, use the following tag:
<% # expression %>

When the expression is evaluated, the value is loaded in the control's bound property. For example, you can bind the Text property of a Label control to a public property called ProductID of the page. To do so, use the following code:
<asp:Label ID = "ProdID" runat = "Server" Text =
'<% # ProductID %>' />
In this code, the |
<% # ProductID %> tag is used to bind the Text property of the |
Label control to the ProductID property of the page. |
|
Caution |
You should be careful while using quotation marks in the |
|
expression. If the expression contains quoted strings, you |
should use single quotation marks.
As mentioned earlier, the control property will not display the bound data until the DataBind() method is called explicitly. You can call the DataBind() method for the page by using the following statement:
Page.DataBind()
Alternatively, you can simply use the following statement to call the DataBind() method for the page:
DataBind()
To call the DataBind() method for a specific control, use the following syntax:
ControlID.DataBind()
In this syntax, ControlID refers to the ID of the control for which you want to call the DataBind() method. For example, to call this method for a DataList control whose ID is DataList1, use the following statement:
DataList1.DataBind()
The topics that follow implement data binding of control properties to page properties, control properties, methods, collections, and lists. However, before implementing data binding, you need to create an ASP.NET Web Application project. You can choose Visual Basic .NET or C#, depending on your language proficiency. In your Web application, design a form as shown in Figure 9-1.
Figure 9-1: A sample Customer Registration form
Table 9-1 describes the properties for different controls used in the form.
Table 9-1: Form control properties
Control Type |
|
Contains |
|
Control ID |
|
|
|
|
|
|
Table 9-1: Form control properties |
|
|
|
|
|
|
|
|
|
|
|
|
|
Control Type |
|
Contains |
|
Control ID |
|
|
|
|
|
|
|
|
|
TextBox |
|
Customer |
|
CustID |
|
|
|
|
ID |
|
|
|
|
|
|
|
|
|
|
|
TextBox |
|
Customer |
|
CustName |
|
|
|
|
name |
|
|
|
|
|
|
|
|
|
|
|
TextBox |
|
Customer |
|
CustStreet |
|
|
|
|
street |
|
|
|
|
|
|
|
|
|
|
|
DropDownList |
|
Customer |
|
CustCity |
|
|
|
|
city |
|
|
|
|
|
|
|
|
|
|
|
DropDownList |
|
Customer |
|
CustState |
|
|
|
|
state |
|
|
|
|
|
|
|
|
|
|
|
Button |
|
Submit |
|
SubmitButton |
|
|
|
|
button |
|
|
|
|
|
|
|
|
|
|
In addition to the controls that you see in Figure 9-1, add a Label control below the button. Set the ID of this label to "DisplayLabel." Also, set the Visible property of this label to False. You can make it visible through programming, whenever required.
Binding data to page properties
In this section, you'll bind a simple property, CustomerID, of the page to the Text property of the TextBox control with ID CustID. To implement this data binding, follow these steps:
1.In the ASPX file of the Web Forms page, in the <HEAD> element, write the following code to create a read-only property called CustomerID:
2.<Script Language = "VB" runat = "Server">
3.
4.ReadOnly Property CustomerID() As String
5. |
Get |
6. |
CustomerID = "C001" |
7. |
End Get |
8. |
End Property |
9. |
|
</Script>
10.Edit the ASP code for the TextBox control with ID CustID to include the data binding expression as follows:
11.<asp:TextBox ID="CustID" runat="Server" Text=
'<% # CustomerID %>' />
12.Call the DataBind() method in the Page_Load method. This is the most critical step, because the data-bound TextBox control will not display data until the DataBind() method is called explicitly. Therefore, write the following code in the <Script> tag:
13.Sub Page_Load(Sender As System.Object, e
14.As System.EventArgs) Handles MyBase.Load
15.If Not IsPostBack Then
16.Page.DataBind()
17.End If
End Sub
When you execute the application, you'll find that the CustID TextBox control displays the value stored in the property CustomerID, as shown in Figure 9-2.

Figure 9-2: Output of the application implementing data binding to page properties
Binding data to control properties
In this section, you'll bind the Text property of the Label control with ID DisplayLabel to the text entered in the TextBox control with ID CustStreet. When a user clicks the Submit button, the Label control should display the street entered in the CustStreet text box. To implement this functionality, follow these steps:
1.In the <Script> tag, write an event handler for the Click event of the Button control whose ID is SubmitButton. This method calls the DataBind() method for the Label control with ID DisplayLabel and set its Visible property to True, as shown in the following code:
2.Sub SubmitButton_Click(Sender As System.Object, e As System.EventArgs)
3.
4.'Calling the DataBind() method for the Label control
5.DisplayLabel.DataBind()
6.
7.'Setting the Visible property of the Label control to True
8.DisplayLabel.Visible = True
9.
10.End Sub
11.Edit the ASP code for the Label control with ID DisplayLabel to include the data binding expression. The expression combines a string and the Text property of the TextBox control with ID CustStreet.
12.<asp:Label ID = "DisplayLabel" runat = "Server" Text =
13.'<% #("The street that you entered
is: " + CustStreet.Text)%>' />
14.Edit the ASP code for the Button control with ID SubmitButton to add the SubmitButton_Click event handler for the Click event:
15.<asp:Button ID="SubmitButton" runat="Server" Text=
"Submit" OnClick="SubmitButton_Click" />
Figure 9-3 displays the output when you enter the name of the street and click the button at run time.

Figure 9-3: Output of the application implementing data binding to control properties
Data binding to an ArrayList
As mentioned earlier in the chapter, the controls, such as DropDownList, ListBox, and DataGrid, can be bound only by using the data classes that implement the ICollection interface. In this section, you'll bind the ArrayList class to the DataSource property of the DropDownList with ID CustState. To implement this data binding, write the following code in the Page_Load event handler.
Sub Page_Load(Sender As System.Object, e As
System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
'Creating an object of the ArrayList class
Dim objArrayList as ArrayList= new ArrayList()
'Adding items to the object of the ArrayList class
objArrayList.Add ("New York")
objArrayList.Add ("California")
objArrayList.Add ("Oregon")
objArrayList.Add ("Illinois")
objArrayList.Add ("Texas")
objArrayList.Add ("None")
'Binding the DropDownList control with ID CustState
to the object of the
ArrayList class
CustState.DataSource = objArrayList

'Calling the DataBind() method for the State1 Drop Down control
CustState.DataBind()
End If
End Sub
In this code:
§objArrayList is an object of the ArrayList class.
§The Add() method of the ArrayList class is used to add items to the object.
§The DataSource property of the DropDownList control with ID
CustState has been bound to the object of the ArrayList class.
After binding the State DropDownList control to the object of the ArrayList class, you can bind the Text property of the Label with ID DisplayLabel to the selected item in the DropDownList control with ID CustState. To do so, edit the ASP code for the Label control with ID DisplayLabel to include the data binding expression:
<asp: Label ID="DisplayLabel" runat="Server" Text=
'<% #("The street that you entered is: " + CustStreet.Text +
" and the state that you selected is: " + CustState.SelectedItem.Text)%>' />
At run time, when you enter the name of a street, select a state, and click the button, the label with ID DisplayLabel becomes visible and displays the text as shown in Figure 9-4.
Figure 9-4: Output of the application implementing data binding to an ArrayList
Binding methods
Binding methods is similar to binding any other expression. In this section, you'll create a method to return a string based on the value selected from the DropDownList control with ID CustState. Then, you'll bind the Text property of the Display Label to this method. To implement this binding, write the following code in the <Script> tag to create a method called StateValue:
Function StateValue() As String
If CustState.SelectedItem.Text="None" Then

StateValue="Not a US resident"
Else
StateValue="Selected state: " + CustState.selectedItem.Text
End If
End Function
The StateValue method returns a string, "Not a US resident", if a user selects None from the DropDownList control with ID CustState. If the user selects any other value, the method returns the selected state. Next, you need to bind this method to the Text property of the Label control with ID DisplayLabel. To do so, edit the ASP code for this Label control to include the data binding expression:
<asp:Label ID="DisplayLabel" runat="Server" Text='<% #StateValue%>' />
At run time, when you select None from the State DropDownList control and click the Submit button, the label shows the text "Not a US resident." Otherwise, if a user selects a state and clicks the Submit button, the selected state is displayed on the label as shown in Figure 9-5.
Figure 9-5: Output of the application implementing data binding to a method
Binding to a DataView
The DataView class represents a custom view of a data table. This class is a member of the System.Data namespace, and to use this class in your page, you need to import the System.Data namespace. Before you can implement binding to a data table, add a new Web Forms page to your ASP.NET Web Application project. In this form, add a DataGrid control. Then, to implement the functionality of the DataView class in this new form, you'll need to import the System.Data namespace. To do so, write the following statement in the ASPX file of the new Web Forms page:
<%@import Namespace="System.Data"%>
You can bind a DataView object to a DataGrid control. A DataGrid control displays information in row and column format. In this section, you'll create an object of the DataView class. This object represents a data table that displays cities and their respective states. Then, you'll bind this DataView object to the DataSource property of the DataGrid control. To implement this functionality, write the following code in the
Page_Load method:
Sub Page_Load (Sender As System.Object, e As System.EventArgs) Handles
MyBase.Load
If Not IsPostBack Then
'Declaring objects of the DataTable and DataRow classes Dim DataTable1 As DataTable
Dim DataRow1 As DataRow
'Initializing the DataTable object DataTable1 = New DataTable()
'Adding columns to the DataTable object DataTable1.Columns.Add(New DataColumn("City", GetType(string))) DataTable1.Columns.Add(New DataColumn("State", GetType(string)))
'Creating arrays to store cities and their respective states Dim strCity(5) as String
Dim strState(5) as String Dim I as Integer strCity(0)="Chicago" strCity(1)="Hampstead" strCity(2)="Houston" strCity(3)="New York" strCity(4)="Portland"
strState(0)="Illinois" strState(1)="New York" strState(2)="Texas" strState(3)="New York" strState(4)="Oregon"
'Adding rows in the DataTable object For I=0 To 4
DataRow1 = DataTable1.NewRow()
DataRow1(0) = strCity(I)
DataRow1(1) = strState(I)
DataTable1.Rows.Add(DataRow1)
Next
'Setting the DataSource property of the DataGrid control to the 'DataView representing the DataTable object DataGrid1.DataSource=New DataView(DataTable1)
'Calling the DataBind() method for the DataGrid control

DataGrid1.DataBind()
End If
End Sub
When you execute the application, the output appears as shown in Figure 9-6.
Figure 9-6: Output of the application implementing data binding to a DataView
Handling PostBack Data
When a form is submitted to a server, the postback event is generated. You might need to process the form data at the server during the postback. The System.Web.UI namespace contains an interface called IPostBackDataHandler that you can use for handling the postback data.
The IPostBackDataHandler interface has two member methods,
RaisePostDataChangedEvent() and LoadPostData(). These methods are described as follows:
§RaisePostDataChangedEvent: This method draws attention of the control to inform any listener about the control's state change. In Visual Basic, the syntax of the method is as follows:
Sub RaisePostDataChangedEvent()
§LoadPostData: This method handles the postback data of a specific control by processing its postback data. The method returns True if the postback results in state change. On the other hand, if the state does not change after the postback, the method returns False. The method takes two arguments:
opostDataKey: This is a String argument that represents the key identifier of the specified control.
opostCollection: This argument is an object of the NameValueCollection in the System.Collections namespace. The argument represents all the incoming name values. In Visual Basic, the syntax of the method is given as follows:
o Function LoadPostData( _
o |
ByVal postDataKey As String, ByVal |
postCollection As NameValueCollection) As Boolean
After understanding the methods of the IPostBackDataHandler interface, let us see how the postback data is handled. You can handle the postback data only for those server controls that implement the IPostBackDataHandler interface. When you submit a Web Forms page to the server, the Page Framework searches the content that is posted, for the unique names of the server controls that implement the IPostBackDataHandler
interface. Then, for each control that implements this interface, the LoadPostData method is invoked. This method returns True if the state of the control changes. Otherwise, this method returns False. For all the controls for which the LoadPostData method returns True, the RaisePostDataChangedEvent method is invoked. This method, then, raises the Change events, if any, for the control.
Summary
This chapter introduced you to the basic concepts of data binding to the Web Forms server controls. To bind a control property to a data store, you need to use a data binding expression and then call the DataBind() method for the control. You learned how to implement data binding to properties, ArrayList objects, methods, and DataView objects. Finally, you learned how to handle the postback data.
Chapter 10: Working with Data Grids
Overview
The DataGrid control is a bound data control that displays items from the selected data source in a grid or spreadsheet-like fashion. This was possible before .NET, but it required a fair amount of code if you wanted to implement more than a read-only grid. This new server control, along with the Repeater and DataList controls, makes it a snap to wire up to a data source and display columnar data using a minimal amount of coding. New to the DataGrid control is paging. You no longer have to be concerned with writing code to handle the paging of data in the grid. For anyone who has written this type of code in the past, this is a welcome relief.
This chapter also takes a look at sorting, editing, and selecting items located in the DataGrid. Also, since the DataSource property of the DataGrid control expects the source of data to be derived from the System.Collections.IEnumerable class, you don't have to bind to just SQL or ODBC data. You can also use arrays and collections as the data source for the DataGrid control.
Using a Data Grid Example
Before getting into the details of the various properties and events available to developers, take a look at a simple example of using the DataGrid control. The following code shows the minimal amount required to wire up and use the DataGrid control:
<html>
<head>
<title>Hungry Minds Chapter 9...</title>
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e) {
//-- create a data source
String[] items = {"Rick", "Billy", "Ed", "Steve"};
//-- bind the data source
simple.DataSource = items;
simple.DataBind();