Check/Uncheck all items in a CheckBoxList using ASP.NET

The CheckBoxList control in ASP.NET 2.0 is one of the useful control for asp.net developer. But it is not so easy(also not complicated :))to handling like checkbox. This control provides a group of checkboxes that can be dynamically generated by binding it to a data source.

You can handling its operation programmatically using both asp.net or JavaScript. Today I discuss how to checked and unchecked items in CheckBoxList using ASP.net/C#.

First you can bind data to CheckBoxList control using a smart tag appears which allows you to specify a datasource or add items manually to the CheckBoxList.Click on the ‘Edit Items’ to open the ListItem Collection Editor and add items.

Bind data into this control from data source like this:


// Assuming that GetCityList() returns a list of CityID and CityName items in a sqldatareader

SqlDataReader dr = GetCityList ();
cblTest.DataSource = dr;
cblTest.DataValueField = "CityID ";
cblTest.DataTextField = "CityName ";
cblTest.DataBind();


Or, use the following code at the Page load event to add items to the CheckBoxList programmatically:

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
cblTest.Items.Add(new ListItem("Dhaka", "Dhaka"));
cblTest.Items.Add(new ListItem("Chittagong", "Chittagong"));
cblTest.Items.Add(new ListItem("Shylet", "Shylet"));
cblTest.Items.Add(new ListItem("Rajshahi", "Rajshahi"));
}
}

Now drag and drop two asp:button which are named as "CheckedAll" and "UnCheckedAll" respectively.

Check All:
For Check all write the following code in the Click Event of "CheckedAll" button

protected void CheckedAll_Click(object sender, EventArgs e)
{
foreach (ListItem li in cblTest.Items)
{
li.Selected = true;
}
}


Uncheck All:
For UnCheck all write the following code in the Click Event of "UnCheckedAll" button

protected void UnCheckedAll_Click(object sender, EventArgs e)
{
foreach (ListItem li in cblTest.Items)
{
li.Selected = false;
}
}

Comments

Anonymous said…
Nice Post. This transmit helped me in my college assignment. Thanks Alot
Anonymous said…
very fine..

Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."

Check/Uncheck all items in a CheckBoxList using Javascript