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

Posted by: Suprotim Agarwal , on 9/16/2007, in Category ASP.NET
Views: 396740
Abstract: A common requirement in most of the projects is to select/unselect all checkboxes in your CheckBoxList at once. In this article, we will explore how to perform this action using both ASP.NET and Javascript.
Check/Uncheck all items in a CheckBoxList using ASP.NET and Javascript
 
The CheckBoxList control in ASP.NET 2.0 provides a group of checkboxes that can be dynamically generated by binding it to a data source. In this article, we will explore how to use a Checkboxlist and use ASP.NET and Javascript to select or unselect all your checkboxes in your CheckBoxList.
Using ASP.NET
Step 1: Open Visual Studio. Create a new website called ‘CheckUncheckAll’. Drag and drop a CheckBoxList control to the page. Rename it to ‘cblMulti’.
Step 2: Once the CheckBoxList is added to the page, 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 as shown in the figure below :
 
Note: If you do not want to use the editor and want to add items to the CheckBoxList programmatically, use the following code at the Page load event :
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            cblMulti.Items.Add(new ListItem("Items 1", "Items 1"));
            cblMulti.Items.Add(new ListItem("Items 2", "Items 2"));
            cblMulti.Items.Add(new ListItem("Items 3", "Items 3"));
        }
    }
However, you can also bind the checkbox list to a datareader as show below :
// Assuming that GetListItems returns a list of customerid and customername items in a sqldatareader
SqlDataReader dr = GetListItems();
cblMulti.DataSource = dr;
cblMulti.DataValueField = "cust_no";
cblMulti.DataTextField = "cust_name";
cblMulti.DataBind(); 
To keep things simple, we will be adding items programatically by using the cblMulti.Items.Add(new ListItem(text,value)) in our example.
Step 3: Drag and drop two LinkButtons from the toolbox to the page and rename them as ‘lbAll’ and ‘lbNone’ respectively.
The code will look like this :
<asp:LinkButton ID="lbAll" runat="server">Select All</asp:LinkButton>
<asp:LinkButton ID="lbNone" runat="server">Select None</asp:LinkButton>
Step 4: Double click the two ‘Link Button’ to generate the click events for them. In the click events of the two Link Buttons(), add the following code:
// Check All
    protected void lbAll_Click(object sender, EventArgs e)
    {
        foreach (ListItem li in cblMulti.Items)
        {
             li.Selected = true;
        }        
    }
 
    // Uncheck All
    protected void lbNone_Click(object sender, EventArgs e)
    {
        foreach (ListItem li in cblMulti.Items)
        {
            li.Selected = false;
        }
    }
Step 5 : Run the application and test it. Click on the ‘Select All’ button to select all the checkboxes at once. Similarly click on the ‘Select None’ button to deselect all the checkboxes at once.
So that was simple.
 
Using Javascript
We can do the same using javascript. However for our javascript example, let us add some complexity into our examples. We will take a master page example, and will now add two checkboxlist instead of one to our page. Follow these steps :
Step 1: Open Visual Studio. Create a new website called ‘CheckUncheckJS’. Drag and drop two CheckBoxList controls to the page. Rename it to ‘cbl1’ and ‘cbl2’.
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:CheckBoxList ID="cbl1" runat="server">
    </asp:CheckBoxList><br />
    <asp:CheckBoxList ID="cbl2" runat="server">
    </asp:CheckBoxList>
</asp:Content>
 
Step 2: Populate the two checkboxlist controls in the Page_Load()
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            cbl1.Items.Add(new ListItem("Items 1", "Items 1"));
            cbl1.Items.Add(new ListItem("Items 2", "Items 2"));
            cbl1.Items.Add(new ListItem("Items 3", "Items 3"));
            cbl2.Items.Add(new ListItem("Items 4", "Items 4"));
            cbl2.Items.Add(new ListItem("Items 5", "Items 5"));
            cbl2.Items.Add(new ListItem("Items 6", "Items 6"));
 
        }
    }
Step 3: It’s time to add the SelectAll/None feature to our page. However before we go ahead, we need to understand how to pass the controls kept in content pages to the javascript function. When the page is rendered in the browser, the content and master pages get merged into a single page. This means that the IDs for the controls get renamed. ASP.NET renames the IDs to prevent naming conflicts. Now to handle the renamed controls, ASP.NET provides the ‘Control.ClientID’ and ‘Control.UniqueID’ to get the renamed ID’s.
Having understood this, let us now add some controls to our page and then pass the respective controls to the javascript using the Control.ClientID.
The prototype of our javascript function will be the following :
function CheckBoxListSelect(<pass the control>, <state i.e true or false>)
{   
      // Our code will come here
}
Step 4: Add two anchor tags beneath each checkboxlist controls in your source. Remember that we are using two checkboxlist controls.
<asp:CheckBoxList ID="cbl1" runat="server"></asp:CheckBoxList><br />
Select <a id="A1" href="#">All</a> | <a id="A2" href="#">None</a>
 
<asp:CheckBoxList ID="cbl2" runat="server"></asp:CheckBoxList><br />
Select <a id="A3" href="#">All</a> | <a id="A4" href="#">None</a>
 
Step 5: Add the onclick event to the anchor tags as shown below. In this event, we will call the javascript function and pass the respective checkboxlist controls and the state which will describe ‘true’ or ‘false’ for each checkbox
The code at the end will look like this :
<asp:CheckBoxList ID="cbl1" runat="server"></asp:CheckBoxList><br />
 
Select <a id="A1" href="#" onclick="javascript: CheckBoxListSelect ('<%= cbl1.ClientID %>',true)">All</a>
| <a id="A2" href="#" onclick="javascript: CheckBoxListSelect ('<%= cbl1.ClientID %>',false)">None</a>   
 
    <br />
    <br />
 
    <asp:CheckBoxList ID="cbl2" runat="server">
    </asp:CheckBoxList>
    Select <a id="A3" href="#" onclick="javascript: CheckBoxListSelect ('<%= cbl2.ClientID %>',true)">All</a>
 
| <a id="A4" href="#" onclick="javascript: CheckBoxListSelect ('<%= cbl2.ClientID %>',false)">None</a>
 
Step 6: Let us add the javascript function to the content page now.
For this add the <script/> tag in the content page and code our logic into the function as shown below:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
 
function CheckBoxListSelect(cbControl, state)
{   
       var chkBoxList = document.getElementById(cbControl);
        var chkBoxCount= chkBoxList.getElementsByTagName("input");
        for(var i=0;i<chkBoxCount.length;i++)
        {
            chkBoxCount[i].checked = state;
        }
       
        return false
}
 
</script>
// ASP.NET Controls are placed here
</asp:Content>
 In this javascript function, we accept two parameters, the checkboxlist control and the state (i.e true or false) of each checkbox, that we would like it to be. Since asp.net renders each checkbox as an input tag, what we are really doing over here is first getting the checkboxlist control using  document.getElementById(cbControl) and then counting the number of <input> tags inside that control. Once we get the count, we use a loop to set the state of each control.
Step 7: Well that’s it. Run the application and select/unselect the checkboxes.
Happy Coding!! I hope you liked this article and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed or Subscribe Via Email
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and authored a new one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by cliff chambers on Thursday, September 27, 2007 11:38 PM
great article. you wouldn't believe how many sites out there have ridiculous "examples" of ways to do this that do not work. this was perfect for me, as i needed the best route to duplicate what i already knew how to do with asp/javascript. thanks!
Comment posted by Suprotim Agarwal on Sunday, September 30, 2007 6:31 AM
Glad you liked it Cliff. Thanks for viewing it.
Comment posted by Doug Pettitt on Monday, October 22, 2007 7:38 PM
Suprotim,

I have tried to implement a similiar solution but am having trouble with Code Render Blocks like this: OnClientClick="javascript:test('<%=cklstLoan.ClientID %>');" rendering out like this: onclick="javascript:test('&lt;%=cklstLoan.ClientID %>');". Can you provide me with any help on how to avoid this? Thanks!
Comment posted by Doug Pettitt on Monday, October 22, 2007 11:33 PM
Suprotim,

I have tried to implement a similiar solution but am having trouble with Code Render Blocks like this: OnClientClick="javascript:test('<%=cklstLoan.ClientID %>');" rendering out like this: onclick="javascript:test('&lt;%=cklstLoan.ClientID %>');". Can you provide me with any help on how to avoid this? Thanks!
Comment posted by Suprotim Agarwal on Friday, October 26, 2007 7:42 AM
Hi Doug,
Check this out to see know the reason behind this
http://west-wind.com/weblog/posts/6148.aspx
Comment posted by charan on Tuesday, November 27, 2007 2:18 PM
Great Sample!!!
Keep up the good work.
Comment posted by shiva on Tuesday, January 8, 2008 8:40 AM
hi,
i am facing some problem to delete the selected checkbox in grdiview,when i checked the checkbox and click on delete button it always goes unchecked value
can anyone give my the solution of this problem
                  
Comment posted by Suprotim Agarwal on Wednesday, January 9, 2008 2:21 AM
Hi Shiva, Check this link http://www.dotnetcurry.com/ShowArticle.aspx?ID=66
Comment posted by flora on Monday, February 18, 2008 9:38 PM
Hi,
That's very good example and is similar what i am doing. But i have a problem with ...please see below.

If this comboboxlist with the two button to check/uncheck the value of comboboxlist is in a web user control, and for example in the content page, this comboboxlist user control have used twice. How can i check/uncheck the comboboxlist for both of them?
how can i get the comboboxlist's clientid for these 2 control?

Any ideas? please can someone help!
Comment posted by hj on Monday, March 3, 2008 9:28 PM
gb
Comment posted by Mohamed Ridvan on Saturday, April 5, 2008 7:45 AM
Thanks alot dude!!!! It's helped me alot
Comment posted by Atif on Monday, April 14, 2008 12:56 AM
Thankyou for the code, it really helpful and simple.
Comment posted by Narender Mudgal on Monday, April 14, 2008 1:08 AM
Hi This is naren.
I am learning dot net.
I was searching this solution
but i went through many sites
but this is the easiest solution.
now i will come and see my problems through your site.
Thankyou very much for support

Naren
Comment posted by .,m.,., on Saturday, April 19, 2008 3:33 AM
.,...,.,.
Comment posted by George Asfour on Tuesday, April 22, 2008 11:43 PM
it was great, I found a solution for my final project.
THANKS.........
Comment posted by Ashish Yengkhom on Friday, May 9, 2008 2:29 PM
Great and simple solution. we can remove the 'return false' statement from the CheckBoxListSelect() function though.

Thanks..
Comment posted by antimioni on Friday, May 16, 2008 11:01 AM
This is a very great article, thanks for describe in detail. It really helped me to undestand the underlying concept.
Comment posted by Rakesh Kumar on Monday, May 26, 2008 2:29 AM
More Exaustive
--------------
   <script language="javascript" type="text/javascript">
        function ReadCheckListBox(CheckListBoxId)
        {            
            var objCheckListBox = document.getElementById(CheckListBoxId);
            var chkBoxCount= objCheckListBox.getElementsByTagName("input");
            var chkBoxLabelCount= objCheckListBox.getElementsByTagName("label");
            var ValueField = document.getElementById('Text1');
            var TextField = document.getElementById('Text2');
            var ValueMatter = "";
            var TextMatter = "";
            for(var i=0;i<chkBoxCount.length;i++)
            {
                if(chkBoxCount[i].checked==true)
                {
                    ValueMatter += (ValueMatter.length>0?', ':'') + chkBoxCount[i].id;
                    TextMatter += (TextMatter.length>0?', ':'') + chkBoxLabelCount[i].innerText;
                }
            }
            ValueField.innerText = ValueMatter;
            TextField.innerText = TextMatter;
            return false;
        }
    </script>
    <asp:CheckBoxList ID="CheckBoxList1" runat="server">
        <asp:ListItem Text="abc 123" Value="1"></asp:ListItem>
        <asp:ListItem Text="def 456" Value="2"></asp:ListItem>
        <asp:ListItem Text="ghi 789" Value="3"></asp:ListItem>
        <asp:ListItem Text="jkl 098" Value="4"></asp:ListItem>
    </asp:CheckBoxList><br />
    <input id="Text1" type="text" />
    <input id="Text2" type="text" />
    <input id="Button1" type="button" value="button" onclick="ReadCheckListBox('<%=CheckBoxList1.ClientID%>');" />
Comment posted by Suprotim Agarwal on Sunday, June 1, 2008 1:36 AM
Thanks Rakesh.
Comment posted by kjhkghghk on Monday, August 18, 2008 12:58 AM
lgjklgjlhjkhljkloiuohbjk
gkhjgjkghjkghk
yu8okhjkghkghjmbmbmnmbmbnmmvbouoyou
Comment posted by andrew on Wednesday, September 3, 2008 6:25 AM
Great thanks for that !!!
Comment posted by jayasri on Tuesday, September 16, 2008 10:33 PM
i'm a new learner to c#.net i want to know how can i select all the checkboxes by clicking a single button?
Comment posted by Suprotim Agarwal on Wednesday, September 17, 2008 8:21 AM
Jayasri: The article explains exactly that. Is there anything else you were trying to ask?
Comment posted by Abdul Muheet on Wednesday, September 24, 2008 2:33 AM
Thank you.
The article are awesome
Comment posted by jpramo on Wednesday, September 24, 2008 5:18 AM
Excellent Work Thanks
Comment posted by Avinash kumar singh on Wednesday, November 12, 2008 11:15 AM
i'm a new learner to c#.net i need code how can i select multipale the checkboxes in checkboxlist
Comment posted by Srujan on Saturday, November 22, 2008 7:26 AM
Hai Suprotim Agarwal,
This is Srujan,You are doing a great job.All the articles are very helpful.
Keep it up.
Comment posted by H Nasir on Tuesday, December 16, 2008 5:00 AM
Good. Nice Description its work absolutely well.thanks
Comment posted by Vinny on Friday, May 1, 2009 10:53 AM
Hi Suprotim,
Nice job.  You make using JavaScript so simple.  I really liked reading this article and the examples are very helpful.  I look forward to more articles on using JavaScript.  Thank you very much.
Comment posted by A.R. on Friday, May 1, 2009 7:43 PM
Thanks yo!
Comment posted by Suprotim Agarwal on Monday, May 4, 2009 12:09 AM
Srujan, Nasir, Vinny,A.R - Thanks all for your comments
Comment posted by Amy on Thursday, June 25, 2009 10:33 AM
Hi!
I'm facing a problem. I want to set left click to select a row and double click or ctrl-click to select/unselect a checkbox in the datagrid.

Any idea? Thanks!
Comment posted by Suprotim Agarwal on Thursday, July 2, 2009 2:24 AM
Amy: Check this link to see how to wire actions with the double click event. That should give you some ideas
http://forums.asp.net/p/1123504/1760477.aspx
Comment posted by Pedro Galvez on Friday, January 29, 2010 9:45 AM
I've been asked to use one of the CheckBoxList boxes for the "None" option instead of a separate LinkButton. However, I can't tell whether the latest selection was "None" or any of the other boxes so I can determine if I should clear out "None" when they select one of the other options, as opposed to clearing all other boxes when user selects "None". Any suggestions?
Comment posted by asa on Sunday, February 28, 2010 4:17 AM
The jscript method rocks
Comment posted by Vani on Tuesday, March 2, 2010 1:13 AM
thanks for the amazing solution in javascript
Comment posted by Rakesh on Thursday, March 11, 2010 10:42 AM
Thanks a lot. This works perfectly. Great work!
Comment posted by Manvendra on Thursday, March 25, 2010 5:30 AM
Great article ! This was the thing I was looking from a long time.Keep up the good work
Comment posted by sanjay vishwakarma on Monday, May 3, 2010 8:01 AM
This is right code
thanks
function CheckBoxListSelect(cbControl, state)
{  
       var chkBoxList = document.getElementById(cbControl);
        var chkBoxCount= chkBoxList.getElementsByTagName("input");
        for(var i=0;i<chkBoxCount.length;i++)
        {
            chkBoxCount[i].checked = state;
        }
      
        return false;
}
Comment posted by Anuj Sharma on Tuesday, June 15, 2010 6:07 AM
Thanks alot. this code is very helpful in my project.
Comment posted by Sourabh on Wednesday, October 6, 2010 9:34 AM
Hi,
I have figured that this solution (javascript) does not work in FireFox. Do we need to change something in code to make it work in FireFox? Any solution to this?
Comment posted by Sourabh on Wednesday, October 6, 2010 9:42 AM
Hi,
I have figured that this solution (javascript) does not work in FireFox. Do we need to change something in code to make it work in FireFox? Any solution to this?
Comment posted by Kris on Monday, December 6, 2010 11:39 AM
This would be perfect if it worked in FireFox.
Comment posted by Suprotim Agarwal on Tuesday, December 7, 2010 3:28 AM
Sourabh, Kris: Check this other article of mine that shows a cross browser solution

http://www.devcurry.com/2009/08/check-uncheck-all-checkboxes-in-aspnet.html

I have also written a book which contains a similar solution - http://www.dotnetcurry.com/order/jQueryASPNETRecipesBook.aspx
Comment posted by Tim on Monday, January 17, 2011 1:36 PM
Rather than true and false and two links, why not use li.Selected = Not li.Selected and one link?
Comment posted by Suprotim Agarwal on Thursday, January 20, 2011 1:27 AM
Tim: yes I just wanted it to be more readable. Thanks for your code!
Comment posted by Mojtaba SH on Monday, February 28, 2011 8:31 AM
Thank U very much
Comment posted by adrianjamv on Tuesday, May 10, 2011 10:36 AM
Excelente ejemplo, gracias
Comment posted by Ahmed on Thursday, August 4, 2011 5:29 AM
thanks very much, this is greate.
Comment posted by Gautam on Friday, September 16, 2011 9:26 AM
Very nicely guided and great many thanks!
Comment posted by Ram on Thursday, March 29, 2012 7:57 AM
Good one. Thank you
Comment posted by ytryrytrrr on Monday, July 16, 2012 7:57 AM
khkhh
Comment posted by Phuongly on Wednesday, July 25, 2012 10:35 PM
Thanks!
Comment posted by Rick on Friday, September 14, 2012 9:47 AM
Nice code thanks!

Ric (NY)
Comment posted by swswsws on Monday, July 1, 2013 5:30 AM
vfsss
Comment posted by amit kate on Friday, October 18, 2013 2:35 AM
nice,it works
Comment posted by a on Wednesday, January 29, 2014 6:15 AM
a
Comment posted by Robert on Wednesday, February 19, 2014 6:28 PM
Finally, a proper working solution!  Thanks!
Comment posted by Krishnakumar on Wednesday, November 26, 2014 4:46 AM
Good article for the person like me who doesn't know anything about developments. Very good. Keep it up..Keep in touch with us.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel