How to Get or Count the Total number of GridView Rows using JavaScript

Have you ever wondered how to count the total rows in a GridView? I am sure you did, as some time it is required to execute some action using the row count. I have previously shared a tip on how to count the GridView rows using jQuery . Here, I am going share a simple example on how to count the total rows of a GridView control, with and without its header using JavaScript.

In the jQuery example that I have mentioned above, I have used a jQuery length property. Similarly, you can make use of the “length” property in JavaScript too. There is no need to add CDN or any other library file. Its simple.

Syntax

string.length

The Markup

In the markup section, I have a GridView control, attached with an SqlDataSource control to connect to a database table and populate data to the grid. Along with it, I have an <input> box of type button with the onclick attribute attached. Clicking the button will call a JavaScript function that will count and return the total number rows.

Here’s how you can Populate Data to a GridView control using SqlDataSource. The link is useful if you are a beginner.

<asp:GridView ID="grdEmployee" 
    AutoGenerateColumns="False" 
    DataKeyNames="EmpID" DataSourceID="SqlDataSource1" 
    GridLines="None"
    runat="server">

    <Columns>
        <asp:BoundField DataField="EmpID" HeaderText="EmpID" 
            ReadOnly="True" SortExpression="EmpID" />
        <asp:BoundField DataField="EmpName" HeaderText="EmpName" 
            SortExpression="EmpName" />
        <asp:BoundField DataField="Designation" HeaderText="Designation" 
            SortExpression="Designation" />
        <asp:BoundField DataField="Department" HeaderText="Department" 
            SortExpression="Department" />
    </Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:ENCODEDNAConnectionString %>" 
    SelectCommand="SELECT [EmpID], [EmpName], [Designation] FROM [Employee]">
</asp:SqlDataSource>

<p>
    <input type="button" id="btCount" value="Show Row Count" 
        onclick="countGridRows('grdEmployee')" />
</p>

<%--ADD LABEL TO SHOW THE TOTAL COUNT.--%>
<p><label id="lbl_RowCount"></label></p>

Ok, now lets see the script.

The JavaScript to Count GridView Rows

<script>
    function countGridRows(grid) {
        var iRows;
        var grd = document.getElementById(grid);
        iRows = grd.getElementsByTagName('tr');

        // GET THE TOTAL ROW COUNT INCLUDING THE HEADER, SHOW IT.
        document.getElementById('lbl_RowCount').innerHTML =
            'The total rows including the header is: ' + iRows.length;

        // GET TOTAL ROW COUNT EXCLUDING (WITH OUT) THE HEADER.
        var iRowsWithoutHeader = 0;
        for (var i = 0; i <= iRows.length - 1; i++) {
            if (iRows[i].getElementsByTagName('td').length > 0) {
                iRowsWithoutHeader++;
            }
        }

        // COMBINE BOTH THE RESULTS AND SHOW IT.
        document.getElementById('lbl_RowCount').innerHTML =
            document.getElementById('lbl_RowCount').innerHTML + '<br />' +
            'Total rows without header: ' + iRowsWithoutHeader;
    }
</script>

The function takes a parameter grid, a string value. The button that I have on my web page, calls this function with id of the GridView. This is in case you have multiple controls on your web page, you can call function with a different id.

Next, I’ll create a GridView object, so I can read its properties etc. A GridView control, when rendered, produces <table> like rows and columns. Therefore, using JavaScript getElementsByTagName() method I’ll get a collection of elements with the tag name tr.

iRows = grd.getElementsByTagName('tr');

Now, I can get the total row counts, including the header, using the length property. Remember, the header itself is a row.

document.getElementById('lbl_RowCount').innerHTML =
    'The total rows including the header is: ' + iRows.length;

I can also get the actual rows, which have all the data extracted from a database table. To do this I am going check if the rows have <td> or table definitions. A table header has <th> tag that defines the header cell, whereas, other rows will use <td> tag element to define standard cells. To do this, I’ll again use the getElementsByTagName() method and check if the row contains <td>.

var iRowsWithoutHeader = 0;
for (var i = 0; i <= iRows.length - 1; i++) {
    if (iRows[i].getElementsByTagName('td').length > 0) {
        iRowsWithoutHeader++;
    }
}

Well, that’s it.

Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+
comments powered by Disqus

Join our Google Plus Community and be a part of a discussion!