CODEDIGEST
Home Articles CodeDigest Tutorials InstallShield FAQs
Skip Navigation LinksHome » Article » ASP.Net Article » Advanced Usages of SqlDataSource Control in ASP.Net-PART 1  Submit Articles and Win Geeky Prizes!!   You are not logged in.
Search
 

Sponsors
InstallShield
 

Product Spotlight
 

Technologies
 

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
Free Trial: InstallShield 2010 for Windows Installers Is InstallShield right for you? InstallShield handles your most complex installation requirements in minutes. Try it now.

By Satheesh Babu
Posted On Aug 23,2009
Article Rating: (Login)
Average Rating: 5
No of Ratings: 1
No of Comments: 2
Category: ASP.Net
Print this article.

Subscribe to our feed!

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.

 

InstallShield

To understand the topic, we will create a sample project that displays User information in GridView control using SqlDataSource control.

Steps

1.      Open Visual Studio 2008.

2.      Click New> Website and Select “ASP.Net Web Site”. You can select the language of your choice. I have selected C#. Rename the website name as per your need.

3.      Include a new SQL express database inside App_Data folder and create a table called  CD_Users.

Note

You can add database by right clicking App_Data folder in the solution and clicking Add New Item. This will bring a dialog box where you need to select “Sql Server Database” and click Add. Then, create a table called CD_Users with the necessary columns using the “Server Explorer”. Just right click the added database and click “Open” to open your database using Server Explorer on the left pane of your Visual Studio 2008.

 

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

 

Sponsors

Useful Books For Developers
LINQ Quickly More books..

Similar Articles

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!!

You can contribute to CodeDigest.Com:
Donate to CodeDigest.com
Article Feedback
Title  
Submitted By  
Comment  
Enter the verification number
 
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