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

C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#

.pdf
Скачиваний:
128
Добавлен:
12.02.2016
Размер:
7.64 Mб
Скачать

the DataGrid control

BindGrid()

When you run this application, you'll notice that the customer details are reflected in the DataGrid control after you enter the data in the respective text boxes and click the Add button.

Modifying and deleting data

The DataGrid control enables users to modify and delete records. To allow rows to be edited, the EditItemIndex property of the DataGrid control is used. By default, this property is set to -1, indicating that no rows are editable.

The DataGrid control has a property called Columns that you can use to add buttons to allow user interaction with individual data rows. To add a button column, follow these steps:

1.Open the Property Window of the DataGrid control.

2.Click the ellipsis in the Columns property to open the Properties dialog box, as shown in Figure 12-4.

Figure 12-4: The Properties dialog box

3.In the left pane, click Columns.

4.In the right pane, under the Available Columns list, under Button Columns, select Edit, Update, Cancel and click the > button to add this button column to the control.

5.Click OK to close the dialog box.

The DataGrid control can have three types of button columns, described as follows:

§The Select button column renders a Select link button used to access a specific row.

§The Edit, Update, Cancel button column renders three link buttons: Edit, Update, and Cancel. The Edit button is used to display the row in Edit mode. After the row switches to Edit mode, the column displays Update and Cancel buttons, which are used to update or cancel the changes made to the row.

§The Delete button column renders a Delete button that enables users to delete a specific row.

To add the update functionality, add the Edit, Update, Cancel button column to your DataGrid control. When the Edit button is clicked, the EditCommand method of the DataGrid control is called. The UpdateCommand method is called when the Update button is clicked. And, when the Cancel button is clicked, the CancelCommand method

is called. Therefore, you need to write appropriate code in these methods to implement the desired functionality.

In the EditCommand method of the DataGrid control, set the EditItemIndex property as follows:

Public Sub MyDataGrid_EditCommand(ByVal source As Object,

ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)

Handles MyDataGrid.EditCommand

'Setting the EditItemIndex property of the DataGrid

control to indicate the row to be edited

MyDataGrid.EditItemIndex = e.Item.ItemIndex

End Sub

In this code:

§The EditCommand method takes two arguments:

osource: Represents the object that generates the event. In this case, the source is the DataGrid control.

oe: Represents the object of the DataGridCommandeventArgs class. This argument represents the event information of the source.

§Item indicates the item that generated the event. In this case, it is the DataGrid control.

§ItemIndex represents the row number for the item.

After you've written this code, you need to use the following SQL statement as a String variable in the UpdateCommand method to modify the customer address based on a customer ID:

Dim UpdateCmd As String = "Update Customers Set Address =

@Address Where CustomerID = @CID"

MyCommand = New SqlCommand(UpdateCmd, MyConnection)

Now, let us discuss how we can implement data deletion in a SQL table. The first step is to add a Delete button column to the DataGrid control. Then, in the DeleteCommand method of the DataGrid control, add the code to delete a customer record. The following SQL statement needs to be used as a String variable to delete a customer record based on a customer ID:

'Defining the SQL query to delete a record from Customers table

Dim DeleteCmd As String = "Delete from Customers where CustomerID = @CID"

MyCommand = New SqlCommand(DeleteCmd, MyConnection)

After understanding how to update and delete data in a SQL Server database, let us now see how to use stored procedures through your Web applications.

Using stored procedures

As mentioned earlier, stored procedures perform database operations more efficiently than the ad hoc SQL queries, because stored procedures are stored on the SQL Server.

You simply need to write the procedure's name and the procedure parameters, if any, to execute the stored procedure. When using stored procedure, the traffic is less as compared to passing the complete set of SQL queries to the server. Therefore, the performance is greatly improved.

If a stored procedure already exists on a SQL Server, use the following syntax to create the SqlDataAdapter object:

MyCommand = New SqlDataAdapter("Procedure_Name", MyConnection)

MyCommand.SelectCommand.CommandType = CommandType.StoredProcedure

In this syntax:

§MyCommand is the object of the SqlDataAdapter class.

§MyConnection is the object of the SqlConnection class.

§Procedure_Name represents the name of the procedure to be called.

§The second statement specifies that the command passed in statement1 is a stored procedure.

Stored procedures can also take parameters that need to be passed while executing them. Parameters make the stored procedures more flexible because they return results based on user input. For example, you can create a stored procedure that takes a product name as a parameter and displays the product details for the specified product. To use stored procedures that take parameters, use the following syntax:

MyCommand = New SqlDataAdapter("Procedure_Name", MyConnection)

MyCommand.SelectCommand.CommandType = CommandType.StoredProcedure

'Adding a SQL parameter with SQL data type

MyCommand.SelectCommand.Parameters.Add(New

SqlParameter("@Parameter_name",

SqlDbType.datatype, size))

'Setting the value of the SQL parameter

MyCommand.SelectCommand.Parameters("@Parameter_name").Value =

TextBox1.Text

In the last statement, the value of the parameter is initialized. Here, the value is initialized by a value entered in a text box at run time.

Before you can use a stored procedure in your Web application, create a procedure named "DisplayCustomer." The code for the same is given as follows:

Create Procedure DisplayCustomer (@CustID Varchar(4))

As

Select * from Customers

Where CustomerID=@CustID

Return

Next, you'll extend the functionality of the Customer form shown in Figure 12-3.

Add a button with ID and text as "Query." In the Click event of this button, write the following code:

Dim DS As DataSet

Dim MyConnection As SqlConnection

Dim MyCommand As SqlDataAdapter

MyConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=Pubs")

'Calling the DisplayCustomers stored procedure

MyCommand = New SqlDataAdapter("DisplayCustomers", MyConnection)

MyCommand.SelectCommand.CommandType = CommandType.StoredProcedure

'Adding the SQL parameter

MyCommand.SelectCommand.Parameters.Add(New SqlParameter("@CustID",

SqlDbType.NVarChar, 4))

'Specifying the parameter value

MyCommand.SelectCommand.Parameters("@CustID").Value = Customer_ID.Text

DS = New DataSet()

MyCommand.Fill(DS, "Customers")

MyDataGrid.DataSource = DS.Tables("Customers").DefaultView

MyDataGrid.DataBind()

When you run the application, you can test the code for its functionality. To do so, enter a customer ID in the Customer ID text box and click the Query button. The DataGrid control now displays only one record with the specified customer ID.

Using ADO Extensions (ADOX)

Data is stored and maintained in different data sources. Some data source applications include MS-Access, SQL Server, Oracle, and Sybase. Each data source uses its own native syntax. Therefore, when you need to manage data stored in data sources from your applications, you would prefer to use standard objects and syntaxes irrespective of the data sources. It is inconvenient to use different objects, methods, and syntaxes to manage different data sources. ADOX provides a set of standard objects that you can use to manage data stored in different data sources.

ActiveX Data Objects Extensions (ADOX) is an extension of the ADO objects and programming model that allows creation, modification, and manipulation of schema objects, such as databases, tables, and columns. ADOX also includes security objects that enable you to maintain users and groups that access the schema objects. ADOX

security objects can be used to grant and revoke permissions on objects that are accessed by different users and groups.

ADOX is part of the Microsoft Data Access Components (MDAC) SDK. When you install Visual Studio .NET, the Windows Component update installs MDAC 2.7. You can visit the http://www.microsoft.com/data/download.htm site to get the latest release of MDAC SDK.

Standard ADOX objects

ADOX objects are a set of standard objects that are used to create and manipulate data stored in different data sources irrespective of their native syntaxes. Table 12-4 describes the ADOX objects.

Table 12-4: ADOX objects

Object

Catalog

Description

Represents the collections that describe the schema catalog of a data source.

Table

 

Represents

 

 

 

 

a table

 

 

stored in a

 

 

database.

 

 

This object

 

 

includes

 

 

columns,

 

 

indexes,

 

 

and keys.

 

 

 

Column

 

Represents

 

 

 

 

a column

 

 

that might

 

 

be from a

 

 

table, index,

 

 

or key.

 

 

 

Index

 

Represents

 

 

 

 

a table

 

 

index.

 

 

 

Key

 

Represents

 

 

 

 

a key field:

 

 

primary,

 

 

foreign, or

 

 

unique.

 

 

 

View

 

Represents

 

 

 

 

a view,

 

 

which is a

 

 

set of

 

 

filtered

 

 

records from

 

 

a table.

 

 

 

Procedure

 

Represents

 

 

 

 

a stored

 

 

procedure in

 

Table 12-4: ADOX objects

 

 

 

 

 

 

 

 

 

Object

 

Description

 

 

 

 

 

 

 

 

 

a database.

 

 

 

 

 

 

 

User

 

Represents

 

 

 

 

 

 

 

 

a user who

 

 

 

 

has access

 

 

 

 

to a

 

 

 

 

database.

 

 

 

 

 

 

 

Group

 

Represents

 

 

 

 

 

 

 

 

a group that

 

 

 

 

has access

 

 

 

 

to a

 

 

 

 

database.

 

 

 

 

 

 

The different ADOX objects can be grouped together in ADOX collections. For example, Tables is an ADOX collection that represents all the Table objects in a catalog. The other ADOX collections are Columns, Indexes, Keys, Views, Procedures, Users, and Groups.

The different ADOX objects share a set of common properties and methods. Table 12-5 describes some of the ADOX properties.

Table 12-5: ADOX properties

Property

ActiveConnection

Count

Description

Represents the ADO

Connectio n object.

Represents the number of objects in an ADOX Collection.

Name

 

Represents

 

 

 

 

the name of

 

 

an ADOX

 

 

object.

 

 

 

PrimaryKey

 

Used to

 

 

 

 

indicate

 

 

whether or

 

 

not the

 

 

index

 

 

represents a

 

 

primary key.

 

 

 

Unique

 

Used to

 

 

 

 

indicate

 

 

whether or

 

 

not the

 

 

index

 

 

represents a

 

 

unique key.

 

 

 

Type (Column)

 

Represents

 

 

 

 

the data

 

 

type of a

 

 

column.

 

Table 12-5: ADOX properties

 

 

 

 

 

 

 

 

 

Property

 

Description

 

 

 

 

 

 

 

Type (Key)

 

Represents

 

 

 

 

 

 

 

 

the data

 

 

 

 

type of the

 

 

 

 

key.

 

 

 

 

 

 

 

Command

 

Represents

 

 

 

 

the ADO

 

 

 

 

Command

 

 

 

 

object that is

 

 

 

 

used to

 

 

 

 

create or

 

 

 

 

execute a

 

 

 

 

procedure.

 

 

 

 

 

 

 

Table 12-6 describes some of the ADOX methods.

 

 

 

 

Table 12-6: ADOX methods

 

 

 

Method

 

Description

 

 

 

Create

 

Used to

 

 

 

 

create a

 

 

catalog.

 

 

 

Delete

 

Used to

 

 

 

 

delete an

 

 

object from

 

 

an ADOX

 

 

Collection.

 

 

 

Append

 

This is a

 

 

common

 

 

method

 

 

shared

 

 

among

 

 

different

 

 

objects and

 

 

is used to

 

 

add a new

 

 

ADOX

 

 

object to an

 

 

ADOX

 

 

Collection.

 

 

For

 

 

example,

 

 

when used

 

 

with Tables

 

 

object, the

 

 

method is

 

 

used to add

 

 

a Table

 

 

object to a

 

 

Tables

 

 

Collection.

 

 

 

GetObjectOwner

 

Used to get

 

 

 

 

the name of

 

 

the owner of

 

 

an object in

 

 

a catalog.

 

Table 12-6: ADOX methods

 

 

 

 

 

 

 

 

 

Method

 

Description

 

 

 

 

 

 

 

SetObjectOwner

 

Used to

 

 

 

 

 

 

 

 

specify the

 

 

 

 

owner of an

 

 

 

 

object.

 

 

 

 

 

 

 

GetPermissions

 

Used to get

 

 

 

 

 

 

 

 

the

 

 

 

 

permissions

 

 

 

 

for a user or

 

 

 

 

a group on

 

 

 

 

an object.

 

 

 

 

 

 

 

SetPermissions

 

Used to

 

 

 

 

 

 

 

 

specify

 

 

 

 

permissions

 

 

 

 

for a user or

 

 

 

 

a group on

 

 

 

 

an object.

 

 

 

 

 

 

 

ChangePassword

 

Used to

 

 

 

 

 

 

 

 

change the

 

 

 

 

password of

 

 

 

 

a user.

 

 

 

 

 

 

 

Using ADOX objects

 

 

 

You can use ADOX objects in your Web applications to manage data stored in different data sources. However, before you can use ADOX objects, you need to establish a reference to the ADOX type library. The name of the ADOX library is Msadox.dll. To establish a reference to this type library, select Add Reference from the Project menu. Then, you can specify the path for the library.

Note ADOX requires an interop assembly. When you add reference for the ADOX library, a dialog box appears asking you if you want to generate an interop wrapper. At this stage, click Yes to add the ADOX reference.

After adding the reference to the type library, you can go ahead and write the code to create databases, tables, or columns in a table.

To create a database, use the following syntax:

Dim ObjectName as New ADOX.Catalog

ObjectName.Create "Provider = Name of the provider; Data Source = Path of the database"

In this syntax:

§ObjectName refers to the instance of the ADOX Catalog object.

§The Create method takes two parameters:

oProvider: Specifies the name of the database provider. The different providers include Microsoft OLE DB Provider for ODBC, Microsoft OLE DB Provider for the Microsoft Jet Database Engine, Microsoft OLE DB

Provider for Oracle, and Microsoft OLE DB Provider for

SQL Server.

oData Source: Specifies the path where you want to create the database.

The following code snippet illustrates how to create a table called "Products" in a database called "Sales.mdb" stored in MS Access:

Dim table1 as New Table

Dim catalog1 as new ADOX.catalog

'Setting a connection with the Sales database

catalog1.ActiveConnection = "Provider = Microsoft.Jet.

OLEDB.4.0; Data Source = C:\Sales\Sales.mdb"

'Specifying the name of the table

table1.Name = "Products"

'Adding columns in the table. Notice that the column

name along with its data type is specified as arguments to the Append method.

table1.Columns.Append "ProductID", adVarWChar, 4

table1.Columns.Append "ProductDescription", adVarWChar, 20

table1.Columns.Append "Price", adInteger

table1.Columns.Append "Quantity", adInteger

'Adding the table in the Tables collection. Notice that the

Table object is specified as an argument to the Append method.

catalog1.Tables.Append table1

In addition to managing data with ADOX objects, you can set the security options associated with different schema objects. Before you can use the ADOX objects to set user or group permissions, you must open the connection with the system database that stores all security information. Then, you can use the GetPermissions and SetPermissions functions to grant and revoke user or group access permissions on an object.

Summary

This chapter explored the server-side data access by using SQL Server from your Web applications. First, you learned the SQL basics. You learned how to retrieve, add, modify, and delete data in SQL tables. You also learned how to create and execute stored procedures. Then, you learned how to implement the retrieval, addition, modification, and deletion of server-side data from your Web applications. You also learned to implement stored procedures in your Web applications. Finally, you learned how to use ADOX objects to create and manipulate schema objects.

Chapter 13: Advanced Data Binding and XML

Overview

The World Wide Web and its rapid growth in the 1990s revolutionized the methods of accessing information and conducting commerce. Numerous companies use the Web as a powerful tool to advertise and sell their products. This has led to an increase in the number of Web applications and their requirements in terms of payment handling, data access, and security. As a result, various new technologies have evolved.

One of the most important requirements of Web applications, especially B2B e- commerce applications, is the ability to interchange data in a standard format that can be understood by any hardware and software platform. Enterprises having similar business interests may need to share data, which may be stored on disparate platforms. This need for a common interface for exchanging data resulted in the evolution of Extensible Markup Language (XML), which is the latest and the most hyped Web technology.

What is XML? How does it allow data interchange in Web applications? These are the questions that need to be answered before you look at its use in ASP.NET. In this chapter, you will learn about XML and its related specifications. You will also learn to use XML documents in ASP.NET.

Introduction to XML

XML is the World Wide Web Consortium's (W3C) specification for interchanging structured data in Web applications. An XML document enables you to store data in the same way a database enables you to store data. However, unlike databases, an XML document stores data in the form of plain text, which can be understood by any type of device, whether it is a mainframe computer, a palmtop, or a cell phone. Thus, XML serves as a standard interface required for interchanging data between various Web applications.

Note W3C (www.w3c.org) is a consortium that ensures the growth of the Web by developing common protocols for the Web. It also ensures that various Web technologies are interoperable. W3C has more than 500 organizations as its members.

XML is a markup language that enables you to enclose data within tags. So how is it different from HTML? The difference lies in the fact that HTML has a set of predefined elements that concentrate on the appearance of the contents within the document. For example, when you enclose the data within the <I> and </I> tags, the browser interprets these tags and displays the content enclosed within the tags in italics. The browser is not concerned about the contents within the tags.

Conversely, XML concentrates on the content in the document and is not concerned with how the contents should appear. For example, if you are creating a document that stores the data about the products offered by your company, you can create a tag called <ProductDescription> and enclose the description of a product within this tag. Thus, tags in XML serve the purpose of structuring the content within the XML document. No presentation or appearance is associated with any of the XML tags. XML does not provide any predefined set of tags. Rather, it enables you to create your own tags. In that sense, XML can be called a meta-markup language, which enables you to create your own markup or vocabulary. In fact, many existing markup languages have been derived from XML. Some examples of markup languages that are based on XML are Wireless Markup Language (WML), which is used to create Web applications that can be accessed using a cell phone, and MathML, which is used to represent mathematical equations.

An example will help you to understand the difference between XML and HTML. Consider the following HTML document that displays a list of items and their prices:

Соседние файлы в папке c#