1. Trang chủ
  2. » Công Nghệ Thông Tin

vb.net book phần 7 pot

79 189 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Using ADO.NET
Trường học Syngress Media, Inc.
Chuyên ngành Computer Science
Thể loại sách
Năm xuất bản 2001
Thành phố Rockland
Định dạng
Số trang 79
Dung lượng 873,33 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Place it where you would like thegrid to show up on the page see CD file Chapter 09/Chapter9 Beta2/Samples/ get-wwwroot/Chapter9/DataGridSample.aspx: All that is left to do is to popula

Trang 1

This line binds the TypedDataSet to the DataGrid:

DataGrid1.DataSource = tdsOrders1

6 Set the Anchor property of the DataGrid to ALL and build the

solu-tion.The finished form should look like Figures 9.7 and 9.8 After you

press F5, click the button, and expand the default node.

Figure 9.7Finished Form

Figure 9.8Orders Table

Trang 2

Click the plus sign to get a list of tables in our DataSet Select the Orders tablefrom the drop-down to get the view shown in Figure 9.8.

In our example, we start out with a list of orders, and we can expand them byclicking the plus sign at the record selector in the far left of the grid.This pro-vides us with a list of relations In our example, we only have the one, so select it,and the grid will change to show the detail records for that order.When youconsider that we started with a project that consisted of dragging and droppingsome objects from the Server Explorer and the toolbox, entering half a dozenlines of code, this is pretty powerful stuff!

The WebForm DataGrid object in ASP.NET is quite a bit different as far ting one to operate A few lines of code are all it takes to put one of these towork with some basic functionality.The following example creates a basic HTMLtable of our data with just a few lines of code.This is the line of code that willactually place the control on the form for us Place it where you would like thegrid to show up on the page (see CD file Chapter 09/Chapter9 Beta2/Samples/

get-wwwroot/Chapter9/DataGridSample.aspx):

<asp:DataGrid id="DGOrders" runat="server"/>

All that is left to do is to populate the grid with a data source:

Private sConn As String = "<MyConnectionstring>"

Private dsShippers As DataSet

Private Sub BindData() Dim strSQLQuery As String Dim objConn As SqlClient.SqlConnection Dim objAdapter As SqlClient.SqlDataAdapter

strSQLQuery = "SELECT * FROM Shippers"

Create a connection to the SQL Server:

objConn = New SqlClient.SqlConnection(sConn)Create a SqlDataAdapter using the connection and the SQL statement asparameters for the constructor:

objAdapter = New SqlClient.SqlDataAdapter(strSQLQuery, objConn)

Trang 3

Create the DataSet and fill it with the SqlDataAdapter object we created earlier:

dsShippers = New DataSet()

objAdapter.Fill(dsShippers, "Shippers")

Set the DataSource of our data grid to the newly created DataSet, and call

the DataBind method to finish the grid:

collec-Figure 9.9DataGrid Sample

Trang 4

Table 9.5Column Collection Objects

BoundColumn Default column, it is bound to data and allows us

to control the ordering and rendering of the column.

HyperLinkColumn Presents the bound data in HyperLink controls The

text and URL of the hyperlink can be static or bound to data.

ButtonColumn Represents a column with a set of push button

controls Bubbles a user command from within a row to an Event Handler on the grid Not bound to data The developer must write a handler to

perform the action specified

TemplateColumn Defines a template used to format controls within

a column.

EditCommandColumn Displays Edit, Update, and Cancel links to allow the

user to edit line items The DataGrid will present the user with appropriate links and text boxes for the line being edited, while displaying the other rows in read-only text.

The EditCommandColumn creates the DataGrid with some options for theHTML output It is also important to note that the OnEditCommand,

OnCancelCommand, and OnUpdateCommand are mapped to server-side procedures that we have to write Also, turn off the AutoGenerateColumns,which defaults to true:

sub-<asp:DataGrid id="DGOrders" runat="server"

Trang 5

Here we define our columns.The first column is the EditCommandColumn.The options are self-explanatory.The EditText, CancelText, and UpdateText are thetext that will show up in our hyperlinks to perform the desired action.The othercolumns are standard BoundColumns that display the data from the Shippers table:

<Columns>

<asp:EditCommandColumn EditText="Edit"

A DataList is very similar to the WebForm DataGrid, with a few exceptions It uses

template tags, is a WebForm control, and inherits from the WebForm namespace.After adding a new WebForm to a Web project, place the following code betweenthe opening and closing form tags.This block of code defines our DataList and

binds the DataList_Click procedure to the OnItemComand event for the list (see

CD file Chapter 09/Chapter9 Beta2/Samples/wwwroot/Chapter9/

DataListSmaple.aspx):

Trang 6

<asp:Label id="lblShipper" _ runat="server">

Trang 7

Private sConn As String = "<MyConnectionString>"

Private dsShippers As DataSet

Private Sub Page_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

'Put user code to initialize the page here

If Not Page.IsPostBack Then BindData()

End If End Sub

Private Sub BindData() Dim strSQLQuery As String Dim objConn As SqlClient.SqlConnection Dim objAdapter As SqlClient.SqlDataAdapter

strSQLQuery = "SELECT * FROM Shippers"

objConn = New SqlClient.SqlConnection(sConn)

objAdapter = New SqlClient.SqlDataAdapter(strSQLQuery, objConn)

dsShippers = New DataSet() objAdapter.Fill(dsShippers, "Shippers")

Trang 8

DLShippers.DataSource = sShippers.Tables("Shippers").DefaultView DLShippers.DataBind()

End SubThis procedure handles the event bubbled up from the browser:

Public Sub DataList_Click(ByVal Source As Object, _

ByVal E As DataListCommandEventArgs) DLShippers.SelectedIndex = E.Item.ItemIndex

Call BindData() End Sub

Figure 9.10 shows the result

This page shows the usage of the template tags and some of the options able.Template tags give us some options for formatting the different rows.Theyreally make the data controls very flexible and remove many of the reasons wehave for not using them.The available templates vary depending on whichDataControl you are using,Table 9.6 lists the available templates for the DataListcontrol

avail-Figure 9.10DataList Output

Trang 9

Table 9.6DataList Template Items

ItemTemplate Required template that provides the style for

items in the DataList.

AlternatingItemTemplate Provides the style for alternating items in the

DataList.

SeparatorTemplate Provides the style for the separator between

items in the DataList.

SelectedItemTemplate Provides the style for the currently selected item

in the DataList.

EditItemTemplate Provides the style for the item currently being

edited in the DataList.

HeaderTemplate Provides the style for the header of the DataList FooterTemplate Provides the style for the footer of the DataList.

Repeater

The Repeater object is a Web form control that allows us to create templates out

of HTML, and then bind them to data—sort of like making our own grid trol, except that we can use data binding.The tricky part of setting up therepeater is the use of template tags An example is worth a thousand words, sohere is a repeater bound to a DataSet that contains the Shippers table from theNorthwind database (see CD file Chapter 09/Chapter9 Beta2/Samples/

<h3><font face=Verdana>Repeater Example</FONT></H3>

<form id=Form1 runat="server">

<b>Shippers:</b>

<p><asp:repeater id=RPTRShippers runat="server">

<HeaderTemplate>

<table border=1>

Trang 11

Notice the use of the <template> tag In between the opening and closingtemplate tags, we have plain vanilla HTML except for the DataBinding code.The

DataBinding is handled during the Page_Load event, and is very similar to the

DataBinding code in the DataList example, the only difference being the name ofthe Repeater object:

Private sConn As String = "<MyConnectionString>"

Private dsShippers As DataSet

Private Sub Page_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

'Put user code to initialize the page here

If Not Page.IsPostBack Then BindData()

End If End Sub

Private Sub BindData() Dim strSQLQuery As String Dim objConn As SqlClient.SqlConnection Dim objAdapter As SqlClient.SqlDataAdapter

strSQLQuery = "SELECT * FROM Shippers"

objConn = New SqlClient.SqlConnection(sConn)

objAdapter = New SqlClient.SqlDataAdapter(strSQLQuery, objConn)

dsShippers = New DataSet() objAdapter.Fill(dsShippers, "Shippers")

RPTRShippers.DataSource = _ dsShippers.Tables("Shippers").DefaultView

Trang 12

RPTRShippers.DataBind() End Sub

Here we are creating a DataSet, populating it with some data, and thenbinding it.To bind data to a container, it must implement the Ilist interface.Thiscan be done by using the DataTable object Figure 9.11 shows the finished page

Figure 9.11Repeater DataControl Sample

Trang 13

We emphasized the connectionless architecture on which ADO.NET is built,and provided a solution if we need to maintain a connection to our data source

by wrapping the COM+ ADO libraries in NET and using them as native NETlibraries

We reviewed the data providers and discussed the benefits of the SQL Serverdata provider and its close integration with Microsoft SQL Server.We talkedabout connecting to other data sources using the ADO data provider, and theimplications of using the provider to give our applications more options when itcomes to connecting to heterogeneous data

We briefly discussed remoting.This topic is broad enough for a separatebook; however, we covered some of the highlights to get you started if that is adirection in which your application needs to go Remoting allows our application

to communicate across application boundaries Cross-boundary communicationcan take place between two separate applications on the same machine, or appli-cations on separate servers thousands of miles apart

Finally, we discussed the data controls and provided some examples todemonstrate the ease of developing using these controls and some of the newfunctionality that is possible with them

Solutions Fast Track

Overview of XML

; XML documents are the heart of the XML specification

; XSL is a language for applying styles and otherwise formatting XML data

; XDR is a specification for describing the data in XML documents

Trang 14

; XSD is similar to XDR, but provides far more flexibility and is itself anXML document.

; XPath is a language for querying XML documents, or describing pathsbetween them

Understanding ADO.NET Architecture

; ADO.NET Architecture is the latest extension of the Universal DataAccess technology from Microsoft that uses textual formatting instead ofbinary formatting

; In ADO.NET Architecture data is accessed and manipulated in a nectionless manner by using data providers

con-; The Command, Connection, DataReader, and DataAdapter are the coreobjects in ADO.NET.They form the basis for all operations regardingdata in NET

Using the XML Schema Definition Tool

; XML Schema Definition Tool is used to generate XSD, or schema definition files

; XML Schema Definition Tool is used by Visual Studio when creatingTypedDataSets

Connected Layer

; The term connected layer implies that a connection to a data source isopen while data is being analyzed or manipulated

; ADO.NET does not support connected data operations

; Persistent connections must be made using the COM Interop moduleswith the older ADO, and OLE DB Libraries

; Use tlbimp.exe to create NET wrappers

Disconnected Layer

; By its very nature, ADO.NET is disconnected, which means a connection to the data source is not maintained

Trang 15

; A disconnected layer allows our data source to free up resources andrespond to the next user.

Using the SQL Server Data Provider

; The SQL Server data provider is written explicitly to provide data access

to Microsoft SQL Server version 7 and later.This set of classes takesadvantage of the SQL Server API in a way that makes it more efficientfor data access than going through the OLE DB libraries

; The SQL Server data provider’s core objects are SqlConnection,SqlDataAdapter, SqlCommand, and SqlDataReader

Remoting

; Remoting allows objects or components to communicate across networks

or the Internet and takes care of many of the complexities of cating across networks

communi-; XML is key to remoting in ADO.NET

Data Controls

; The data controls in VB.NET are similar to the data controls in VB6.They provide for flexible viewing and editing of data either in the form

of bound data or unbound data

; Data controls can be manipulated at runtime for flexibility and speed

Trang 16

Q:Which object allows for faster reading of data, the DataReader or the DataSet?

A:As always, testing is the final determination, but generally, the DataReader isfaster than the DataSet.The DataReader is intended to provide a scrollablesource of data that provides access to data one row at a time If you arereturning a great number of rows, then the DataReader may be a better ideathan the DataSet.Your testing will determine if the DataSet is better forsmaller amounts of data

Q:Should I use the OLE DB data provider or the SQL data provider?

A:If your project is using SQL Server in production, then by all means use theSQL data provider.The SQL data provider is more efficient and faster thanthe OLE DB libraries, which is the only advantage that I see Both objectshave the same options and methods; the differences lie in the implementa-tion.The OLE DB data provider will allow you to change the DataSourceeasily without having to change much code

Q:Should I use SQL statements or stored procedures for data access?

A:Stored procedures are the preferred method of data access, as they allow foranother layer of granularity to your application Most relational databases alsoprecompile, and take the opportunity to optimize the query plan of thestored procedure based on index statistics.They do, however, require otherspecialized skills that may not be available on your team In general, I woulduse SQL statements as a last resort, or in special instances

Q:When should I use output parameters?

A:Output parameters have less overhead than returning data from a stored cedure If you are returning a couple of pieces of data, or even an entire row

pro-of data, it is more efficient to use the output parameters It is, however, much

Frequently Asked Questions

The following Frequently Asked Questions, answered by the authors of this book, are designed to both measure your understanding of the concepts presented in this chapter and to assist you with real-life implementation of these concepts To have your questions about this chapter answered by the author, browse to

www.syngress.com/solutions and click on the “Ask the Author” form.

Trang 17

more work for both the DBA and the developers It may come down to yourproject deadlines, but in general, they are variables in memory that are moreefficient than an XML data stream.

Q:When should I use return values from stored procedures?

A:Return values are limited to integer data For the most part, this is the iting factor for using return values As far as ADO.NET is concerned, it is justanother output parameter Return values are useful for returning an errornumber, informational number, or the identities of new records

Trang 18

lim-Developing Web Applications

Solutions in this chapter:

Adding Controls to Web Forms

Creating Custom Web Form Controls

Web Services

Using Windows Forms in Distributed Applications

; Summary

; Solutions Fast Track

; Frequently Asked Questions

Chapter 10

459

Trang 19

In Chapter 8 we learned how to use Windows forms and controls; now it is time

to learn about Web forms and controls.This chapter is not meant to teach youhow to develop complete Web applications It is intended to show you how touse Visual Basic NET as a development tool for Web applications

Web forms are a part of ASP.NET that allows you to create programmable Web

pages.They integrate HTML with server-side and client-side programming logic.For those of you who have developed ASP Web pages, you know the headachesthat arise when you try to ensure that your page works correctly on both

Microsoft Internet Explorer and Netscape.Web forms automatically determinethe client’s browser type and create the correct client-side code for that browser.Web forms also give you a richer set of controls for a better user interface

Web form controls are server-side controls that provide the user interface as well

as programmatic functionality.Web form controls are different from Windowscontrols in that they are designed to work with ASP.NET A common and

tedious task in Web pages is data validation.Web form controls have built-in datavalidation capabilities that streamline this task.You will find that Web applicationdevelopment is greatly enhanced, with many more features and capabilities thanwere previously available

In order to move to the next phase of the Internet,Web applications need to

be distributed across the Internet with different functionalities Web services allow

this to happen.Web services are object-based components that use XML andHTTP By allowing communication across the HTTP protocol, you don’t have tochange your existing network architectures or firewall configurations.Web ser-vices are based on open Internet standards that can communicate with compo-nents on different platforms and written in different programming languages.Thisflexibility allows you to communicate with objects through a URL

Another feature of NET that further enhances Web applications is the ability

to use a Windows form as a client-side user interface in a distributed application.This capability is useful when you require a richer user interface An example iscreating Web forms for most of your users but a thick client for your administratorswho would require greater functionality

We end the chapter with developing a Web application utilizing the featurescovered in this chapter.This discussion shows how the pieces fit together.Tocompletely cover Web application development with ASP.NET would require abook unto itself

Trang 20

Web Forms

Web forms extend the Rapid Application Development (RAD) capabilities ofVisual Basic to Web applications, allowing developers to create rich, form-basedWeb pages.Web forms allow users to design Web applications the same way theyuse Windows forms for Windows applications.Web forms provide a rich userinterface, complex layout, and user interaction with no burden on the developer

They also separate the code from the content on a page, eliminating spaghetticode.This feature helps different groups concentrate more on their respectivepieces of code For example, the design group can work on the site using theirdesign tools without having to worry about the code, while the programmers canconcentrate on functionality without worrying about the screen design

Similar to the Windows controls,Web forms have their own controls, called

Web controls However,Web controls have more limited capabilities than their

counterparts, due to the limitations of the Web model For example, some of theevents found in Windows form controls, such as mouse events, are not practical inthe Web model because they require an expensive round trip to the server

Furthermore, these controls aren’t ActiveX controls; they exist only on the serverand render themselves as standard HTML to the client

The Integrated Development Environment (IDE) for Web forms is similar tothat for Windows forms.You will notice few differences in this environmentcompared with Windows applications.The design area does not have a formwindow It contains a blank Web page, white in the background with two tabs(Design and HTML) at the bottom.The HTML tab allows you to view and editthe HTML code for the page On the Design tab you have two options: absolutepositioning (grid layout) and flow layout, which is the default layout.You canchange to the grid layout by using the pageLayout property in the Propertiesdialog box.The difference between flow layout and grid layout is that in flowlayout, the control is dropped where the cursor is currently positioned, whereas

in grid layout, the control is placed in the exact X-Y position, similar toWindows forms It is not a good idea to use grid layout, because your users canuse any platform and any screen resolution In this chapter we use flow layoutonly

In this section, we design a simple Web form.We then see how Web forms aredifferent from Windows forms and why they are better than the existing ActiveServer Pages (ASP).The next section covers Web form controls—the types ofcontrols available and their event model—and finally, we create our own control

Trang 21

A Simple Web Form

Let’s begin our work with a tiny program, the classic “Hello World.” In Exercise10.1, we create a simple Web form.This Web form will have no Web controls.(We discuss Web controls in the next section.) In order to create a Web form, wemust first create a Web application

Exercise 10.1 Creating a Simple Web Form

In this exercise, we create the standard Hello World example

1 Begin a new Visual Basic Web project by selecting File | New | Project and then selecting ASP.NET Web Application under

Visual Basic Projects.The New Project dialog box appears, as shown inFigure 10.1

2 Change the name of the application to Chapter10 If you are using

your local machine as the Web server, leave the Location box set to

localhost; otherwise, enter the name of your Web server in the Location field Click OK and Visual Studio.NET will create the Web project for

you, as shown in Figure 10.2

If you look at the Solution Explorer of the IDE, you will see that ithas more files than a Windows application All of these files are created

Figure 10.1The New Project Dialog Box

CD Exec.

10.1

Trang 22

under the root directory of your Web site, typically C:\Inetpub\

wwwroot\Chapter10 (Chapter10 is the name of our project) Among

these files,WebForm1.aspx (note the new file extension) contains yourWeb form Global.asax is similar to Global.asa in the classic ASP, whichcontains the Application and Session events Styles.css contains the styles

to render HTML AssemblyInfo.vb contains the assembly informationfor this project, such as versioning and assembly name.Web.config con-tains configuration details, and Chapter10.vsdisco contains the discoveryinformation for the Web services.We discuss these two files later in thischapter

3 Using the Properties dialog box, set the pageLayout property to

FlowLayout.

4 Now click the design surface of the form and type Hello World.

5 We have created our first Web form Before you run the program, youmust set the start page for this project In order to do this, right-click the

Web form WebForm1.aspx in the Solution Explorer and then click the Set As Start Page menu option in the popup menu Now let’s run Figure 10.2Visual Studio.NET IDE for a Web Application

Trang 23

the program by pressing F5 or clicking the Start icon in the toolbar.

VS.NET builds the application and invokes Internet Explorer.You willsee the “Hello World” text in the browser

Wasn’t that easy! You can also run the program by compiling it using Build | Build menu (Ctrl+Shift+B) once the form is compiled.You can manually

open the browser and type the URL Here the URL of our Web form is

http://localhost/chapter10/webform1.aspx In this exercise, we created a simpleWeb form Now let’s see the difference between Web forms and Windows forms.How Web Forms Differ from Windows FormsYou might have observed that Web forms and Windows forms look similar; bothcan provide a rich user interface and complex application support to fulfill busi-ness requirements.The two types of forms might look similar from a design anddevelopment point of view, but they differ a great deal in terms of implementa-tion For example, for an e-commerce application that will be accessed over theInternet on different platforms and browsers,Web forms may be used.When cre-ating a highly responsive system with high-volume transactions for an officeapplication,Windows forms are the best choice In other words, a Web form is a

thin client and a Windows form is a thick client In some cases, the choice

between Web forms and Windows forms might not be immediately clear In thissection we see how Web forms and Windows forms differ in various situations:

User interface Windows forms can take advantage of NET WinFormsand graphics classes to create rich user interfaces, whereas in Web forms,user interaction requires an expensive round trip to the server, creating aslower response

Security Windows forms have complete access to local computerresources, whereas browser security limits Web forms

Client platform All clients in Windows forms require the NETframework, whereas Web forms require only a browser, so they cantarget any client platform.The only requirement here is that the Webserver should be running NET Framework

Client application Windows forms are thick clients, so they rely onthe client processor.Web forms usually are thin clients and hence theirclients don’t have to use high-performance machines

Trang 24

Throughput Windows forms run on the client side, so they can vide the quickest response and high throughput.Web forms rely on thenetwork traffic over HTTP and hence can’t give high throughput andmight not be suitable for applications requiring high throughput withhigh-volume transactions.

pro-■ Deployment Since Windows forms run on the client machine, theyneed to be installed on all user desktops As the users grow in numberand with each new release, the deployment becomes tedious.Web formshave no client deployment at all.The client requires only a browser toview them

You can see that the difference between Web forms and Windows forms isbasically the difference between client/server applications and Web applications

Because Web forms use a browser, a universal client, they are excellent for targeting a wide range of clients and for intranet applications

Why Web Forms Are Better Than Classic ASPASP.NET makes it much easier to build enterprise Web applications ASP.NET islargely syntax compatible with ASP, but under the hood it is completely changedand rewritten to take the advantage of NET Framework ASP.NET pages arecompiled to CLR For this reason, you can use any NET-compatible language:

Visual Basic, C#, or Jscript.NET VBScript is now knocked out, and the friendlyand sophisticated Visual Basic is used in its place, thereby using all the features ofthis language.This change makes it possible for developers to access all the NETFramework classes in ASP.NET as they would in Visual Basic

If you have developed any ASP pages, you are very familiar with the majorlimitations of ASP.The new ASP.NET addresses all of these limitations and pro-vides a much-simplified development environment Let’s see the benefits ofASP.NET over its predecessor:

Simplicity ASP.NET makes it easy to perform common tasks such asform submission, client authentication, site configuration, and deployment

Improved performance Because ASP.NET is compiled to CLR, itcan take advantage of early binding and JIT thus having significant performance over its interpreted predecessor

Strong typed language ASP.NET now uses Visual Basic as the programming language rather than VBScript, which supports only the

Trang 25

Variant data type.With VB in ASP.NET, we can take advantage of various data types.

Event-driven model ASP.NET supports an event-driven model, justlike Visual Basic, thus eliminating the large case statements in the begin-ning of the page to determine with which button the user has inter-acted ASP.NET supports Session and Application events in Global.asaxsimilar to that in ASP In addition to these four events, Global.asax nowsupports more than a dozen events

Nonspaghetti code The programming model of ASP.NET separatesthe code from the presentation, making constructing and maintenance ofcode easier

State management ASP.NET provides easy-to-use Application andSession states that are familiar to ASP developers In ASP, the Sessionstate resides in the memory of the server, so you can’t use it in a Webfarm ASP.NET eliminates this limitation by moving the sessions notonly out of process but also out of machine ASP.NET uses a dedicatedstate server process that runs as a Windows NT service.This state serverlistens on a port (default port 42424).This means that you can create adedicated state server for your Web farm.You can even tell ASP.NET touse SQL Server to store State

Security ASP.NET provides authorization and authentication services

in addition to IIS authentication services ASP.NET takes the burdenfrom you to authenticate and authorize users stored in a database or in aconfig file Users can be authenticated and authorized using

CookieAuthenticationModule and URLAuthorizationModule, whichsets a cookie that contains the user credentials, and that cookie ischecked for subsequent requests

Configuration ASP.NET uses an XML file to store configuration tings rather than depending on the IIS metabase.This makes the deploy-ment of the site easier, especially in a Web farm

set-■ Web services ASP.NET allows you to expose your business functions

to your business partners over standard Web protocols

Cache services ASP.NET allows you to cache the output of yourdynamic page, thus increasing throughput

Trang 26

Debugging ASP.NET has a built-in tracing utility.You don’t have to useResponse.Write periodically to trace your program execution Developerscan now use the debugging features they are accustomed to using.

Deployment Deployment is as simple as copying the files.This isbecause all the configuration settings of the site are in an XML file

Furthermore, it avoids DLL Hell (component registration, versioning,locked DLLs, and so on).You can even recompile a component anddeploy it without having to restart the Web server

At first glance, you might think that all of these benefits will probably makeyour development harder Actually, the features of ASP.NET are designed to beeasier to use If you want to take full advantage of ASP.NET, you have to rewriteyour current applications.The good news is that ASP and ASP.NET can co-exist

on the same machine In order to accomplish this compatibility, Microsoft duced new file extensions for ASP.NET (.ASPX, ASAX, and so on) so you canconvert them at your own pace

intro-Adding Controls to Web Forms

Web form controls are server-side controls that are instantiated on the server andrender HTML to the browser.These controls detect the browser and then gen-erate HTML accordingly to provide a customized appearance to the user

Furthermore, these controls expose events similar to the Windows controls, thusworking within an event-driven programming model

Placing the Web form controls on a Web form is similar to placing aWindows control on a Windows form.The only difference is that the layout ofthe Web form is linear and the controls are dropped where the cursor is currentlypositioned If you don’t feel comfortable with this setup, you can change thelayout to grid layout, which allows you to place the controls on the form simi-larly to a Windows form

NOTE

Web form controls not only detect browsers such as Internet Explorer and Netscape, but they also detect devices such as Palm Pilots and cell phones and generate appropriate HTML accordingly.

Trang 27

Exercise 10.2 Adding Web Controls to a Web Form

In this exercise, we first create a Web form and place four controls in it.Then wetake a close look at the code, and finally we examine the different types of con-trol available Use the same Web form that we created in Exercise 10.1

1 Open the Web application project

2 In the Web form, delete the Hello World text

3 Place some controls on the form: two label controls, one text box trol, and a button control

con-4 Place a label control that contains the heading of our application and setthe following properties using the Properties dialog box:

Text: Customer Order Details Font-Size: X-Large

ID: lblCustomerOrder

5 Select the design surface and press Enter.Then place another label

con-trol on the form by setting the following properties:

Text: Customer ID ID: lblCustomerID

6 Place a text box control next to the second label control and set itsproperties to:

Text: “” (empty) ID: txtCustomerID

7 Press Enter and then place a button control and change its

8 Save the Form (Ctrl+S) and let’s test the form we created Press F5 to

run the application.Visual Studio builds the Web form and invokesInternet Explorer, as shown in Figure 10.4

When you click the button, nothing happens.That’s because we haven’t addedany code Actually, when you click the button, the browser sends a request to the

server with the entire user entered data; this process is called form submission.You

might not notice this process if your local machine is the Web server because the

CD Exec.

10.2

Trang 28

response is quick.Try entering something in the text box and click the button;

you can see that the text you entered persists in the form submission.Web forms

do this for us without writing any code In classic ASP, user-entered data does notpersist in form submission and we have to write code to do this

Now let’s see the code of the Web form In the VS.NET IDE, click the

HTMLbutton below the design surface to view the HTML code.The Web

Figure 10.3A Web Form with Controls

Figure 10.4Viewing Web Form Controls Using a Browser

Trang 29

form code generated by IDE will look familiar to an ASP developer Here is thecode generated by IDE:

<%@ Page Language="vb" AutoEventWireup="false"

<asp:Button id=cmdGetDetails runat="server"

Text="Get Order Details"></asp:Button>

</p>

</form>

</body>

</html>

Trang 30

Let’s go through the code Ignore the following first line for now; we will discuss it later:

<%@ Page Language="vb" AutoEventWireup="false"

Codebehind="WebForm1.aspx.vb"

Inherits="Chapter10.WebForm1"%>

The next few lines contain the header information and metatags of the

HTML page After that is the form tag Observe the runat clause at the end:

<form id="WebForm1" method="post" runat="server">

The runat clause tells NET that this is a Web control and will expose the form events.You might have noticed that the action attribute is missing here If the action attribute is missing, the form posts to itself—that is, to the same page.

So, in ASP.NET, all the forms post to themselves Now let’s see the code for thecontrols you have placed in the form First observe the heading label:

<asp:Label id=lblCustomerOrder runat="server" Large">

Font-Size="X-Customer Order Details

</asp:Label>

asp:Label says that it is a label control in the ASP namespace All the controls

available in ASP.NET are under the ASP namespace and have a runat clause.

Unlike HTML, ASP.NET is strict with closing tags All the opened tags must beclosed; otherwise, ASP.NET generates a compile error As mentioned earlier, allthe Web form controls render themselves as HTML to the client So if you viewthe HTML source in the browser, you will see pure HTML code Let’s see theHTML code returned by the Web server:

Trang 31

value="YTB6MTk1NDExNjQxNl9fX3g=e92c2469" />

<p>

<span id="lblCustomerOrder" style="font-size:X-Large;">

Customer Order Details

</span>

</p>

<p>

<span id="lblCustomerID ">Customer ID</span>

<input name="txtCustomerID" type="text" id="txtCustomerID"/>

</p>

<p>

<input type="submit" name="cmdGetDetails"

value="Get Order Details" id="cmdGetDetails"/>

</p>

</form>

</body>

</html>

Notice the form tag generated by the Web form.This tag has an action

attribute and its value is the current name of the page, thus posting to itself.Under the form tag, observe the hidden field:

<input type="hidden" name=" VIEWSTATE"

value="YTB6MTk1NDExNjQxNl9fX3g=e92c2469" />

ASP.NET uses this field to maintain the state across the page submission Asyou’ll recall, the text you entered in the TextBox persisted after the page submis-sion.You can use this state management to store values similar to the Sessionvariables Classic ASP uses Session variables to store State across pages (A detaileddiscussion of this topic is beyond the scope of this chapter.) All the label controls

placed in the form rendered themselves to a span tag.TextBox and button

con-trols rendered into the HTML input tag.Web forms generate HTML, so they can

be viewed in any browser

Now let’s write some code If the button is clicked, we set the text in the

TextBox to Button is clicked In order to write code for the Click event, in the

VS.NET IDE design, double-click the button control to open the code window.Observe that a new window is opened and your cursor is positioned inside the

Trang 32

cmdGetDetails_Click function For now, ignore the rest of the code and writethe following code to set the text of the TextBox:

txtCustomerID.Text = "Button is clicked"

Compile the program, run it in the browser, and click the button.You seethat the text in the TextBox is changed to what we have entered in the code

Code BehindBefore going into the VB code, let’s revisit the first line in the Web form:

<%@ Page Language="vb" AutoEventWireup="false"

Codebehind="WebForm1.aspx.vb"

Inherits="Chapter10.WebForm1"%>

This is called a page directive, and it tells the compiler that the language used in

this page is Visual Basic, its code is found in the file WebForm1.aspx.vb under thesame folder, and this page is inherited from Chapter10.WebForm1 If you see files

in the physical directory under the Web server, you will notice a Visual Basic filecalled WebForm1.aspx.vb.This file is named the same as the filename of the Webform with a VB extension.When you compile your Web form,Visual Studio actu-ally compiles this file into an assembly (.DLL) under the bin directory of the Webapplication on the Web server If you check the bin directory of your application

on your Web server, you will see the DLL In our case, you will find Chapter10.dllunder C:\Inetpub\wwwroot\Chapter10\bin.This DLL contains the namespaceChapter10 (the name of our Web application) and all the Web forms in our appli-cation as classes inside this namespace.This structure restricts the usage of the samefilename for the Web form, even though the files are in different folders.This

technique is called code behind because code is behind the form.

Now let’s see the Visual Basic code for this form.The first few lines importdifferent namespaces commonly used in the ASP.NET Of these namespaces, werequire System.Web.UI and System.Web.UI.WebControls because they containthe page and Web control APIs:

Imports System Imports System.ComponentModel.Design Imports System.Data

Imports System.Drawing Imports System.Web Imports System.Web.SessionState

Trang 33

Public Class WebForm1

Inherits System.Web.UI.Page

Protected WithEvents cmdGetDetails As

System.Web.UI.WebControls.Button Protected WithEvents txtCustomerID As

System.Web.UI.WebControls.TextBox Protected WithEvents lblCustomerID As

System.Web.UI.WebControls.Label Protected WithEvents lblCustomerOrder As

System.Web.UI.WebControls.LabelObserve the hidden region (This is similar to what you see in Windows formcode.) The hidden region is where Visual Studio places the generated code.Youshouldn’t modify this code:

#Region " Web forms Designer Generated Code "

'This call is required by the Web form Designer.

<System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent()

End Sub

Private Sub Page_Init(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Init 'CODEGEN: This method call is required by the Web form Designer

'Do not modify it using the code editor.

Trang 34

InitializeComponent() End Sub

#End RegionAfter this hidden region, we have all the events exposed by the Web form

Here you see the code we wrote for the Button Click event.The WebForm1_Load event is similar to the form Load event, and the WebForm1_Init event fires when

the page is initialized.This is the first event in the page’s life cycle; after that, theload event triggers and is followed by events of the controls in the form Other

events such as PreRender and UnLoad trigger in the form life cycle Apart from

these events, more than a dozen events in Global.asax trigger for every request to

a Web form Covering them is beyond the scope of this chapter:

Private Sub cmdGetDetails_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles cmdGetDetails.Click

txtCustomerID.Text = "Button is clicked"

End Sub Private Sub Page_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here

End SubSimilar to the events in the Windows forms, every event delegate in Web

forms has two arguments: the sender of the event (in the Button Click event, the

sender is the button) and an instance of the class that holds data for the event

The Handles keyword attaches this procedure to the object declared using theWithEvents keyword Because the sender contains the object that triggered theevent, it is used to get or set the object properties.The second parameter is used

to retrieve other data associated with the event—for example, an ImageButton

Control Click event contains X and Y coordinates where a user clicked.

So far, we have seen a Web form with some Web controls In the next tion, we look at various types of control available in Web forms Before that, wesee how Web form controls differ from Windows form controls

Trang 35

sec-How Web Form Controls Differ

from Windows Form Controls

Web form controls are similar to Windows form controls.They both have driven programming models.The main difference between them is that Web formcontrols generate HTML to the user, whereas Windows controls take advantage ofrich user features available in the Microsoft Windows operating system

event-In Windows form controls, events are raised and handled on the client sideonly, whereas in Web form controls, the events are raised on the client browserbut they are handled on the Web server Because of this model,Web form con-trols have fewer events than their counterparts

ASP.NET Server Controls

Web form server controls are broadly classified into four categories: intrinsic

con-trols, bound concon-trols, custom concon-trols, and validation controls Intrinsic controls are those controls that can render themselves to equivalent HTML elements Bound

controls help us lay out a page in a grid or list format with data returned from a

database Custom controls are the rich controls that are not available in HTML, such as the calendar control Finally, Microsoft provided validation controls to

validate user inputs.The following sections examine each control type in detail.Intrinsic Controls

In Exercise 10.2, we used three controls: label, text box, and button All threecontrols rendered HTML to the client, so these controls are intrinsic controls.There are several other intrinsic controls besides these For those of you whohave worked with ASP previously, you know that for a text box you would writeHTML as follows:

<input type="text" name="txtCustomerID" id="txtCustomerID">

Web Form Deployment

Deploying a Web form involves simply copying the ASPX file and DLL in the bin directory to their destinations The DLL file should always be in the bin directory.

Developing & Deploying…

Trang 36

In the previous exercise, you noticed that the equivalent of this code inASP.NET controls is:

<asp:TextBox id=txtCustomerID runat="Server">

There is another way of creating a server control, simply add a runat clause to

the HTML:

<input type="text" name="txtCustomerID"

id="txtCustomerID" runat="server">

Adding the runat clause to the HTML element makes this a server control.

ASP.NET exposes all of the events of this control.These controls are called HTML

server controls All of the HTML server controls are derived from the namespace

System.Web.UI.HtmlControls ASP server controls and HTML server controlsbehave in exactly the same manner.The main difference between these controls isthat ASP Server controls detect the browser and generate the appropriate HTML(HTML 3.2 or HTML 4.0), whereas with HTML controls, you have to writecode for browser detection if you want to take advantage of the upper-levelbrowser For this reason, ASP.NET server controls have a richer object model thanHTML server controls In this chapter, we use ASP server controls only.Table 10.1shows the various ASP.NET intrinsic controls and their HTML equivalents

Table 10.1ASP.NET Controls and Their Corresponding HTML Elements

Label <span> … </span>

TextBox <input type=”text”>

Button <input type=”Submit”>

LinkButton <a href=”javascript:form.submit()”>

ImageButton <input type=”image”>

HyperLink <a href=””>

DropDownList <select> </select>

ListBox <select size=””> </select>

CheckBox <input type=”checkbox”>

RadioButton <input type=”radio”>

Panel <div> </div>

Table <table>… </table>

Trang 37

All intrinsic controls run at the server level and render HTML elements.Among these intrinsic controls, some of the controls such as DropDownList andListBox controls can be bound to a dataset from the database.We discuss how tobind a dataset to the control in the next section.

Bound Controls

In a Web page, we usually retrieve data from the database and show it to the user

in a tabular form or in a list form Microsoft introduced three bound controlsthat do the work for us; they are DataGrid control, Repeater control, and

DataList control.The DataGrid is the richest bound control and the easiest way

to display the data in a grid control In a Repeater control, you define the layout

of individual items.When the page is run, the control repeats the layout for eachitem in the data source DataList is similar to the Repeater control and providesmore formatting options

DataGrid

As mentioned earlier, DataGrid allows us to display the data returned from a datasource in a tabular form.This is the most commonly used control.The controlhas numerous customization options First let’s see a simple DataGrid in action,and then we can apply some customizations

Exercise 10.3 Using the DataGrid Control

Use the same project that we used for Exercise 10.2 In that exercise, we placedfour controls on a Web form (refer back to Figures 10.3 and 10.4) Once the userenters the Customer ID and clicks the button, it shows the orders placed by thecustomer.Typically, orders are shown in a tabular form, which is where DataGridcomes into the picture

For this exercise, we use the NorthWind database, which comes with defaultinstallation of the SQL Server 2000 In the NorthWind database, the Orders tablecontains all the orders placed by the customers.We will use this table to get theorders placed by the user-supplied Customer ID

1 Open the Chapter10 Web application project

2 Place a DataGrid control on the Web form by dragging and dropping itfrom the toolbox and set the following properties:

ID: dgOrders HeaderStyle-BackColor: Navy HeaderStyle-Font-Bod: True

CD Exec.

10.3

Trang 38

HeaderStyle-ForeColor: White AlternatingItemStyle-BackColor: Silver

After placing the DataGrid control in the Web form, your designarea should appear as shown in Figure 10.5

For this design, the user enters a Customer ID and clicks the Get

Order Details button So, for the Button Click event, we need to write

code to get the orders placed by the customer In order to reuse thecode, we create a function that will return the dataset containing theorders placed by the customer for a given Customer ID

3 Add the following code to your page in WebForm1.vb:

Public Function GetOrders(ByVal CustomerID As String) As DataSet

Dim sConnectionString As String Dim sqlString As String

Dim MyConnection As SqlConnection Dim MyDataAdapter As SqlDataAdapter Dim DS As New DataSet()

'building the connection string sConnectionString = "Server=localhost;

Database=Northwind; "

sConnectionString += "UID=sa; pwd=;"

Figure 10.5DataGrid Control in Design Time

Trang 39

'building the select statement sqlString = "SELECT * FROM Orders "

sqlString += "WHERE CustomerID = '" + CustomerID + "'"

'opening the connection MyConnection = New SqlConnection(sConnectionString) MyDataAdapter = New SqlDataAdapter(sqlString, MyConnection)

'getting Data Set MyDataAdapter.Fill(DS, "Orders")

Return DS End FunctionBecause you saw in the previous chapter how to access data from adatabase, we don’t delve into this code here.You might have to changethe username and password, depending on your SQL Server setup Here

we use SqlConnection and SqlDataAdapter instead ofOleDBConnection and OleDBDataAdapter for data retrieval

SqlConnection and SqlDataSetCommand are part of the ADO.NET andare optimized for SQL Server to provide more functionality and fasteraccess than a generic managed provider In order to use SQL APIs inour code, we have to import that namespace

4 To import the SQL namespace, add the import statement to the code:'other import statements

Imports System.Data.SqlClient

5 Place the following code in the Button Click event:

Dim DS As DataSet 'getting the DataSet with Order Details for the entered CustomerID

DS = GetOrders(txtCustomerID.Text) 'Binding the DataGrid

dgOrders.DataSource = DS.Tables("Orders").DefaultView dgOrders.DataBind()

Ngày đăng: 14/08/2014, 04:21

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN