How do you check if SQLDataSource returns empty data

A user asked me a simple way to determine if the SQLDataSource returns empty data.

Here's a simple way to do so: Use the OnSelected event of the SQLDataSource


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


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


SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName],


[ContactTitle], [Address] FROM [Customers]"


onselected="SqlDataSource1_Selected">


</asp:SqlDataSource>




C#


protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)


{


if (e.AffectedRows < 1)


{


// perform action


}


}




VB.NET


Protected Sub SqlDataSource1_Selected(ByVal sender As Object, ByVal e As SqlDataSourceStatusEventArgs)


If e.AffectedRows < 1 Then


' perform action


End If


End Sub



Note: As pointed out by a reader, this tip will not work if SQLDataSource caching is enabled.

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

7 comments:

Shilpa Jathar said...

Thank you for posting this solution. Really helpful.

Anonymous said...

It helps me too, thank you!

Anonymous said...

This is useful but it fails when SQLdatasource Caching is enabled, as 0 is returned.

Suprotim Agarwal said...

Good point! I have added it to the post.

A said...

Another issue is that when using a DataReader, 0 is always returned as well.

A said...

Another issue is that if using a DataReader, 0 is always returned as well.

Harryest said...

It's fantastic!!! Very, very thanks!!!