简体   繁体   中英

How to count the rows in a gridview asp.net c#

I have a gridview that is being populated correctly. When the user presses the Search button, the function ShowData() is called which presents the data based on the criteria entered into the textbox. I want to be able to count how many rows are created in the gridview.

I know I can just count it from the SQL Database Table, but I feel simply counting the rows in the gridview would be so much easier! (Please correct me if I'm wrong!)

I've tried to use search_results = GridView1.Rows.Count.ToString(); in code behind in the ShowData() function with this markup:

<div class="size_info" id="allSelected" runat="server" visible="false"><br />
                There are <asp:Label ID="search_results" runat="server"></asp:Label> entries for this search criteria.  
</div>
</div>

but it doesn't seem to be returning any value (not even 0!).

Any help would be most appreciated!

search_results = GridView1.Rows.Count.ToString();

will give compilation error as

System.String cannot be converted to System.Web.UI.Label

Use

search_results.Text = GridView1.Rows.Count.ToString();

And make sure that this is written after grid is bound.

If you have enabled Pagination , by using GridView1.Rows.Count you will only get the current page rows, so if PageSize equals to 10 and you have 60 rows, you will get 10 as result which is not true!

In that case you need to go like this:

protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        var d = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
        if (d != null) lblGridRowsCount.Text = d.Count.ToString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM