akb29 akb29 - 1 month ago 13
ASP.NET (C#) Question

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!

Answer
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.