CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Advanced Usages of SqlDataSource Control in ASP.Net - PART 1

By Satheesh Babu
Posted On Aug 23,2009
Article Rating:
Be first to rate
this article.
No of Comments: 2
Category: ASP.Net
Print this article.

Advanced Usages of SqlDataSource Control in ASP.Net - PART 1

 

With the release of .Netframework 2.0, there are lot of new features added that made the data access very easier and simpler. This release added a new set of data access controls to the asp.net control set called DataSource controls. With these controls, it is now possible to access and do data operations without even writing a single line of code. Using this control is much straight forward and easier which doesn’t even require knowledge on .net programming. Moving forward, we will learn more about SqlDataSource control and its advanced usages.

 

To understand the topic, create a sample project that displays User information from a sql express database in GridView control using SqlDataSource control. I have created a table called CD_Users to demonstrate the SqlDataSource control usages in this article.

 

Binding a SqlDataSource Control

Drag a SqlDataSource control and a GridView control from the “Data” tab of Visual Studio toolbar. Configure the SqlDataSource control through “Configure Data Source...” wizard to fetch the data from the Sql express database added to your solution. Assign the GridView’s DataSourceID property to the SqlDataSource control’s ID.

These steps will generate the code below,

ASPX

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

        SelectCommand="SELECT * FROM [CD_Users]"></asp:SqlDataSource>

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

        DataKeyNames="Email" DataSourceID="SqlDataSource1">

        <Columns>

            <asp:BoundField DataField="UserID" HeaderText="UserID" InsertVisible="False"

                ReadOnly="True" SortExpression="UserID" />

            <asp:BoundField DataField="FirstName" HeaderText="FirstName"

                SortExpression="FirstName" />

            <asp:BoundField DataField="LastName" HeaderText="LastName"

                SortExpression="LastName" />

            <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True"

                SortExpression="Email" />

            <asp:BoundField DataField="RoleID" HeaderText="RoleID"

                SortExpression="RoleID" />

            <asp:BoundField DataField="CreatedOn" HeaderText="CreatedOn"

                SortExpression="CreatedOn" />

            <asp:BoundField DataField="LastUpdated" HeaderText="LastUpdated"

                SortExpression="LastUpdated" />

        </Columns>

    </asp:GridView>

 

Execute the application and you can see the data populated in the GridView control. Moving forward, we will see some advance features that we can implement with the SqlDataSource control.

 

Cancel SqlDataSource DataBind on Initial Page Load

By default, when we configure the SqlDataSource control with a Databound control it will populate the data on the initial page load. At times, we need to restrict the databind on initial page load and populate it in subsequent postbacks. For example, in a button click. SqlDataSource expose various events during the process of data binding to have a control on databinding. With these events, it is possible to do customizations and even implementing business rules dynamically during the databind operation. To cancel a databind, we can utilize the “onselecting” event which will be raised by SqlDataSource control during every database select operation. The SqlDataSourceSelectingEventArgs object is packed with a property called “Cancel” which can be used to cancel the databind.

 

To cancel the databind on initial page load,

ASPX

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

        SelectCommand="SELECT * FROM [CD_Users]"  onselecting="SqlDataSource1_Selecting"></asp:SqlDataSource>

CodeBehind

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)

    {

        if (!IsPostBack)

            e.Cancel = true;

    }

 

Get Total Number of Rows returned by SqlDataSource control

There will be requirements where we need to fetch the number of records or rows returned by SqlDataSource control. The previous section explained about an event called “onselecting” which gets raised during select operations. This means that the selected data will be available only after this event. There is an event called “onselected” event which gets raised after every database select operations. This event exposes a property called AffectedRows that returns number of rows selected.

 

To fetch the total number of records or rows returned by SqlDataSource control,

ASPX

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

        SelectCommand="SELECT * FROM [CD_Users]"  onselecting="SqlDataSource1_Selecting"></asp:SqlDataSource>

CodeBehind

protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)

    {

        Response.Write(e.AffectedRows.ToString());

    }

 

Get Output Parameter Value from SqlDataSource control

Sometimes, we will use stored procedures to bind the data to a databound control using SqlDatasource control. To use strored procedure we need to set the “SelectCommand” property to the stored procedure name and “SelectCommandType” proeprty to “StoredProcedure”. There are also chances where we will have output parameters associated with the Store procedures whose value should be assigned to a page control like Label, etc. 

 

To access the output parameter returned from SP,

ASPX

  <asp:SqlDataSource ID="SqlDataSource2" runat="server"

        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

        onselected="SqlDataSource2_Selected"

        SelectCommand="SP_GetUsersForModeration" SelectCommandType="StoredProcedure">

             <SelectParameters>

                 <asp:Parameter Direction="Output" Name="NoOfRoles" Type="Int32" />

             </SelectParameters>

    </asp:SqlDataSource>

CodeBehind

protected void SqlDataSource2_Selected(object sender, SqlDataSourceStatusEventArgs e)

    {

        Response.Write(e.Command.Parameters["@NoOfRoles"].Value);

    }

SP

ALTER PROC [dbo].[SP_GetUsersForModeration]

(

@NoOfRoles INT OUTPUT

)

AS

Begin

SELECT

       users.Email,

       users.FirstName,

       users.LastName,

       roles.Role,

       roles.RoleID

FROM

       CD_Users users INNER JOIN CD_Roles roles

       ON users.RoleID = roles.RoleID

      

       SELECT @NoOfRoles = COUNT(*) from CD_Roles

End

 




Changing SQL Query at Runtime

Sometimes, there are chances where we require changing the SQL query that is executed against database at runtime for a particular case. SqlDataSource control exposes the SqlCommand object that is being used in DB operation through the SqlDataSourceSelectingEventArgs object in OnSelecting event. We can change the SQL query dynamically on this event using the SqlDataSourceSelectingEventArgs object.  Hence, our requirement can be easily implemented by accessing the command object and changing the SQL query.

 

The below code does that,

ASPX

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

        SelectCommand="SELECT * FROM [CD_Users]"  onselecting="SqlDataSource1_Selecting"></asp:SqlDataSource>

 

CodeBehind

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)

    {       

        e.Command.CommandText = "Select * from CD_Users where FirstName='Satheesh'";

    }

Execute the page and see it in action.

 

Conclusion

The datasource controls as such are very good and productive addition to the ASP.Net framework which greatly simplifies the data access. In this article, we have seen some of the advance usages of SqlDataSource control which makes the control usage effective in those scenarios. In Part 2 of this we will see some more advance features like filtering, programmatically accessing the resultsets, etc.

Happy coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Recorrection
"Should say OnSelected not omselecting"

Should say OnSelecting, not omselecting
;)
correction
To fetch the total number of records or rows returned by SqlDataSource control,

ASPX

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT * FROM [CD_Users]" onselecting="SqlDataSource1_Selecting"></asp:SqlDataSource>

!!! Should say OnSelected not omselecting