Accessing and Updating Data in ASP.NET 2.0: Data Source Control Basics
By Scott Mitchell
A Multipart Series on ASP.NET 2.0's Data Source Controls
ASP.NET 2.0 introduced a number of new Web controls designed for accessing and modifying data.
These controls allow page developers to declaratively access and modify data without writing any
code to perform the data access. This article is one in a series of articles on ASP.NET 2.0's new data
source controls.
Data Source Control Basics - explores the concepts
and advantages of data source controls, and compares their usage in ASP.NET 2.0 to data access techniques in ASP.NET 1.x.
Accessing Database Data - shows how to use the
SqlDataSource and AccessDataSource controls to query data from a relational database.
Filtering Database Data with Parameters - learn how to
retrieve just a subset of database data based on hard-coded values and values from the querystring, other Web controls on the page,
session variables, and so on.
Creating Custom Parameter Controls - learn how
to create your own custom, declarative Parameter controls for use in the data source controls' parameters collections.
Inserting Data - learn how to insert data using
a SqlDataSource control. Also examines how to retrieve the IDENTITY column value for the just-inserted record.
Deleting Data - see how to delete data using
a SqlDataSource control. Also looks at how to programmatically cancel a delete.
Updating Basics - learn the basics of updating database data using a
SqlDataSource control. Also examines using the GridView to provide a web-based editing interface.
Customizing the Editing Interface - see how to
customize the GridView's columns to provide a customized editing interface that includes input validation and alternative
user interface elements.
Handling Database NULL Valuese - explore how to
extend the GridView's customized editing interface to handle database NULL values.
Using Optimistic Concurrency - see how to prevent
concurrent users from overwritting one anothers changes by using concurrency control.
Introduction
When I started my career as a web developer, Microsoft's Active Server Pages version 2.0 had just burst onto the scenes
(classic ASP, mind you, not .NET).
Back in my day, web developers were responsible for writing code to both access and display data. That is, we had to write
code that queried the database and then had to write more code to squirt out the appropriate data surrounded by the
applicable HTML elements. ASP.NET version 1.x simplified this process
with the host of data Web controls (the DataGrid, DataList, Repeater, DropDownList, and so on). With just two lines of code
these controls could emit their own, proper HTML elements when given an arbitrary data source. Today, with
ASP.NET version 2.0 and its data source controls, developers can both
access data and display it without writing a lick of code. You kids have it so easy these days!
In a nutshell, the ASP.NET 2.0 data source controls provide a declarative way to work with data. Rather than having to
write code to connect to a database, issue a command, and retrieve the results as a DataReader or DataSet, with the
data source controls these instructions can be specified through the standard Web control syntax. (Of course behind the scenes, the
data source controls are still performing the programmatic steps we had to take in ASP.NET 1.x.) Once a data source control
has been properly configured, it can be bound to any data Web control. When the page is visited, the data Web control
will automatically invoke the associated data source control, retrieve its data, and display it as configured.
While the data source controls are easy to get started with, there are a number of subtleties and issues that can cause
headaches. In this article series we'll examine the five built-in data source controls in detail. This first part, however,
examines the concepts shared among all five data source controls and how ASP.NET 2.0's data Web controls work with their
associated data source controls at runtime. Read on to learn more!
You can still access and modify data in an ASP.NET 2.0 application using the same techniques used in ASP.NET version 1.x.
That is, you can still programmatically access data using the familiar SqlConnection, SqlCommand,
and SqlDataReader classes, and bind those results to the data Web controls through their DataSource
properties. The data source controls merely provide a declarative, more efficient means for working with data.
The Benefits of the Data Source Controls
One of ASP.NET version 1.x's biggest improvements over its precursor, classic ASP, was the data Web controls had the ability to
render HTML markup from an arbitrary data source without having to write a lick of code. This enhancement introduced two
advantages: it saved having to write a lot of code and markup, and required less domain expertise from developers. When emitting
data to a web page with classic ASP, page developers needed to write code to iterate through the database results and display
not only the contents of the current record, but also the HTML that accompanied the record.
For example, to display the results
of a database query in an HTML <table>, a classic ASP developer would have to first retrieve the data,
then emit the starting <table> tag, followed by a loop that enumerated the records in the RecordSet. For
each database record, a table row (<tr>) would be emitted, and for each field in that database record
a table column (<td>). Finally, after exhausting the data, a closing table tag would complete the code.
If you've never had to write classic ASP code consider yourself lucky - it was inherently messy, especially when applying
more involved formatting, such as having alternating row colors or formatting cells based on various conditions. The data
Web control model in ASP.NET 1.x removed the expanse of code needed to be written.
In addition to reducing the sheer volume of code needed, the data Web controls also remove the domain expertise needed
with simpler technologies like classic ASP. For example, with classic ASP the page developer needed to know the precise syntax
and semantics of the HTML <table> element. An ASP.NET developer using a
DataGrid, however, really doesn't need to know
squat about the HTML syntax for displaying a table (although such knowledge is definitely helpful).
Likewise, with the DropDownList controla page developer can simply bind database results to the control and not concern
himself with the <select> and <option> elements needed.
The ASP.NET 1.x data Web controls provided a consistent pattern for displaying data, even though the various controls rendered
the data differently. Despite the fact that a DataGrid displayed its data in a grid, and the DropDownList control in a drop-down
list, the code needed to bind the data to the two data Web controls is identical. Merely set the control's DataSource
property to the retrieved data and then call the control's DataBind() method.
The advantages of displaying data in a web page using data Web controls carry over to accessing data. In ASP.NET 1.x working
with data requires writing repetitive code and a fair amount of domain expertise. While libraries like the
Data Access Application Block help abstract
away the repetition, and utilizing a well-designed application architecture helps reduce the required domain knowledge for
the website's implementors, the data access techniques in ASP.NET 1.x still feel much like displaying data in classic ASP
applications.
The data source controls in ASP.NET 2.0 were introduced to bring the advantages from the data display side over to the data
access side as well. Data source controls provide for a page developer to access and modify data without needing to write a
lick of code, thereby greatly reducing the code repetition seen in ASP.NET 1.x. Furthermore, ASP.NET 2.0 provides five different
data source controls, each designed for accessing a different type of data. The SqlDataSource control, for example, is used
to access data from a relational database, whereas the XmlDataSource can work with data from an XML file. Regardless of the
data source control being used, they are plugged into the data Web controls in the same manner. This reduces the domain
knowledge needed for working with different types of data. You no longer need to know the specifics for connecting to a
Microsoft SQL Server 2000 database, or the precise code for accessing and filtering the contents of an XML file. This information
is abstracted away by the data source control.
The Loss of Required Domain Expertise - Good or Bad?
The ASP.NET 2.0 data Web controls and data source controls allow for page developers to build data-driven web applications without
having to know the ins and outs. The data Web controls squirrel away the need to know the specifics of HTML, whereas the
data source controls reduce the required knowledge for connecting, querying, and working with database results. On one hand
this is a good things as it opens the development space to those who might not have a web-based background. Furthermore, it
allows for projects to be turned around quicker, since the developers need not focus their time and energy researching what
are now becoming esoteric topics.
However, anytime a new layer of abstraction is added on top of another, it permits developers to forgo education on the lower
layers of abstraction. And this works well until something goes awry, and one layer of abstraction "leaks" into another.
At this point developers only familiar with the data source controls and not their underlying architecture will be immobile.
I am not saying don't learn about and use the data source controls, nor am I saying that the days of not having
to understand how to access data programmatically are nigh. Rather, let me give Joel
Spolsky's advice from his
great essay, The Law of Leaky
Abstractions: "Learn how to do it manually first, then use [data source controls] to save time. Code generation tools which
pretend to abstract out something, like all abstractions, leak, and the only way to deal with the leaks competently is to
learn about how the abstractions work and what they are abstracting. So the abstractions save us time working, but they
don't save us time learning. And all this means that paradoxically, even as we have higher and higher level programming
tools with better and better abstractions, becoming a proficient programmer is getting harder and harder."
The Generic Basics of a Data Source Control
While various data source controls all offer some unique bit of functionality, they all share a common set of features
as well. Conceptually, a data source control is a collection of DataSourceViews, where a
DataSourceView represents some collection of data. All data source controls implement the IDataSource
interface, which is found in the System.Web.UI namespace. This interface defines a couple methods and an event,
the most germane one being the GetView(viewName) method.
As its name suggests, this method returns the data source control's DataSourceView named viewName.
From this common base, the various data source controls begin to diverge and specialize. The SqlDataSource, for example,
is made up SqlDataSourceViews, which are DataSourceView objects specialized to provide capabilities
for representing data from a relational database. Regardless of how the data source controls begin to differentiate, the
data Web controls in an ASP.NET page use all five different data source controls in the same manner, as we will see shortly.
Binding a Data Source Control to a Data Web Control
Since data source controls are declarative controls just like the other ASP.NET Web controls (Labels, TextBoxes, Buttons, and
so on), they can be added to an ASP.NET page by simply dragging and dropping from the Toolbox onto the page. Once there, their
properties can be configured to access or modify the correct data. How this is accomplished depends on what data source control
is being used (which depends on what type of data is being accessed). Once the data source control has been properly configured,
it can be bound to a data Web control by simply setting the data Web control's DataSourceID property to the
ID of the data source control. (Those controls that derive from the BaseDataBoundControl class
have the DataSourceID property. This includes the following controls: AdRotator, BulletedList, CheckBoxList,
DropDownList, ListBox, RadioButtonList, DetailsView, FormView, GridView, Menu, and TreeView.)
Once the DataSourceID property has been assigned a data source control, your duties as the page developer
are done. During the page lifecycle the data Web control will query the needed data from its associated data source control
as needed. For example, when displaying data in a GridView
(the DataGrid's replacement in ASP.NET 2.0) using, say, a SqlDataSource, the GridView control will invoke the SqlDataSource's
GetView() method, which, in turn, accesses the data from the database as specified by the page developer
in the SqlDataSource's various properties. This retrieved data is then enumerated by the GridView and rendered into an
HTML <table>.
That's all there is to it! The data source controls enable page developers to access data without writing a lick of code, much
like the data Web controls allow for data to be displayed without requiring code. Just as the data Web controls programmatically
enumerate their data source and construct the necessary HTML elements behind the scenes, the data source controls programmatically
access the data. (We'll examine how to correctly configure the various
types of data source controls in future articles in this series; for the time being, check out
A Sneak Peak at Working with Data in ASP.NET 2.0, which
shows using a SqlDataSource control through Visual Studio 2005!)
Conclusion
In this article we examined the motivation beind and the basics of ASP.NET version 2.0's new data source controls. With the
data source controls, page developers can create data-driven ASP.NET pages without having to write data access code, instead
specifying data access through the declarative data source controls. Once a data source control has been added to a page
and properly configured, it can be bound to a data Web control by setting the data Web control's DataSourceID
property to the ID property value of the corresponding data source control. Once that association has been made,
the data Web control will automatically retrieve the data from its data source control during the page life cycle.
In future parts of this article series we'll examine the five built-in data source controls in greater detail, as well as see
how to work with data source controls programmatically.
A Multipart Series on ASP.NET 2.0's Data Source Controls
ASP.NET 2.0 introduced a number of new Web controls designed for accessing and modifying data.
These controls allow page developers to declaratively access and modify data without writing any
code to perform the data access. This article is one in a series of articles on ASP.NET 2.0's new data
source controls.
Data Source Control Basics - explores the concepts
and advantages of data source controls, and compares their usage in ASP.NET 2.0 to data access techniques in ASP.NET 1.x.
Accessing Database Data - shows how to use the
SqlDataSource and AccessDataSource controls to query data from a relational database.
Filtering Database Data with Parameters - learn how to
retrieve just a subset of database data based on hard-coded values and values from the querystring, other Web controls on the page,
session variables, and so on.
Creating Custom Parameter Controls - learn how
to create your own custom, declarative Parameter controls for use in the data source controls' parameters collections.
Inserting Data - learn how to insert data using
a SqlDataSource control. Also examines how to retrieve the IDENTITY column value for the just-inserted record.
Deleting Data - see how to delete data using
a SqlDataSource control. Also looks at how to programmatically cancel a delete.
Updating Basics - learn the basics of updating database data using a
SqlDataSource control. Also examines using the GridView to provide a web-based editing interface.
Customizing the Editing Interface - see how to
customize the GridView's columns to provide a customized editing interface that includes input validation and alternative
user interface elements.
Handling Database NULL Valuese - explore how to
extend the GridView's customized editing interface to handle database NULL values.
Using Optimistic Concurrency - see how to prevent
concurrent users from overwritting one anothers changes by using concurrency control.