[ASP.NET Data Binding] DataSource Controls

ASP.NET provides another set of controls for data bindings. Using the “DataSource” property of a data-bind control you can bind the data object to the control directly. Another way is to use DataSource controls. Any control that implements the “IDataSource” interface becomes a data source control and you can bind the data-source control to a data-bind control using the “DataSourceID” property.

DataSource controls are very easy to use and you can create a page with data without writing any code. But what you can does not always means what you should do. In professional applications, the DataSource controls are not generally used. Data access code should be separated from UI and be optimized for your business needs.

DataSource controls can still be very useful when you create a small personal application or the test pages to look at the result without relying on data access code.   

1. DataSource Controls

DataSource controls are server controls that allow you to access the data source directly from a web page. They are configurable with parameters.

A parameter values can be obtained  from:

  • a cookie
  • the session
  • a form field
  • a query string

The DataSource controls can be bound to data-bind controls very easily. You just need to add a the DataSource control to a page, set the properties of it, and set the “DataSourceControlID” property of a data-bind control. That’s all. The magic will happen.

The DataSource controls pefrom data binding after the “PreRender” event, which is the last  page creation stage before HTML output is rendered. When you perform “Update” or “Insert” operations using the controls, the events are handled just before the “PreRender” event. This life cycle is very important. When you peform “update” or “insert”, you cannot catch the change in the “Page_Load”.

ASP.NET provides a couple of built-in controls for you.

  • SqlDataSource: ADO.NET provider (SQL Server, Oracle, OLE DB, ODBC, and a new access file (.accdb) )
  • AccessDataSource: Access database file (.mdb)
  • XmlDataSource: XML files
  • SiteMapDataSource: .sitemap
  • LinqDataSource: LINQ to SQL
  • ObjectDataSource: a custom data access class
  • EntityDataSource: Entity Framework

Some controls can cache data: ObjectDataSource, SqlDataSource, and AccessDataSource controls.

2. IDataSource interface

Any controls that implements “System.Web.UI.IDataSource” interface can be a DataSource control.

The interface has 2 methods to be implemented:

  • DataSourceView GetView(string viewName)
  • ICollection GetViewNames()

3. SqlDataSource

The “SqlDataSource” control represents the data access to an ADO.NET provider.

– Attributes –

  • ID: used when referring to the data source during data binding
  • ProviderName: System.Data.SqlClient, System.Data.OracleClient, System.Data.OleDb, or System.Data.Odbc
  • ConnectionString: connection string or a page script to read the connection string ( <%$ ConnectionStrings:NorthwindConnectionString %> )
  • SelectCommand, UpdateCommand, InsertCommand, DeleteCommand:
  • SelectCommandType, UpdateCommandType, InsertCommandType, DeleteCommandType: SqlDataSourceCommandType.Text / SqlDataSourceCommandType.StoredProcedure
  • DataSourceMode: SqlDataSourceMode.DataSet / SqlDataSourceMode.DataReader

– Filtering –

  • The “DataSourceMode” attribute must be set to “DataSet
  • Use “FilterExpression” and “FilterParameters” attributes

– Caching –

  • The “DataSourceMode” attribute must be set to “DataSet
  • Use “EnableCaching“, “CacheExpirationPolicy“, and “CacheDuration” attributes
Categories:
<asp:DropDownList ID="productCategoryDDL" runat="server"
  DataSourceID="productCategorySqlDS" DataTextField="Name"
  DataValueField="ProductCategoryID" AutoPostBack="True">
</asp:DropDownList>
<br /><br />
<asp:GridView ID="productSubCategorGV" runat="server"
  DataSourceID="productSubCategorySqlDS">
</asp:GridView>
<asp:SqlDataSource ID="productCategorySqlDS" runat="server"
  ConnectionString="<%$ ConnectionStrings:AdventureWorks %>"
  SelectCommand="SELECT [ProductCategoryID], [Name] FROM [Production].[ProductCategory]">
</asp:SqlDataSource>
<asp:SqlDataSource ID="productSubCategorySqlDS" runat="server"
  ConnectionString="<%$ ConnectionStrings:AdventureWorks %>"
  SelectCommand="SELECT [ProductSubcategoryID], [Name] FROM [Production].[ProductSubcategory] WHERE ([ProductCategoryID] =
@ProductCategoryID)">
  <SelectParameters>
    <asp:ControlParameter ControlID="productCategoryDDL" Name="ProductCategoryID" PropertyName="SelectedValue" Type="Int32" />
  </SelectParameters>
</asp:SqlDataSource>

Even without writing a single line of code, you can create a web page with 2 data-bind controls (parent-child).

– Exception Handlings –

  • Handle Selected, Updated, Inserted and Deleted events
  • Check the Exception property of the EventArgs object
protected void source_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
    if(e.Exception != null)  { … }
}

4. AccessDataSource

The “AccessDataSource” control works with Access database (.mdb). The “DataFile” attribute is used instead of the “ConnectionString” attribute.

You need to use SqlDataSource to connect to the newer version of Access files (.accdb).

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccess2007file.accdb;Persist Security Info=False;

5. XmlDataSource

The “XmlDataSource” control is for XML files, which are typically stored in App_Data folder.

– Attributes –

  • DataFile: the path of the xml file
  • TransformFile: the path of the xsl (XML Stylesheet Language) file
  • XPath: filtering using XPath expressions
<asp:XmlDataSource ID = "XmlDataSource1" runat="server"
  DataFile="~/App_Data/product.xml"
  TransformFile="~/App_Data/producttransform.xsl"
  XPath="/Products/Product[Category='Food']" >
</ asp:XmlDataSource>

6. SiteMapDataSource

The “SiteMapDataSource” control automatically picks up the “Web.sitemap” file in the root directory of the web application.

– Attributes –

  • StartingNodeUrl:
  • ShowStartingNode:
  • StartingFromCurrentNode

7. LinqDataSource

The “LinqDataSource” control is used with “LINQ to SQL“.

– Attributes –

  • ContextTypeName: the name of the class that represents the database context
  • EnableDelete, EnableInsert, EnableUpdate: Boolean
  • TableName

– Sorting –

  • OrderBy
<asp:LinqDataSource ID = "LinqDataSource1" runat="server"
  ContextTypeName="NorthwindDataContext"
  EnableDelete="True" EnableInsert="True" EnableUpdate="True"
  TableName="Suppliers" OrderBy="CompanyName" Where="Country==@Country" >
  <WhereParameters>
    <asp:QueryStringParameter DefaultValue="us" Name="Country" QueryStringField="country" Type="String" />
  </WhereParameters>
</ asp: LinqDataSource >

8. EntityDataSource

The “EntityDataSource” control is used with “Entity Framework” which becomes replacing LINQ to SQL. I will explain this control in other posts in more detail.

9. ObjectDataSource

The “ObjectDataSource” control is used with a custom data access object.

– Attributes –

  • TypeName: the type name of the object for DB access
  • DataObjectTypeName: the type name of the object for Data Model
  • SelectMethod: works with IEnumerable, IListSource, IDataSource, IHierarchicalDataSource (return classes as a DataTable, DataSet, or some form of a collection)
  • InsertMethod, UpdateMethod, and DeleteMethod:

– Filtering –

  • Use FilterExpression and FilterParameters attributes

– Sorting-

  • Use SortParameterName attribute

– Paging –

  • EnablePaging:
  • StartRowIndexParameterName:
  • MaximumRowsParameterName:
  • SelectCountMethod:

– Caching –

  • EnableCaching:
  • CacheDuration: in seconds

When you crate a “Data Object” class, you need to decorate a class properly.

  • Set the “DataObject” attribute to the class
  • Add “DataObjectMethod” attribute to methods – Pass a “DataObjectMethodType” enum (Select, Insert, Update, and Delete)
[System.ComponentModel.DataObject()]
public class MyData
{
    [System.ComponentModel.DataObjectMethod(Syste.ComponentModel.DataObjectMethod.Select)]
    public static DataTable GetAllData()
    {
    }
}

One thought on “[ASP.NET Data Binding] DataSource Controls

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s