ASP.NET v2.0 (IV): Data Source Controls, data bound controls and data binding (A)


This article is the fourth in a series looking at ASP.NET 2.0 though it follows on from my earlier overview articles on the subject.
By: Chris Sully Spacer Date: June 29, 2007Spacer

Introduction

This article is the fourth in a series looking at ASP.NET 2.0 though it follows on from my earlier overview articles on the subject. Here’s what we’ve covered thus far:

I: we looked at the enhancements to existing controls. II: we proceeded to provide an overview of the new controls that have been introduced. III: we looked at the changes to the compilation and deployment architecture in v2.0 as well as briefly looking at the tool support in VS .NET 2005.

As promised after 3 overview articles we now move away from the high level material to look in more detail at the nuts and bolts of the changes from v1.X to 2.0 with a couple of articles looking at data source controls, data bound controls and data binding in 2.0. As this is a large topic we'll split the content into A and B articles. A will be mostly about data source controls and B the various data bound controls.

Data binding in v1.x probably had the greatest impact in reducing the code required to build data driven pages, particularly in tandem with the data controls themselves. The data source controls continue this drive to make life simpler for the developer. They remove the need for the developer to repeatedly write almost identical data access code to retrieve data from the data store. At the same time the server side data binding syntax is simplified.

'Code-free' data binding

Data source controls allow declarative definition of all the information required to extract data from the data source. They react to events within the page framework to fetch this data and bind it to specified data bound controls.

Here's an example that shows how simple life can be in the v2.0 world:

<form id="form2" runat="server">
    
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" DataKeyNames="EmployeeID"
 DataSourceID="SqlDataSource1" />
   
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
 ConnectionString="Data Source=OPTIPLEXGX620;Initial Catalog=AdventureWorks;Integrated Security=True"
 SelectCommand="SELECT [EmployeeID], [Title], [BirthDate], [Gender], [HireDate] 
  FROM [HumanResources].[Employee]">
</asp:SqlDataSource>

</form>

(You will need to replace the connection string with that which is pertinent to your own system set up.)

Note that I'm using the AdventureWorks sample database MS provides for SQL 2005 and will continue to do so for demonstration purposes throughout this series of articles.

The SqlDataSource uses the supplied connection string and SQL statement (it could equally be the name of a stored procedure) as well as its own default settings to connect to the database and extract the data. It reacts to the page events that occur when the page is requested and behind the scenes builds the usual ADO.NET objects it needs (either the default Connection, DataAdapter and DataSet or a Connection, Command, and DataReader).

The GridView is a new version of the DataGrid, enhanced with new features. Note it is associated with the data source control via the DataSourceID attribute, in common with all data controls in v2.0 (including all the controls in the System.Web.UI.WebControls and System.Web.UI.HtmlControls namespaces that currently support server-side databinding).

If you run the code you'll get something similar to what you'd expect with a basic DataGrid.

As an aside the GridView also makes adding implementing row sorting and row paging easier than previously. We'll return to look at the GridView and other new data controls in the next article.

As a second example let's look at how you would use a control parameter with a DataSource control and GridView. The control parameter in this instance will be specified via a dropdownlist. Here's the (declarative) code first:

<form id="form3" runat="server">

<asp:DropDownList ID="ddlGender" runat="server" AutoPostBack="True">
  <asp:ListItem Text="Male"  Value="M" />
  <asp:ListItem Text="Female"  Value="F" />
</asp:DropDownList>

<asp:GridView ID="GridView2" runat="server" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1" />

<asp:SqlDataSource ID="SqlDataSource2" runat="server"
   ConnectionString="Data Source=OPTIPLEXGX620;Initial Catalog=AdventureWorks;Integrated Security=True"
   SelectCommand="SELECT [EmployeeID], [Title], [BirthDate], [Gender], [HireDate] 
    FROM [HumanResources].[Employee] where Gender=@Gender">
  <SelectParameters>
    <asp:ControlParameter  Name="Gender" ControlID="ddlGender" PropertyName="SelectedValue"/>
  </SelectParameters>
</asp:SqlDataSource>

</form>

You can even enable editing of data with a GridView and a data source control declaratively:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
  <asp:ListItem Text="Male"  Value="M" />
  <asp:ListItem Text="Female"  Value="F" />
</asp:DropDownList>

<asp:GridView ID="GridView3" runat="server" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1"
      AutoGenerateEditButton="true" />

<asp:SqlDataSource ID="SqlDataSource3" runat="server"
     ConnectionString="Data Source=OPTIPLEXGX620;Initial Catalog=AdventureWorks;Integrated Security=True"
     SelectCommand="SELECT [EmployeeID], [Title], [BirthDate], [Gender], [HireDate] 
      FROM [HumanResources].[Employee] where Gender=@Gender"
     UpdateCommand="Update [HumanResources].[Employee] SET Title=@Title where EmployeeID=@EmployeeID">

    <SelectParameters>
      <asp:ControlParameter  Name="Gender" ControlID="ddlGender" PropertyName="SelectedValue"/>
    </SelectParameters>
</asp:SqlDataSource>

Similarly you could enable Delete functionality.

We'll return to look at other databound controls in the next article.

Data Source controls

The aims of the data source controls (combined with the new data controls and data binding) are to provide:

Types of data source control

The data source controls can be categorised according to the type of data source they will be used to access. All live in the System.Web.UI.WebControls namespace of the .NET Framework and are descended from the base classes DataSourceControl or HierarchicalDataSourceControl. The controls are:

All except the last two you’re safe with your bets at what they are and do. The SiteMapDataSource uses a hierarchical XML file to provide a data source for the special controls in ASP.NET that implement menus and other site navigation features. ObjectDataSource allows developers to interact with a data access or business logic layer consisting of suitable classes, rather than directly with the database. We'll focus on the SqlDataSource and ObjectDataSource as the two developers are likely to use most frequently.

SqlDataSource

This is the choice for most relational database access tasks where the code is to 'directly' access the database. It will default to SQL Server but altering the connection string and ProviderName properties you can use any database for which a provider is available. For full details regarding the available parameters see the SDK/ MSDN documentation.

A key area is how we pass parameters in and out of SQL statements/ stored procedures. Parameters are exposed in a way that allows them to be set declaratively by referencing dynamic values that are part of the page request or the control tree (see the example above). The parameter values can be taken directly from:

All 6 types of parameter are descended from the common base class System.Web.UI.WebControls.Parameter and expose 5 properties/ attributes: Name, Direction, DefaultValue, Type and ConvertEmptyStringToNull.

These parameters can be defined for select, update, delete and insert operations as well as a filter operation used to filter the rows returned by a select operation. At runtime ASP.NET creates a separate ParameterCollection for each of the sections.

You can also work with the SqlDataSourceControl at runtime if the declarative control is insufficient. As well as the DataBind method 4 methods corresponding to the data access operations are exposes: Select, Insert, Update and Delete. When called the specified operation will be called with the declaratively specified parameters. The SqlDataSource also raises events as it operates which can be coded against: 'ing' and 'ed' events of the data operations, e.g. Selecting and Selected. Finally, the SqlDataSource also exposes an SqlDataSourceView instance which contains the data bound to the control. This can be accessed programmatically in an event handler as required.

ObjectDataSource

I'll cover the ObjectDataSource briefly as in many ways it is similar to the other data source controls, the SqlDataSource for example. However, whereas the other data source controls, including the SqlDataSource, encourage a 2 tier approach to building applications the ObjectDataSource depends on a middle business logic tier which defines business objects which you want to bind to UI elements, like the GridView. This is, in fact, the manner in which most business applications will be developed in reality. The ObjectDataSource imposes a few requirements on the business layer/ tier objects:

Summary

In this article we've introduced the declarative, 'no code' data binding capabilities of ASP.NET 2.0 via data source controls and data bound controls. This was done primarily via the SqlDataSource and GridView. In the next article we’ll take a closer look at some of the new data bound controls in ASP.NET 2.0.

References

ASP.NET v2.0 – the Beta Version
Homer et al.
Addison-Wesley

Professional ASP.NET2.0
Evjen et al.
Wrox