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

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

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

37.EstablishConnection())

38.Dim dsObj As New DataSet()

39.

CmdObj.Fill(dsObj, "DISPLAYDATA")

Return dsObj.

40.Tables(0).DefaultView

41.End Function

End Class

This class establishes a connection with the database server and also uses DataSet and DataView objects. Therefore, you must import the System.Data and System.Data.SQLClient namespaces. The DataAccessObj class contains two data members:

§sConnectionStr: Used for storing connection information such as the server name, database to be used, and the username and password to be used for establishing a connection with the database server.

§SQryStr: Used for storing the query to be sent to the database server.

Next, you write the property procedures for returning and setting sConnectionStr and sQryStr.

In addition to the property procedures, the DataAccessObj class also includes the EstablishConnection() method for establishing a connection with the database server by using the connection string stored in sConnectionStr. This function returns an object of the type SQLConnection.

Finally, the class has the GetData() method, which sends the command stored in sQryStr to the database server by using the connection object returned by the EstablishConnection() method. The GetData() method fills a DataSet object with the data returned by the database server and returns an object of type DataView.

Compile the DataAccessObj class by selecting Build Build. Alternatively, you can compile the class from the MS-DOS command prompt by giving the following statement:

vbc /t:library /out:dataaccess.dll GetData.vb /r:System.dll

/r:System.Data.dll /r:System.XML.dll

This statement is similar to the statement we used earlier to compile the UI-centric data component. The /r option in the statement specifies the additional libraries to be used for compiling the application. The statement creates the Dataaccess.dll file, which can be included in projects to access the functions written in the DataAccessObj class.

Using business objects

In the previous section, you were introduced to the process of creating business objects. In this section, you will learn to use the business objects in an application with the help of an example. You will create an application, which will display a list of product IDs from the Products table in a DropDownList control. When a user selects a product ID from the DropDownList, the details about the product should be displayed along with the net amount payable on the product. The application should use the DataAccessObj and CalcNetAmt business objects created earlier for fetching the required data from the SQL Server and for calculating the net amount payable. For using these business objects in your application, follow these steps:

1.Create a new Web application by clicking the File New Project option. Select Visual Basic Projects from the Project types list box. Select ASP.NET Web Application from the Templates list box. Name the project UseBusinessObj.

2.Create a DropDownList control in the Design view of the Web Form and set the properties of the control as given in Table 15-1.

Table 15-1: DropDownList control properties

Property

 

Value

 

 

 

ID

 

LstProductId

 

 

 

DataTextField

 

ProductID

 

Table 15-1: DropDownList control properties

 

 

 

 

 

 

 

 

 

Property

 

Value

 

 

 

 

 

 

 

DataValueField

 

ProductID

 

 

 

 

 

 

 

AutoPostBack

 

True

 

 

 

 

 

 

3.Create Label controls for displaying the name and the unit price of a product. Specify the ID of these Label controls as LblProductName and LblUnitPrice. Also create an additional Label control for displaying the net amount payable on the product. Specify the ID of this Label control as LblNetAmt.

4.To use the CalcNetAmt and DataAccessObj business objects, you must add a reference to them in the project. Right-click the References tree in the Solution Explorer and select Add Reference from the popup menu. This invokes the Add Reference dialog box, shown in Figure 15-1.

Figure 15-1: The Add Reference dialog box

Click the Browse button to invoke the Select Component dialog box. Locate the folder where you created the CalcNetAmt component. Select CalcNetAmt.dll and click Open. The Select Component dialog box closes and the control returns to the Add Reference dialog box. Notice that the dll file that you selected appears in the Selected Components list view. Add a reference for the GetData.dll file in a similar way.

5.Import the required namespaces by adding the following statements in the WebForm1.aspx file:

6.<%@ Import Namespace=System.Data %>

<%@ Import Namespace=System.Data.SqlClient %>

7.Create an instance of each business object by writing the following code in the Page_Load() method of theWeb Form:

8.Dim NetAmtObj As New CalcNetAmt.CalcNetAmt()

9.Dim daObj As New GetData.DataAccessObj()

Note

You can write this code in the Page_Load() method in the VB file

corresponding to the Web application instead of including it in the

 

 

Page_Load() method of the ASPX file. If the VB file corresponding to

 

the Web application is not visible in the Solution Explorer window, click

the Display All Files icon to display the listing of all files included in the project.

10.Set the connection string and the SQL query string of the DataAccessObj instance by typing the following statements:

11.daObj.sConnection="Server=localhost;uid=sa;pwd=;

12.database=NorthWind"

13.

14.daObj.sQry= "Select ProductID, ProductName, UnitPrice

from Products"

15.If the user is visiting the Web page for the first time, the DropDownList control needs to be populated with the product IDs existing in the Products table. This can be done by invoking the GetData() method of DataAccessObj. This method returns an object of type DataView after executing the query. Set the DataSource property of the DropDownList control to the DataView object returned by the GetData() method by using the following code:

16.If not IsPostBack then

17.'Set the DataSource property of the LstProductID

18.'DropDownList to the DataView object returned by the

19.'GetData() method of DataAccessObj

20.LstProductID.datasource=daObj.DisplayData()

21.

22. 'Bind the data in the DataView to the DropDownList

LstProductID.DataBind()

23.When a user selects an item from the DropDownList control, the AutoPostBack property of the control causes the Web page to be reloaded. At this point, you need to display the details relating to the products in the respective Label controls. This can be done by using the following code:

24.If not IsPostBack then

25.:

26.:

27.Else

28.'create a dataview object

29.Dim dvProducts1 as new DataView()

30.

31.'Call the DisplayData() method of DataAccessObj to

32.'return product details and store the resulting

33.'DataView object in dvProducts1

34.dvProducts1 = daObj.DisplayData()

35.

36.'Set the RowFilter property of the dvProducts1

37.'DataView to the product ID selected from the

38.'DropDownList. This will result in displaying only the

39.'details about the selected product

40.dvProducts1.RowFilter = "ProductId='" + LstProductID.

41.SelectedItem.Text + "'"

42.

43.'Store the details of the selected row from the DataView

44.'into the myrow DataRow object

45.dim myrow as DataRow

46.myrow = dvProducts1.Table.Rows(LstProductID.SelectedIndex)

48.'Set the text of Label controls to the values of 'respective columns

49.LblProductName.Text =

myRow(dvProducts1.Table.Columns(1)).ToString

50. LblUnitPrice.Text =

myRow(dvProducts1.Table.Columns(2)).ToString

51.

52.'Invoke the CalcAmt() method of the CalcNetAmt object to

53.'calculate the net amount payable on the product

54.LblNetAmt.Text = NetAmtObj.CalcAmt(CDbl(lblUnitPrice.Text))

.ToStringEnd If

This code will result in populating the Label controls when you select a product ID from the DropDownList control. The explanation for each line of code is included in the comments inserted in the code. The complete code in the Page_Load() method of the Web Form will look as follows:

<script language=vb runat="server">

sub Page_Load(Sender as Object, e as EventArgs)

Dim NetAmtObj As New CalcNetAmt.CalcNetAmt()

Dim daObj As New GetData.DataAccessObj()

daObj.sConnection =

"Server=localhost;uid=sa;pwd=;database=NorthWind"

daObj.sQry = "Select ProductID, ProductName,

UnitPrice from Products"

If Not IsPostBack Then

LstProductID.DataSource = daObj.DisplayData

LstProductID.DataBind()

Else

Dim myrow As DataRow

Dim dvProducts1 As New DataView()

dvProducts1 = daObj.DisplayData

dvProducts1.RowFilter = "ProductId='" +

LstProductID.SelectedItem.Text + "'"

myrow =

dvProducts1.Table.Rows(LstProductID.SelectedIndex)

LblProductName.Text =

myrow(dvProducts1.Table.Columns(1).ToString)

lblUnitPrice.Text =

myrow(dvProducts1.Table.Columns(2).ToString)

LblNetAmt.Text =

NetAmtObj.CalcAmt(CDbl(lblUnitPrice.Text)).ToString

End If

End Sub

</script>

LblProductName, LblUnitPrice, and LblNetAmt are not Textboxes. They are labels that are being used to display the values retrieved from the database.

55.Run the application by pressing Ctrl + F5. Sample output of the application is shown in Figure 15-2.

Figure 15-2: Output of the application implementing business objects

Creating a data access component by using Data controls of ASP.NET

ASP.NET provides you with Data controls that enable you to create data-centric business rule objects in an easier way without having to type the code manually. In this section, you will look at the process of creating a simple data-centric business rule object by using the Data controls provided in ASP.NET. This object will be responsible for establishing a connection with the database and returning all necessary data.

Creating a data access component

To create a data-centric business object by using Data controls, follow the steps given as follows:

1.Select File New Project. In the Project Types list box, select Visual Basic Projects. In the Templates list box, select ASP.NET Web application. Change the name of the application to DataAccessComp and click OK.

2.Select Project Add Component to open the Add New Item dialog box. In the dialog box, change the name of the file to DataAccess.vb.

3.To create a component by using the Data controls available in ASP.NET, click the Data tab on the Toolbox. The Data tab expands to display the Data controls. Point to the OleDbDataAdapter control

and drag it to the component designer. The OleDbDataAdapter control enables you to create an instance of the OleDbDataAdapter classm, which represents a set of SQL statements and connection

information required for getting the data from the database. It also enables you to fill a data set with the data returned by the SQL statement.

4. When you drag the OleDbDataAdapter control to the component designer, it invokes the Data Adapter Configuration Wizard, shown in Figure 15-3.

Figure 15-3: Data Adapter Configuration Wizard

This wizard guides you through various steps for establishing a connection with the database. The first step in this wizard enables you to choose the database connection. Select the name of the data server and the database from the drop-down list. If the name of the desired server does not exist in the drop-down list, click the New Connection button to open the Data Link Properties dialog box, shown in Figure 15-4.

Figure 15-4: The Data Link Properties dialog box

Select the Connection tab. Specify the data server name and the logon information for connecting to the data server. Select the NorthWind database. Click the Test Connection button to ensure that the connection to the database server is successfully established. Click the OK button to close the Data Link Properties dialog box and return to the Data Adapter Configuration Wizard.

5. The next step of the Data Adapter Configuration Wizard enables you to specify the query type for fetching the required data. This step provides three options, as shown in Figure 15-5: Use SQL Statements; Create New Stored Procedures; and Use Existing Stored Procedures.

Figure 15-5: Choose a Query Type window

Select the Use SQL Statements radio button and click the Next button.

6. The next step of the Data Adapter Configuration Wizard enables you to generate the SQL statement to be used for fetching the data. You can type the SQL statement in the text area provided to you or generate it visually by clicking the SQL Builder button. Type the following SQL statement in the text area:

7.SELECT

8.Orders.OrderID,

9.Customers.CustomerID,

10.Customers.CompanyName,

11.Products.ProductName,

12.Products.UnitPrice,

13.[Order Details].Quantity

14.FROM

15.Customers INNER

16.JOIN

17.Orders ON

18.Customers.CustomerID = Orders.CustomerID

19.INNER JOIN [Order Details]

20.ON Orders.OrderID = [Order Details].OrderID

21.INNER JOIN Products

22.ON [Order Details].ProductID = Products.

ProductID

This step finishes the process of creating the OleDbDataAdapter control. Click the Finish button to close the Data Adapter Configuration Wizard dialog box. At the end of this process, you will see two new objects, OleDbDataAdapter1 and OleDbConnection1, added to the component tray, as shown in Figure 15- 6.

Figure 15-6: Component tray after adding the adoDataSetCommand1 and adoConnection1 objects

23.The next step is to create the DataSet class for storing the data returned by the SQL statement. For this, right-click the empty area in the component designer and select the Generate Dataset option. This results in invoking the Generate Dataset dialog box, shown in Figure 15-7.

Figure 15-7: Generate Dataset dialog box

Enter the name of the DataSet class as OrderDataSet and click the OK button. This results in generating the OrderDataSet.xsd file. The file is included in the Solution Explorer window. This file contains the XML schema

CrossReference

definition for the resulting DataSet. Components in .NET use XML for ensuring interoperability. The XSD file defines the structure of the data in the OrderDataSet object. In addition to the XSD file, the Generate Dataset option also generates the methods required for filling and updating the OrderDataSet class. The OrderDataSet class can now be used in the Web Form.

For information on XML and XML schemas, refer to Chapter 13.

Using the data access component in a Web Form

You will now look at using the OrderDataSet class and the DataAccess class in a Web Form. You will create a DropDownList control in the Web Form to display all order IDs. When a user selects an order ID, the details about the order ID should displayed in a DataGrid control.

1. To use the OrderDataSet class in a Web Form, you need to create an instance of the OrderDataSet class. Select the DataSet control from the Data tab of the Toolbox and drag it to the Web Form. This invokes the Add DataSet dialog box, shown in Figure 15-8.

Figure 15-8: Add DataSet dialog box

This dialog box has two radio buttons, Typed Dataset and Untyped Dataset. The Typed Dataset option enables you to create a data set based on an XML schema definition. You can use the Untyped Dataset option if you do not have an XML schema definition. In this example, you have already generated the XML schema called OrderDataSet.xsd. Therefore, select the Typed Dataset option. In the drop-down list box, locate the name of the OrderDataSet class, which appears with the prefix of your project name. For example, if your project name is DataAccessComp, the class appears in the drop-down list as DataAccessComp.OrderDataSet. Selecting the OrderDataSet class and clicking the OK button results in the creation of an instance of the OrderDataSet class. This object has the name OrderDataSet1.

2. The OrderDataSet1 object needs to be filled with the required data by using the connection information and the SQL statement stored in the OleDbDataAdapter and OleDbConnection objects. To achieve this functionality, create an instance of the DataAccess component in the Page_Load() event of the Web application as follows:

Dim ordercomponent as new DataAccess()

This statement creates an instance of the DataAccess class in which you created the OleDbDataAdapter1 and OleDbConnection1 objects and generated the functions for filling the OrderDataSet.

3.Invoke the Fill() method of the OleDbDataAdapter object in the Page_Load() method of the Web Form, as follows:

4.If Not IsPostback Then

5.ordercomponent.OleDbDataAdapter1.Fill(OrderDataSet1)

6.End If

7.After filling the DataSet, the next step is to create a DataView object. You can create a DataView object by using the DataView control

provided in ASP.NET. Click the Data tab on the Toolbox. Click and drag the DataView control to the Web Form. This will create a DataView object called DataView1. You can change the name of this object by using the Properties window. Press F4 to switch to the properties window and change the ID of the DataView object to OrderDataView1. Change the Table property of the DataView object to OrderDataSet1.customers.

8. The DataView object created in the previous step can now be used to populate controls in the Web Form. Create a DropDownList control on the Web Form. Set the properties of the control as shown in Table 15-2.

Table 15-2: DropDownList control properties

Property

 

Value

 

 

 

ID

 

LstOrderId

 

 

 

DataTextField

 

OrderID

 

 

 

DataValueField

 

OrderID

 

 

 

AutoPostBack

 

True

 

 

 

DataSource

 

OrderDataView1

9.Modify the Page_Load() method of the Web Form to include instructions for binding the order ID to the DropDownList control as follows:

10.If Not IsPostback Then

11.ordercomponent.OleDbDataAdapter1.Fill(OrderDataSet1)

12.LstOrderId.DataBind()

End If

13.Now, you need to add the functionality for displaying the details of an order when a user selects a particular order ID from the DropDownList. For this purpose, create another DataView object by clicking and dragging the DataView control from the Data tab of the Toolbox to the Web Form. Set the ID property of the DataView control to OrderDataView2 and the Tables property to OrderDataSet1.customers.

14.Create a DataGrid control on the Web Form for displaying the details of the selected order ID. Set ID of the DataGrid control to dgOrderData.

15.Click the Property Builder link in the Properties window of the DataGrid. This will invoke the dgOrderData Properties dialog box, shown in Figure 15-9.

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