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...
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.
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"
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;
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;