Search   Articles   Dev Forums   Personalize   Favorites   Member Login   ASP.Net Hosting
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Sunday, February 19, 2006

Search Directory
ESET
ASP.NET
VB.Net
C-Sharp
SQL Server
 
More Partners >>

How to Check all Checkboxes without PostBack

Author: DevASP Team
Download Source Code : 685_GridViewCheckBox.zip

In this article I will try to explain you how you can add javascript on Page_PreRender event. This will help full in scenarios where you don’t want to postback your page and page will work with server

To begin with this application, create a new application in asp.net 2.0 and drop grid view control on your page. Now add the following code on page load event:

 

        this.Page.PreRender +=new EventHandler(Page_PreRender); 

 

        SqlConnection objConn = new SqlConnection("Persist Security Info=False;User ID=uid;password=pwd;Initial Catalog=tempdatabase");

        SqlDataAdapter objAdap = new SqlDataAdapter();

        DataSet ds = new DataSet();

 

        objConn.Open();

 

        objAdap = new SqlDataAdapter("Select RouteID from Route", objConn);

        objAdap.Fill(ds);

        GridView1.DataSource = ds;

        GridView1.DataBind();

 

        objConn.Close();

In above code the main thing you will see is I have registered the Pre_Render event on page load now add the following code on your page:

 

protected void Page_PreRender(object sender, EventArgs e)

    {

        string script;

 

        script = "<script language=\"javascript\" type=\"text/javascript\">";

        script += "function checkAll(chk){";

        script += "if(document.getElementById('" + GridView1.HeaderRow.FindControl("chkBox").ClientID + "').checked == chk.checked){";

        foreach (GridViewRow row in GridView1.Rows)

        {           

            script += "document.getElementById('" + row.FindControl("chkBox2").ClientID + "').checked = chk.checked;";           

        }

        script += "}";

        script += "}";

        script += "</script>";

       

 

        ((CheckBox)GridView1.HeaderRow.FindControl("chkBox")).Attributes["onClick"] = "checkAll(this);";

       

        this.RegisterStartupScript("sample", script);

    }

Here RegisterStartupScript will register your script on your browser page.   




Article Comments
Name:  Shirish Bhale 
This is a simple code to check all check boxes into Item templete.chkAll is used to chech all the chkFile check boxes.

protected void chkAll_CheckedChanged(object sender, EventArgs e)
{

int Rows = grdFileDetails .Rows.Count;
for (int j = 0; j < Rows; j++)
{
Control ctrl2 = grdFileDetails.Rows[j].Cells[0].FindControl("chkFile");
CheckBox chkBox2 = ((CheckBox)ctrl2);
if (i == 0)
chkBox2.Checked = true;
else
{
chkBox2.Checked = false;
}
}
if (i == 0)
i = 1;
else
i = 0;
}

Name:  yy 
well done !

Name:  uttam kumar singh 
Article about CheckBox



Disclaimer - Privacy
Copyright © 2008 DevASP.net