Anda di halaman 1dari 8

TechLab 70-528VB-E01 Data-binding Server Controls 2.

0 Hours

Lab Information
TechLab Author(s): Sean Holmes
Revision Date: 5/25/2010
Feedback: All comments and suggestions should be submitted via the feedback system, which can
be accessed from Course Materials on the StudentWeb

Prerequisites
Students should be familiar with the fundamentals of ASP.NET technologies, Visual Basic .NET programming,
and SQL Server 2005.

Knowledge Goal
The various methods of data-binding ASP.NET Server controls.

Exam Correlation
1.0 Creating and Programming a Web Application
1.2 Add and configure Web server controls
2.0 Integrating Data in a Web Application by Using ADO.NET, XML, and Data-Bound Controls
2.1 Implement data-bound controls

Lab Setup Requirements

Windows XP Professional Client

Setup Requirements:
Software: Visual Studio 2005 Professional or higher
Software: SQL Server 2005 Express Edition or higher with the Adventure Works
sample database installed.
VPC Image Name
Visual Studio 2005

Reference
• MCTS Self-Paced Training Kit (Exam 70-528): Microsoft .NET Framework 2.0 Web-Based Client
Development, MSPRESS, Chapter 3.
• StudentWeb My Personal Bookshelf, Keyword: ASP.NET 2.0, data-bound controls

Copyright © 2007, TechSkills LLC Page 1 of 8


Lab # 70-528VB-E01 Data-binding Server Controls

Lab Overview

ASP.NET 2.0 contains very powerful data access controls that allow comprehensive data binding and manipulation with
little or no coding. The data access model of ASP.NET 2.0 allows for a no-code solution for the most common data
scenarios, such as:

• Querying and displaying data within numerous control types

• Sorting, paging and caching data

• Updating, Adding and Modifying data

• Filtering data using parameterized queries

ASP.NET 2.0 contains two categories of server controls that allow this simplistic data binding functionality; Data Source
and Data-bound controls. In addition to binding to traditional data sources like a database, controls can be easily be
bound to other data access storage providers like XML files and Business Objects.

Data Source Controls

The new data source controls in ASP.NET 2.0 are the SqlDataSource, ObjectDataSource, XmlDataSource,
AccessDataSource, and SiteMapDataSource. According to Microsoft, they all can be used to retrieve data from their
respective types of data sources and can be bound to various data-bound controls. These data source controls simplify
the amount of custom code that needs to be written to retrieve and bind data, and even to sort, page through, or edit data.
Each data source control has similar properties that allow it to interact with its respective data source. The
SiteMapDataSource and the XmlDataSource are built to retrieve hierarchical data while the other data source controls are
a built to retrieve set-based data with columns and rows.
The AccessDataSource is built specifically to retrieve data from Access databases. The SqlDataSource may sound like it
works only with SQL Server™, but that's not the case. It can actually be used to retrieve data from any OLE DB or ODBC-
compliant data source. The table below provides a brief description of each data source control.

Data Source Control Description

SqlDataSource Enables binding to a SQL database represented by an ADO.NET provider,


such as Microsoft™ SQL Server, OLEDB, ODBC, or Oracle.

ObjectDataSource Enables binding to a middle-tier object such as a data access layer or


business component.

AccessDataSource Enables binding to a Microsoft™ Access database.

SiteMapDataSource Enables binding to the hierarchy exposed by an ASP.NET 2.0 site


navigation provider.

XmlDataSource Enables binding to an XML file or document.

Data-bound Controls

Data-bound controls are UI controls that render data as HTML to the requesting client device or browser. A data-bound
control can auto-bind to data exposed from a data source and will fetch data at the appropriate time in the page request
lifecycle. These controls can optionally take advantage of data source capabilities such as sorting, paging, filtering,
updating, deleting, and inserting. A data-bound control connects to a data source control through its DataSourceID
property. Other controls, such as the DropDownList, can also be bound to the data source controls. For example, a
DropDownList control can be bound to a SqlDataSource control that retrieves a list of employees. The employee's full
name could be displayed in the DropDownList while the EmployeeID could be bound to the control as its underlying data
value field. ASP.NET 2.0 contains several new data-bound controls that are outlined in the table below:

Copyright © 2007, TechSkills LLC Page 2 of 8


Lab # 70-528VB-E01 Data-binding Server Controls

Data-bound Control Description

GridView Presents data in a traditional grid format. A GridView can automatically


utilize data source controls to data bind, manipulate, and format data
without any coding. Coding is required to perform more complex business
scenarios.

DetailsView Presents a single data item in a table of label/value pairs. A DetailsView


control, just like a GridView, requires no coding to take advantage of data
source control data binding.

FormView Presents a single record at a time from its associated data source,
optionally providing paging buttons to navigate between records. It is
similar to the DetailsView control, except that it requires the user to define
the rendering of each item using templates, instead of using data control
fields.

TreeView Enables binding to a hierarchical data source exposed by an ASP.NET 2.0


site navigation provider or an XML file.

Menu Enables binding to an XML file or document.

The following lab exercises will cover simple data-binding using the data source controls in conjunction with data-binding
controls. In addition, we will explore the use of the TreeView and FormView controls.

Scenario

You are creating a Web Form that will display data from the AdventureWorks SQL Server 2005 database. The Web Form
allows users to select a Contact Name from a DropDownList control. A SqlDataSource control should be used to retrieve
the data. You set the SelectQuery property of the SqlDataSource control by using the following code segment.

SELECT [ContactID],[FirstName]+ ' '+ [LastName] As Contact


FROM [AdventureWorks].[Person].[Contact]
ORDER BY [LastName]

You need to bind the DropDownList control to the data source control so that the Contact is displayed to the user. The
ContactID of the Contact must be stored as the user's selected item.

You also need to incorporate the use of a FormView control to allow users to edit and update data. When the user clicks
the Update button on the FormView control, the application must validate that the user has entered data in all of the fields.
You need to ensure that the Web Form does not update if the user has not entered data in all of the fields.

Step-by-Step Instructions
Exercise 1

1) Create a new Web Site


a. Open Visual Studio 2005 and create a new Web Site by clicking File NewWeb Site
b. Select the ASP.NET Web Site and ensure that the Language drop down is selected to Visual Basic.
c. Press OK

2) Create the SQLDataSource Control


a. Change the view for the page Default.aspx to Design.

Copyright © 2007, TechSkills LLC Page 3 of 8


Lab # 70-528VB-E01 Data-binding Server Controls

b. In the Toolbox, expand the Data section.

c. Drag a SqlDataSource control onto Default.aspx. You should see the control on your page now.

d. Click the “Configure Data Source” link to open the Configure Data Source Wizard.
e. Click the “New Connection…” button to create a new connection object. This embedded object is used to
determine which physical data source to connect to. A single data source control can only have one static
connection in place using the wizard. However, with the use of code, you can dynamically setup the
connection object as needed. This is one limitation of using the wizard type.
f. In the “Choose Data Source” dialog window select “Microsoft SQL Server” as the Data Source. Select “.Net
Framework Data Provider for SQL Server” in the Data provider drop down. This is the preferred data provider
for connecting to Microsoft SQL Server. Press Continue.

g. In the Add Connection dialog window, select your SQL Server name, the proper security credentials, and the
AdventureWorks database. Press the “Test Connection” button to test your settings. Press OK when this is

Copyright © 2007, TechSkills LLC Page 4 of 8


Lab # 70-528VB-E01 Data-binding Server Controls

properly setup.

h. Now you should be back to the “Choose your Data Connection” screen of the wizard. Press the Next button.
Save the connection string if the wizard asks you to and Press Next.
i. Choose the “Specify a custom SQL statement or stored procedure” option and press Next. We are writing a
custom SELECT statement because our scenario requires the FirstName and LastName columns to be
concatenated into one column. In the SELECT tab type the following SQL statement:

SELECT [ContactID],[FirstName]+ ' '+ [LastName] As Contact


FROM [AdventureWorks].[Person].[Contact]
ORDER BY [LastName]
We do not need an UPDATE, INSERT, or DELETE statements so let’s ignore those tabs. Press Next.
j. The next screen allows you to test your query. Do so and press Finish to complete the Data Source control
configuration.

3) Create a Data-bound Dropdown control


a. Expand the Standard section in the Toolbox. Drag a DropdownList control onto the Default.asp page.
b. Click the “Choose Data Source…” link in the DropDownList Task Smart Tag.

c. In the next screen, select the appropriate data source, data display, and data value options from the drop
downs. Press Ok when complete. That’s it! We now have a data-bound DropDownList control. If you could not
get through this step please read the next step.
d. Run the project and test functionality.
Let’s examine the properties needed for a list control to be officially data-bound. Open the Properties window
and click on the DropDownList. The properties we are concerned with are DataSourceID, DataTextField, and

Copyright © 2007, TechSkills LLC Page 5 of 8


Lab # 70-528VB-E01 Data-binding Server Controls

DataValueField. These three properties are the minimum requirements for data-binding a list control.

DataSourceID is the essentially the data source control used. If you have multiple data source controls on
your page they will be available in the DataSourceID drop down list. DataTextField is what the control will
display after it pulls the data from the data source. DataValueField is the underlying value of the selected
item in the list control.

Exercise 2

1) Create a new SQLDataSource Control and data-bound FormView


a. Create a new SQLDataSource. This time use the “Specify columns from table or view” option. Select the
Contacts table and check the ContactID, FirstName, LastName, EmailAddress, and Phone columns. Also
click the “Advanced” button and check the box to generate UPDATE, INSERT, and DELETE statements and
to check for concurrency. Press Next.
b. At this step you will see another limitation of the wizard. Try to test the query. More than likely it will fail with
an error that states the object Contact is invalid. The AdventureWorks database heavily utilizes schemas with
the tables which forces you to call the tables by schema.tablename format. We will need to fix this manually.
Press the Finish button.
c. View the properties within the Properties Window of the SqlDataSource2 control. We need to change the
SelectQuery, InsertQuery, DeleteQuery, and UpdateQuery properties to contain the proper table name call.
When you click on the elipse “…” button in the SelectQuery Property, a window appears that allows you to
edit the query. Change the query to the following:
SELECT [ContactID], [FirstName], [LastName], [EmailAddress], [Phone] FROM Person.Contact

We add the schema and remove the brackets. Now do this for the InsertQuery, DeleteQuery, and
UpdateQuery properties.
d. Next add a FormView control to the page and data bind it to the new SQL Data source. Check the “Enable
Paging” to allow automatic record navigation options to appear. Also click on the “Edit Templates” link.

e. There are templates for each action that the control provides. Basically it is a view of the control when it
enters different states. Once you select a template, you can edit the way the control looks when it does enter
the state. For example, select the EditItemTemplate and notice that the Update and Cancel links appear.
Make the control a little bigger by stretching its borders and then enlarge the Email Address Textbox. Click on
the other templates in the list to see what each represents. When you are done click on the “End Template
Editing” link.
f. Now run the project and test the functionality of the FormView control.

2) Adding Validation to the FormView Control


a. The scenario requires us to add validation functionality to the FormView control. Basically a user cannot leave
blank fields during an update into the database. To meet this requirement we need to add code to a certain
event of the FormView control.

Copyright © 2007, TechSkills LLC Page 6 of 8


Lab # 70-528VB-E01 Data-binding Server Controls

b. Open the Events window by clicking the lightning bolt icon on the Properties window. Locate the ItemUpdating
event and double click in the empty space to the right of it. This will take us to the event method so we can
add our validation code.
The ItemUpdating event fires right before the Update statement is executed.
c. Add the following code to the ItemUpdating event method:

Dim entry As DictionaryEntry


For Each entry In e.NewValues
If entry.Value.Equals("") Then
e.Cancel = True
Return
End If
Next entry
End Sub
This code uses a DictionaryEntry object to store each FormView value that are to be updated. The “e.NewValues”
represents the entire Dictionary collection of the values. Basically, the code loops through all values and if any
value is equal to nothing then the event is canceled (e.Cancel).

From this exercise we can see how easy it is to set up web based data manipulation with no code. In addition, we
learned how to add extra functionality with code to compensate for the lack of validation.
Bonus Exercise 3

3) Using the TreeView Control for Site Navigation


a. Data binding a TreeView control to a Site Map XML file provides a no-code solution for site navigation.
b. Add two new WebForms to your project. You can leave them named Default2 and Default3. Also add a Site
Map file.
c. Open the Site Map file and copy the following XML between the root <siteMap> nodes.

<siteMapNode url="~\default.aspx" title="Home" description="Site Home Page">


<siteMapNode url="default2.aspx" title="Sales" description="Sales Home">
<siteMapNode url="default3.aspx" title="West Region" description="Sales for the West Region" />
</siteMapNode>
</siteMapNode>
d. Open the Default.aspx page in design view. Add a SiteMapDataSource Control to the form. This control
automatically data binds to the Web.sitemap file in our project.
e. Set the StartingNodeUrl Property to”~/Default.aspx”. This in conjunction with the ShowStartingNode = True
property will set the root node navigation to the home page; Default.aspx.
f. Next, drag a TreeView control onto the page. Set the data source to SiteMapDataSource1. Click the “Edit
Tree Databindings” link to set how the TreeView control will behave. Add the SiteMapeNode from the
“Available data bindings” section. When you select the SiteMapNode, you should see the list of properties on
the right side.
g. Change the NavigateUrlField property to “Url”. Change the TextField property to “Title”. Change the
ValueField property to “Description”. These properties are actually pulling values from the Site Map file. Url,
Title, and Description are three attributes of <siteMapNode> XML Nodes. Press Ok and run the project.
You should now see the following tree view.

This was a simple exercise on how to leverage a Site Map file and a TreeView Control. The TreeView control
contains a number of nifty and easy to use features. As extra practice take a few minutes to explore all what you
can do with the control. Use the MSDN help system to help with your research.

Copyright © 2007, TechSkills LLC Page 7 of 8


Lab # 70-528VB-E01 Data-binding Server Controls

Evaluation
Summarize, in your own words what you accomplished in this lab, what challenges you had to overcome and what you
learned?

Assessment
To provide assessment for this lab, answer the following questions for evaluation by your Instructor.

1) A SQLDataSource control is only used for Microsoft SQL Server. True or False?

_____________________________________________________________

2) What three Properties are needed to data bind a DropDownList control

_____________________________________________________________

3) What are the 3 basic steps to incorporate a TreeView control for use with a Site Map file?

_____________________________________________________________

4) Does the FormView Control contain a no-code solution for validation controls? Yes or No

_____________________________________________________________

After lab completion, please validate this lab and check your answers with an Instructor.

Copyright © 2007, TechSkills LLC Page 8 of 8

Anda mungkin juga menyukai