Wednesday, July 25, 2012

Asp.Net jQuery GridView Column Count


The number of Columns in an Asp.Net GridView can be obtained using jQuery script as follows.

$("#grdEmployee").find('tr')[0].cells.length


This will count the number of cells in the first row and give the column count.

Example

<script type="text/javascript"
src="JavaScript/jquery-1.7.2.js"></script>
<link type="text/css"
href="Stylesheet.css"
rel="Stylesheet" />
<script type="text/javascript">
$(document).ready(function() {
//
// Add Grid Style
$("#grdEmployee").addClass("Grid");
//
// Add Grid Cell Style
$("#grdEmployee td").addClass("GridCell");
      //
      // Add Header Style
$("#grdEmployee th").addClass("GridHeader");
      //
      // Add Row Style
      $("#grdEmployee tr").addClass("GridRow");</script>   
      //
      // Add Row Hover Style
      // MouseOver
      $("#grdEmployee tr").mouseover(function() {
      $(this).addClass("GridRowHover");
      })
      // MouseLeave
      $("#grdEmployee tr").mouseleave(function() {
      $(this).removeClass("GridRowHover");
      })
      //
      // Get Row Count
      var rowCount = "Total Rows: " + ($("#grdEmployee tr").length -    
      1).toString();
      document.getElementById("lblRowCount").innerText = rowCount;
      //
      // Get Column Count
      var columnCount = "Total Columns: " +
      ($("#grdEmployee").find('tr')[0].cells.length).toString();
      document.getElementById("lblColumnCount").innerText = columnCount;  
});

<asp:GridView
   ID="grdEmployee"
   runat="server"
   AutoGenerateColumns="true"></asp:GridView>
<br>
<span id="lblRowCount" class="Label"></span>
<br>
<span id="lblColumnCount" class="Label"></span>


Add your logic in codebehind to populate the Grid with data.

Stylesheet.css

.Grid
{
      border: 1px solid #000000;
}
.GridCell
{
    padding: 3px 3px 3px 3px; /* Cellpadding */
    border: 1px solid #000000;
    font-family:Verdana;
    font-size:10pt;   
}
.GridHeader
{
      background-color:#999966;
}
.GridRow
{
    background-color:#ffffcc;
}
.GridRowHover
{
    background-color:#CCCCCC;

Search Flipkart Products:
Flipkart.com

2 comments:

Anonymous said...

C# GridView column resizing

Final Fantasy XIV Gil said...

I care for such
info a lot. I was looking for this certain information for a
very long time. Thank you and good luck.
Cheap FFXIV Gil
Final Fantasy 14 CD Key