Hi,
I'm using SqlDataSource control.
Is there a way to know how many records a query has returned?
Try this one to get the total Rows Returned
This is a simple trick about how you can get the total of rows returned from your SqlDataSource control's SelectCommand query.
When you bind a data-source control to a GridView control and use paging etc, you can't use the GridView's Rows property to get the number of rows returned from your data-source control. The Rows property will only return the rows rendered by the GridView control. To get the total number of rows returned from the SelectCommand, you can hook up to the SqlDataSource's Selected event. The Selected event's SqlDataSourceStatusEventArgs event argument's AffectedRows property will return the number of totals rows the SelectCommand returnes. The following example is a simple page with a GridView, SqlDataSource control and a label control. The lable control will be used to display the total number of rows the SelectComamand of the SqlDataSource control returns.
<%@. Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="Server">
protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
totalRows.Text = e.AffectedRows.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"
DataSourceID="SqlDataSource1" AllowPaging="True">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"
ProviderName="System.Data.SqlClient" SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName] FROM [Customers]" OnSelected="SqlDataSource1_Selected">
</asp:SqlDataSource>
<asp:Label ID="Label1" runat="server" Text="Number of total rows:"></asp:Label>
<asp:Label ID="totalRows" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Hope this will help you
Satya
No comments:
Post a Comment