xorpower
xorpower

Reputation: 19003

how to count number of rows in gridview in javascript?

As the question says, i wish to count the number of rows in gridview via JS. I am doing the way it is done here but that is not coming up correctly.

I have also tried different ways as:

 1. var rowscount = document.getElementByID('<%=Gridview1.ClientID%>').rows.length; 
 2. var rowscount = document.getElementByID("<%=Gridview1.ClientID%>").rows.length; 
 3. var rowscount = document.getElementByID('<%#Gridview1.ClientID%>').rows.length;
 4. var rowscount = document.getElementByID("<%#Gridview1.ClientID%>").rows.length;    
 5. var rowscount = document.getElementByID("Gridview1.ClientID").rows.length;
 6. var rowscount = document.getElementByID("Gridview1").rows.length;  

UPDATE : Forgot to Mention: My gridview is inside updatepanel. Would that make any difference? What is the right statement?

Upvotes: 6

Views: 47896

Answers (7)

kasim
kasim

Reputation: 356

We can simplify that,

var gridViewRowCount = document.getElementById("<%= GridView1.ClientID %>").rows.length;
alert(gridViewRowCount);

Upvotes: 1

user2335127
user2335127

Reputation: 31

var GridId = "<%=Questionsedit.ClientID %>";            
var grid = document.getElementById(GridId);
rowscount = grid.rows.length;

Upvotes: 3

xorpower
xorpower

Reputation: 19003

Found the reason: Because the grid is included in content page, the javascript had to be included under form tag. It runs well! Thanks all for inputs!!

Upvotes: 1

brheal
brheal

Reputation: 1237

You could set the RowStyle.CssClass property for the gridview and count them using jQuery.

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" ...>
   <RowStyle CssClass="gridrow" />
</asp:GridView>

This will render the grid rows with the class specified.

<tr class="gridrow">
  <td>row data here</td>
</tr>

Then you can count the rows using the class selector

var rowscount = $(".gridrow").length;

Upvotes: 1

Răzvan Flavius Panda
Răzvan Flavius Panda

Reputation: 22126

If you want to get the number of rows from the server one way would be to use:

var rowsCount = <%=GridView1.Rows.Count %>

It is also possible to send the data to JavaScript from codebehind.

Upvotes: 6

4b0
4b0

Reputation: 22321

try this:

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

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

Upvotes: 0

Dot NET
Dot NET

Reputation: 4907

DataTable dt = //configure datasource here 
GridView1.DataSource = dt;
GridView1.DataBind();
HiddenField1.value = GridView1.Rows.Count.ToString();

var  count = document.getElementById('HiddenField1');

alert(count.value);

This seems to have worked for someone in this forum post.

Upvotes: 2

Related Questions