How to count the rows in a gridview in asp.net using jQuery

Does anyone know how to count the no of rows in asp:GridView using jQuery. If no rows found then I want to do stuff…

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

A GridView is just rendered as a standard HTML table, so just count the number of tr elements under the GridView:

var totalRows = $("#<%=GridView1.ClientID %> tr").length;

Method 2

Every GridView produces HTML that is basically a table and that table has an ID (view source of your output page to know what im talking about). You can pass the ID either from .Net to JavaScript by means of myGridView.ClientID or in ASP.NET 4 make the ClientIdMode="Static" and thus use the exact same ID you use for the ASP control.

Then in jquery (which is a client-side layer that is completely seperated from the GridView layer), grab that ID and count:

$("#mygridviewid tr").length;

Method 3

You can assign a CSS class to your gridview using CssClass (I don’t remember the exact spelling) property, and then access it jquery’s css class selectors.

Suppose you have assigned gridviewclass to that property, then when you write –

$('table.gridviewclass')

in jquery, you will be able to access the table that is being generated in place of that gridview by ASP.NET. Now, to access all the rows, you will write –

$('table.gridviewclass tr')

which will give you all the rows of that table inside a jquery array. To count the number of rows, you will then write –

var rowcount = $('table.gridviewclass tr').length

if(rowcount == 0)
{
    // No rows found, do your stuff
}
else
{
    // Rows found, do whatever you want to do in this case
}

To access the first row, you can use the following selector –

$('table.gridviewclass tr:first')

To access the last row, you will write –

$('table.gridviewclass tr:last')

etc. You can find a whole list of jquery selectors here.

Hope that helps.

Method 4

I tried this
var totalRows = $("#<%=GridView1.ClientID %> tr").length;
and it failed
when I tried

var count = $get("mygridviewclientid").rows.length

it gave the count of all the rows (th and tr)
I also made sure that the attribute ClientIDMode="Static"


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x