Tuesday, 12 July 2011

Check/uncheck GridView Header checkbox using Javascript Code


<script type="text/javascript">
     function SelectAll(id)
        {
          var grid = 
document.getElementById("<%= GridView1.ClientID %>");
            variable to contain the cell of the grid
            var cell;
            
            if (grid.rows.length > 0)
            {
            
             for (i=1; i<grid.rows.length; i++)
              {
              cell = grid.rows[i].cells[0];
              for (j=0; j<cell.childNodes.length; j++)
               {           
                if (cell.childNodes[j].type =="checkbox")
                 {
                  cell.childNodes[j].checked = 
document.getElementById(id).checked;
                 }
                }
              }
            }
        }
    </script>
 
Server side binding for checkbox is as follow:
 
    protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        { 
         ((CheckBox)e.Row.FindControl("cbSelectAll")).
Attributes.Add("onclick", "javascript:SelectAll('" + 
          ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
        }
    }

No comments:

Post a Comment