Saturday, December 17, 2011

Data Source Controls

Data Source controls are asp .net controls that allow you to connect to a database, retrieve or update data inside the database without writing any code. Thus Data source controls implemented all those downs and ups used in direct data access. More interestingly data source controls work with data oriented list controls (data-bound controls) with ease.
Data source controls handle operations like: 
  • Managing connection
  • Data retrieval and update
  • Data presentation etc
.Net framework includes these data source controls:
  • SqlDataSource -used for Sql Server, Oracle, OleDb and ODBC
  • AccessDataSource - used for Ms Access
  • ObjectDataSource - custom data access class(es)
  • XmlDataSource -used for xml files
  • SiteMapDataSource - used for sitemap data source
In this note I'll be considering SqlDataSource.To use SqlDataSource controls you need to provide certain values including connectionString, ProviderName and command (SelectCommand, UpdateCommand, DeleteCommand or InsertCommand). All these is usually done inside your aspx markup page:


<asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>"
            ProviderName="System.Data.SqlClient"
            SelectCommand="SELECT [DName], [Dcode] FROM [Departments]">
</asp:SqlDataSource>

 In the above connectionString you provide the name of your connectionString (probably stored inside web.config) like the one I underlined.

Now after this point what is remaining is how to bind to another control that uses the retrieved data and may provide data to update. Let us use a dropdownlist to display the list of departments:

<asp:DropDownList ID="DropDownList1" runat="server"
      AppendDataBoundItems="True" DataSourceID="SqlDataSource1"
      DataTextField="DName" DataValueField="Dcode">
      <asp:ListItem Selected="True" Value="Select">Select . . .</asp:ListItem>
</asp:DropDownList>

Inside the above markup DataSourceID="SqlDataSource1" is telling the dropdownlist where to find the data while  DataTextField="DName" and DataValueField="Dcode" tells which column to use for display text and which one to use for item's value respectively. The AppendDataBoundItems="True" on the other hand dictates the dropdownlist to not only use data from database but also append another additional data to be added at design time or at runtime. Now we've added an item <asp:ListItem Selected="True" Value="Select">Select . . .</asp:ListItem> at design time.
The result should look like:

 Go to this links to see more: 
 Data Source Controls, Part 1: The Basics
 

2 comments:

  1. Really great and nice info about asp .net.
    I will share your blog with my friends .Thanks for sharing and keep it up.
    machine to machine

    ReplyDelete

Search This Blog (raadi)