Monday, February 7, 2011

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;
}
}

3 comments:

Anonymous said...

Nice Post. This transmit helped me in my college assignment. Thanks Alot

Anonymous said...

very fine..

Anonymous said...

Hi try this logic also http://codingresolved.com/discussion/111/how-to-fill-checkboxlist-from-database-with-check-uncheck

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...