Tuesday, February 15, 2011

gridview: CheckBox 'SelectAll' and 'DeselectAll' using JAVASCRIPT

Checking the checkbox in the header would select all the checkboxes in the column and un-checking a single checkbox in the column would un-check the header checkbox. This strategy can be used to access any type of controls not only inside the GridView but other data rendering controls as well. Now lets see the code for the same.


Javascript Code:


           SelectAll CheckBox's:
    function selectAllCheckboxInGrid(gridID, chk) 
    {
        var grid = document.getElementById(gridID);
        //Loop starts from 1 because the zeroth row is the header. 
        for (var i = 1; i < grid.rows.length; i++) 
        {
            //Getting the control in the second cell of the grid. 
            //Second cell contains the checkbox. 
            var cntls = grid.rows[i].cells[1].getElementsByTagName('input');
            //If you are have only one control in the cell then 
            //one can do away with the loop. 
            for (var j = 0; j < cntls.length; j++)
            {
                if (cntls[j].type == "checkbox")
                    cntls[j].checked = chk.checked;
            }
        }
    }


C# Code:
    public partial class _Default : System.Web.UI.Page
{
    DataSet ds = new DataSet();
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        Bind();
    }
    
    protected void gridCheck_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //Check if the row is of header type. 
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //Add the javascript function which gets called 
            //when the checkbox in the header is clicked. 
            (e.Row.FindControl("chkHeader") as CheckBox).Attributes.Add("onclick", "javascript:selectAllCheckboxInGrid('" + gridCheck.ClientID + "', this);");
        }
       
    }
    public void Bind()
    {
        SqlDataAdapter sda = new SqlDataAdapter("select * from Sathish", con);
        sda.Fill(ds);
        gridCheck.DataSource = ds.Tables[0];
        gridCheck.DataBind();
    }


}






No comments: