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

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

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

160 Chapter 3 • ASP Server Controls

Figure 3.87 Continued

Dim connStr, sqlStr, strPName As String

Dim myUpdateCommand As OleDbCommand

Dim intPid As Integer

Dim dblPrice As Double

' Get the key-value of the clicked row

intPid=dataGrid1.DataKeys.Item(e.Item.ItemIndex)

' Get the new value of ProductName

strPName=(CType(e.Item.Cells(2).Controls(0), Textbox)).Text

' Get the new value of Price

dblPrice=cDbl((CType(e.Item.Cells(3).Controls(0), Textbox)).Text)

' Build the SQL

sqlStr="UPDATE Products SET ProductName=' " + strPName _

+" ', Price=" + dblPrice.ToString _

+" WHERE ProductID=" + intPid.ToString

connStr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Products.mdb"

myConn= New OleDbConnection(connStr)

myConn.Open()

myUpdateCommand=New OleDbCommand(sqlStr, myConn)

' Execute the Update SQL statement

myUpdateCommand.ExecuteNonQuery

myConn.Close()

dataGrid1.EditItemIndex=-1

BindDataGrid

End Sub

</script>

<html><head></head><form runat="server">

<asp:DataGrid id="dataGrid1" AutoGenerateColumns="False"

DataKeyField="ProductId" OnEditCommand="setEditMode"

OnCancelCommand="cancelEdit" OnUpdateCommand="updateDataBase"

CellPadding="2" Font-Name="Verdana" Font-Size="8pt" runat="server">

<HeaderStyle Font-Size="8" Font-Names="Arial" Font-Bold="True"

BackColor="Yellow" HorizontalAlign="center"></HeaderStyle>

<Columns>

Continued

www.syngress.com

ASP Server Controls • Chapter 3

161

Figure 3.87 Continued

<asp:EditCommandColumn EditText="Edit" UpdateText="Update" CancelText="Cancel">

</asp:EditCommandColumn>

<asp:BoundColumn HeaderText="Product ID" DataField="ProductId"

ReadOnly="True" />

<asp:BoundColumn HeaderText="Description" DataField="ProductName"/> <asp:BoundColumn HeaderText="Unit Price" DataField="price"

DataFormatString="{0:c}" /> </Columns>

</asp:DataGrid></form></html>

Creating Custom ASP

Server User Controls

We may develop our own server controls by extending an existing control or a group of controls to provide additional functionalities. As stated earlier, there are two versions of custom controls: Web User Controls and Web Custom Controls.The Web User Controls are easy to develop and these are typically stored as ascx files. The Web Custom Controls require in-depth knowledge of Object Oriented Programming and CLR.These are stored in compiled form as assemblies.

A user control, if developed correctly, functions like any other controls. It can be placed inside any other host ASP page (often called the “Consumer” of a control). In this section we will provide two examples on how to develop and use a Web User Control. In the first example, we will develop a very simple user control. In the second example, we will develop a user control that will expose some of its properties to its host page class.

Creating a Simple Web User Control

Suppose that we want to build the control as shown in Figure 3.88. If a host page embeds this control, it will automatically display the current time in the server’s time zone. Once we build this control, we can use it in any subsequent page.We will provide a step-by-step procedure to build this control.

www.syngress.com

162 Chapter 3 • ASP Server Controls

Figure 3.88 A Sample User Control

1.Develop the necessary code for the control.The code for this example is shown in Figure 3.89 and can be found on the CD that accompanies this book in the file named TimeUserControl.ascx.The code is essentially very simple.We are using use a <table> tag with an embedded <asp:Label> control. In the Page_Load event, we will display the current time in the label.

Figure 3.89 The Code for the User Control (TimeUserControl.ascx)

<!— Chapter3/TimeUserControl.ascx —>

<table border ="5" cellpadding="5" rules="none" bgcolor="lightyellow" bordercolor="orange">

<tr valign="middle"><td><h3>The time in server land is</h3></td> <td><h3><asp:Label id="lblDateTime" runat="server"/></h3></td>

</tr>

</table>

<script Language="vb" runat ="server">

Sub Page_Load(s As Object, e As EventArgs)

If Not Page.IsPostBack Then

' lblDateTime.Text=System.DateTime.Now.ToLongTimeString() lblDateTime.Text=Format(Now,"hh:mm:ss")

End If End Sub </script>

2. Save the code with an extension of *.ascx in your virtual directory.

3. Test the User Control: A control cannot be tested unless it is hosted in an ASPX page.Thus, start a new page, and enter the code shown in Figure 3.90.The code can be found on the CD that accompanies this book in the file named TestTimeUserCntrol1.aspx. First, a host page needs to register a user control using the Register directive.The Register directive has three major attributes.We provide a prefix in the tagprefix

www.syngress.com

ASP Server Controls • Chapter 3

163

attribute (it can be any prefix of your choice).Then we need to provide a name of the registered control in the tagname attribute. Finally, we must also specify the name of the source code (of the .ascx file) using the Src attribute. Can you believe that you are done? Go ahead and open the page in your browser.You will see a page very similar to the one shown in Figure 3.91.

Figure 3.90 Testing the User Control (TestTimeUserCntrol1.aspx)

<!— Chapter3/TestTimeUserControl1.aspx —>

<%@ Register tagprefix ="utoledo" tagname="Time"

Src="TimeUserControl.ascx" %>

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

<b>I am a host page. Suppose that I don't know how to show the time. Hence, I will use the TimeUserControl. I am using an instance of the

TimeUserControl below:<p>

<utoledo:Time runat="server" /><br/>

Now I can do my other work... <b/>

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

Figure 3.91 Using a User Control

Exposing Properties of a User Control

Obviously, the control developed in our previous example does not do much more than display the current time. If judiciously designed, a user control can actually play an extremely crucial role in systems development practice.We can develop user controls to encapsulate standard business processes. A user control is

www.syngress.com

164 Chapter 3 • ASP Server Controls

essentially a visual component (almost like ActiveX controls and visual JavaBeans), except that it is much easier to develop. Once we develop the component, it can be plugged in many applications, thereby making it easy for the front-end application developers. More importantly, it provides the mechanism to implement standard business processes and maintain their integrity.

We will illustrate this concept with an example. In this example, we will encapsulate a simple business rule for computing gross wage.The interesting feature of this control is that it will pass the result of its computation to the host page for further processing. It will also accept a title from the host page and display it within itself.That means we will provide two-way communication between the control and the host page.The run-time view of the control when hosted in a page is shown in Figure 3.92.

Figure 3.92 Exposing Properties of a User Control

Developing the Payroll User Control

The code for this user control is shown in Figure 3.93 and can be found on the CD that accompanies this book in the file named UserControlPayroll.ascx. As can be observed in the listing, we have provided number of labels, two textboxes, and a button in this user control.These are named lblTitle, txtH, txtR, and cmdCompute. In the script, we have provided two properties: Title and grossWage. The grossWage property is defined as ReadOnly, so the host page will not be able to change its value.The Title property simply returns the content of the lblTitle. However, the host page will be able to set its value during the run-time.

www.syngress.com

ASP Server Controls • Chapter 3

165

Figure 3.93 UserControlPayroll.ascx

<!-- AspNet/UserControls/UserControlPayroll.ascx --> <table border='2' bordercolor="blue"><tr><td>

Here is a title that is loaded from the parent Form: <br/>

<asp:Label id="lblTitle" backcolor="yellow" Height=15 runat="server"/> <br>How many hours have you worked?

<asp:TextBox id="txtH" rows="1 " width="50" runat="server"/></br> Your Hourly Rate? <asp:TextBox id="txtR" rows="1" width="80"

runat="server"/><br>

<asp:Button id="btnCompute" runat="server" text="Compute Pay" onclick="computePay"/>

<p/><asp:Label id="lblPayMsg" runat="server"/>

<asp:Label id="lblPay" runat="server"/><br></tr></td></table>

<script language=vb runat="server"> Public Property Title() As String

Set

lblTitle.Text=value

End Set

Get

return lblTitle.Text

End Get

End Property

Private grWage As Single

Public ReadOnly Property grossWage() As Single

Get

return cSng(lblPay.Text)

End Get

End Property

Protected Sub computePay (Sender As Object, E As EventArgs)

Dim h, r, g As Single

h=CSng(txtH.Text)

r=CSng(txtR.Text)

lblPayMsg.Text="Your Gross Wage is : "

g=h * r

Continued

www.syngress.com

166 Chapter 3 • ASP Server Controls

Figure 3.93 Continued

lblPay.Text=FormatCurrency(g)

grWage=g

End Sub

</script>

Consuming the Payroll User Control

We have tested the previous user custom control in a page named UserControlPayrollTest.aspx.The code for this page is shown in Figure 3.94, and can be found on the CD that accompanies this book in the file named UserControlPayrollTest.aspx. First, we have registered the user control with a

tagprefix of userCtrlPayroll and a tagname of payroll.We inserted one of these controls in our page using the runat=“server” attribute.This will ensure that the controls in the user control persist during postbacks. We have set the Title property of the control to “The University of Toledo” as follows:

<usrCtrlPayroll:payroll id="usrPayCtrl" runat="server"

Title="University of Toledo"/><br>

After the user enters the data in the user control, he or she will click the Compute Pay button inside the user control.The user control will apply its own business logic (comptePay procedure) to compute the gross wage. As a consumer of the user control, we do not need to know the details of how the gross wage is being computed. However, we need its value to compute appropriate tax in our own application (page). Fortunately, the user control has exposed the value of the gross wage as a property.Thus, we have developed the following code to compute the value of tax:

Sub computeTax (s As Object, e As EventArgs)

Dim t, gWage As Single

gWage=usrPayCtrl.grossWage()

t=gWage * 0.10

--- ---

End Sub

In this example, we have demonstrated how to develop a user control and expose its properties.We have maintained the states of the properties of the user control.This was accomplished by exploiting the controls embedded in the

www.syngress.com

ASP Server Controls • Chapter 3

167

custom control and by using the runat=“server” attribute. In an advanced custom control, we may avoid this trait by maintaining the states of the variables using objects similar to the old ActiveX Controls “PropertyBags”. However, that topic is not within the bounds of this chapter.

Figure 3.94 Consuming the Payroll User Control (UserControllPayrollTest.aspx)

<!-- Chapter3\UserControlPayrollTest.aspx -->

<!-- Uses the UserControlPayroll.ascx -->

<%@ Register tagprefix="usrCtrlPayroll" Tagname="payroll"

src="UserControlPayroll.ascx" %>

<html><head</head><title>Example on User Controls</title>

<body><form runat="server">

Hello there, here we are in our main page.

Now, let us instantaite the payroll user control <br>

<usrCtrlPayroll:payroll id="usrPayCtrl" runat="server"

Title="University of Toledo"/><br> <asp:Button id="btnShowTax" runat="server" text="Show Tax"

onclick="computeTax" />

<br><asp:Label id="lblTaxMsg" runat="server"/> <asp:Label id="lblTax" runat="server"/><br> </form></body></html>

<script language=vb runat="server">

Sub computeTax (s As Object, e As EventArgs)

Dim t, gWage As Single

gWage=usrPayCtrl.grossWage()

t=gWage * 0.10 lblTaxMsg.Text="Your Tax is : " lblTax.Text=FormatCurrency(t)

End Sub </script>

www.syngress.com

168 Chapter 3 • ASP Server Controls

Summary

This chapter has been about ASP.NET Web Controls.The ASP.NET controls are placed in Web pages.Thus, we cannot isolate them and discuss them without knowing how the ASP.NET Engine works, and how it maintains the states of the server controls. Hence, we presented brief overviews of various concepts like HTML Forms, server-side processing, and in-page coding vs. code-behind.We have also given a step-wise procedure to develop a simple ASP.NET project using VS.NET.

We have essentially covered almost all of the HTML server and Web server controls in this chapter.We have also introduced you to a very promising technology named Custom User Control.We have not presented two special purpose controls, namely the Calendar and the AdRotator controls in this chapter. Detail examples of these controls are available in plenty of sources (including the SDK documentations). After you practice the examples presented in this chapter, you will not have much difficulties in tackling these two controls.

The ASP.NET server controls are here to stay.They provide exceptional functionalities and abilities to develop server-side codes just like the VB 6 codes we used to develop in the old days.The bound controls make it easy for us to develop powerful data-oriented applications on the Web very fast.We have illustrated many of these controls with simple examples. However, each of these controls has many properties and events beyond the materials presented in this chapter. A complete book can be written on data-bound list controls, and still the richness of these controls would not be covered in full.The details of the beauties and the beasts behind these controls are anxiously waiting for you in the SDK documentation. After you complete this chapter, be sure to go and grab them from the SDK documentation! Pretty soon, you will be one of the most successful ASP.NET developers.

Solutions Fast Track

Major Features of ASP.NET Server Controls

;There are four types of ASP.NET server controls: HTML Server Controls, Web Server Controls,Validation Controls, and Custom Controls. HTML server controls can be used to run server-side code against conventional HTML controls.The Web server controls follow standard objectoriented programming model and provide rich functionalities. Custom

www.syngress.com

ASP Server Controls • Chapter 3

169

controls enable users to develop their own controls.The Validation controls allow data validation.

;HTML uses HTTP protocol. HTTP is state-less.

;The client can submit data to the server using the GET or POST method.The GET method transmits the data by augmenting the data in the URL.The POST method packages the data inside the BODY of a HTTP massage.

Server-Side Processing in ASP.NET

;When a server receives a request for a page, it retrieves the page from the disk and gives it to the ASP Engine.The ASP Engine compiles the page and creates a page class. Subsequently, the class is instantiated and executed, thereby providing a Response object.The server sends this Response object back to the client.

;ASP.NET server controls are state-full.The system maintains the states of the controls automatically. All server controls are typically defined with a runat=“server” attribute.

;When a user enters data and submits a form back to the server, it is known as PostBack. On a PostBack, the server reloads the form, and the events generated at the client-side are handled at the server. In conventional HTML, typically a Submit button is used to submit data from the client to the server. However, many Web server controls can also trigger PostBacks.

;When a page is loaded and executed, the sequence of events are: Page_Init, Page_Load, Change events, Action events, and finally the Page_Unload.

Code-Behind versus In-Page Coding

;In an ASP page, scripts and HTML tags are usually intermixed.This is known as In-Page Coding. ASP.NET pages can be developed using this procedure. However, ASP.NET provides an alternative methodology to develop a page. It enables separation of HTML tags (presentation) from the processing logic (code).This is known as Code-Behind. It is essentially very similar to the VB development model.

www.syngress.com