Click here to Skip to main content
Click here to Skip to main content

A Multiple Selection DropDownList (a CheckBoxList Inside a DropDownList)

By , 19 Mar 2010
 

Introduction

This ascx user control, the MultiCheckCombo, allows the user to select more than one option inside a DropDownList. The different items that are being checked are being copied in the box area of the control.

The great thing of this control is that it doesn't close the check panel until you click outside the control. Example: you can check more than one item at once.

In ASP.NET C#, if you need a web control that allows the user to check more than one option in a DropDownList, you can use this user control freely.

Background

Well, first of all, this control was made in Microsoft Visual Studio 2008, with .NET 3.5 (2.0) and was written in C#. To use it, you need to have properly installed the AjaxControlToolkit in your project.

Using the Code

Again: You need to have installed the AjaxControlToolkit in your project.

This control is fairly easy to implement. Simply copy the 3 ascx files into your project.

Then replace the namespace in both ascx and ascx.cs files with [YourProjectName].MultiCheckCombo.

E.g.: Let's suppose your project's name is TestMultiCheck, replace in the ascx file the Control tag with the name of your namespace/project:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MultiCheckCombo.ascx.cs" 
    Inherits="TestMultiCheck.MultiCheckCombo" %>

And in your ascx.cs file, change the namespace to:

namespace TestMultiCheck

Well, then drag and drop the main file (MultiCheckCombo.ascx) to your Page Designer.

You may drag the control inside or outside an UpdatePanel, but you need a ScriptManager at the beginning of the body tag of your aspx page.

<asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> 

When you drag the control, the following line should be added automatically to the beginning of your aspx page:

<%@ Register src="MultiCheckCombo.ascx" tagname="MultiCheckCombo" tagprefix="uc1" %>

And the code of the control looks like this (it also will be added automatically):

<uc1:MultiCheckCombo ID="MultiCheckCombo1" runat="server" />        

Then, in the code behind (C#), you have to fill the values of the control.

You can fill it with an ArrayList or with an OdbcDataReader.

A: Easy mode: Filling the MultiCheckCombo with an ArrayList:

ArrayList array = new ArrayList();
for (int i=0;i<100;i++) array.Add(i.ToString());
MultiCheckCombo1.AddItems(array);

B: Other option is to fill the MultiCheckCombo with an OdbcDataReader:

OdbcConnection con = /* get YOUR connection string*/
con.Open();
OdbcCommand cmd = new OdbcCommand();
cmd.Connection = con;
cmd.CommandText = "select text,id from ...........";
OdbcDataReader dr = cmd.ExecuteReader();
MultiCheckCombo1.ClearAll();
dr.Read(); 
MultiCheckCombo1.AddItems(dr, "text", "id");

And that's it. You can now test it.

Some important properties of this controls are:

MultiCheckCombo1.WidthCheckListBox = 200; //Set the Width of the CheckBoxList inside DDL.
MultiCheckCombo1.Width = 250; //Set the Width of the DropDownList
MultiCheckCombo1.Enabled = true;
MultiCheckCombo1.fontSizeCheckBoxList = FontUnit.Small; 
MultiCheckCombo1.fontSizeTextBox = FontUnit.XSmall;
MultiCheckCombo1.Text; //Get or Set the Text shown in the Combo

Some important methods of this control are:

MultiCheckCombo1.unselectAllItems(); //Uncheck all of the Items of the CheckBox
MultiCheckCombo1.ClearAll(); //Delete all the Items of the CheckBox;

Points of Interest

I hope you can make it work. Cheers! ENJOY IT!

By the way, my e-mail is leoivix@hotmail.com.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

leoivix
Web Developer
Argentina Argentina
Systems Eng.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionRead the selected checkbox valuesmemberRockstar_2-Jun-13 19:33 
Hi,
 
How can i read the selected checkbox values, as i've place the user control in gridview.
GeneralMy vote of 5memberRockstar_2-Jun-13 19:23 
My 5! Good One..
GeneralMy vote of 5membercooldiv4u31-May-13 5:10 
This is an excellent article as it explains step by step all functionalities.
GeneralMy vote of 5memberganeshnarsale2-May-13 0:28 
Really a great control..
helps me to improve my webpage
BugDoes not work with several controls inside the same page. [modified]memberJaviere ere24-Jan-13 4:24 
After reading every comment and try some changes I realized that it shows what it should but it doesn't work properly because you cannot read values, the last control you added will be the only one working and also every value is erased when postback happens. Sniff | :^)

modified 24-Jan-13 10:31am.

QuestionProblem while showing the values after selecting the checkbox in MultiCheckCombomembervaibhavpahade2005078-Jan-13 6:31 
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<%@ Register Src="~/UserControl/MultiCheckCombo.ascx" TagPrefix="uc1" TagName="MultiCheckCombo" %>
 

<td>
                   <uc1:MultiCheckCombo runat="server" ID="MultiCheckCombo1" />
               </td>
 
<td>
                    <uc1:MultiCheckCombo runat="server" ID="MultiCheckCombo2" />
 

In my case both MultiCheckCombo1 and MultiCheckCombo2 are loading with correct value but when i am selecting the checkbox in MultiCheckCombo1 its value is showing in MultiCheckCombo2 not in MultiCheckCombo1.</td>

BugAfter submit button text box clears the text whereas checkboxes are checkedmemberMember 429341829-Nov-12 15:50 
After submit button text box clears the text whereas checkboxes are checked.
 
Please suggest me some tip after submit button text box not clears the text.
 

 
Thank You
Soumya Ranjan Maharana

GeneralSelect All option????? [modified]memberKalhangarga29-Aug-12 20:25 
please tell me what changes i have to make for Select all event to include a SELECT ALL in the COMBOBOX

modified 17-Sep-12 7:23am.

GeneralMy vote of 4memberChintan Udeshi4-Jul-12 19:40 
Nice article.
QuestionHow to make checkboxs checked on page loadmembersheetal20129-Jun-12 9:22 
Hi, this control is great and very usefull, i have used this control in my web application and saved the data into a table, Now i want to show this data back in my page with all that checkbox's selected for that values, any help would be appreciated.
 
Thankyou,
Sheetal.
QuestionRESOLVED FOR C#: Multiple MultiCheckCombo controls on same page, textboxes getting wrong selections / Plus solution to undefined showing up in explorermembers.hashmi20-May-12 22:03 
In MultiCheckCombo.ascx change function CheckItem () here:
 
// Added by SH
    // getting clientID of current textbox clicked

    var currentClientID = document.getElementById('<%=txtVal.ClientID %>').value;
 
    // Changed by SH
    //var TxtBox = document.getElementById("<%=txtCombo.ClientID%>");
    var TxtBox = document.getElementById(currentClientID);
 
    TxtBox.value = s;
    document.getElementById('<%=hidVal.ClientID %>').value = s;
 
Add a hidden input control in MultiCheckCombo.ascx:
<input type="hidden" name="txtVal" id="txtVal" runat="server" />
 
Add a function to get the current client ID:
 
// Added by SH
function getClientID (tBox)
{
    document.getElementById('<%=txtVal.ClientID %>').value = tBox;
}
 

Add onclick="getClientID(this.id) in txtCombo, making it:
 
<asp:TextBox ID="txtCombo" runat="server" ReadOnly="true" Width="200" Font-Size="X-Small" onclick="getClientID(this.id)"></asp:TextBox>
 
Basically what was happening was that
document.getElementById("<%=txtCombo.ClientID%>");
was getting the clientID of the last MultiCheckCombo control added to the page. When the user clicks on txtCombo textbox to bring out the checkboxlist, the client of the last textbox was being read as its using document.getElementByID.
The solution was to send the clientID of the respective textbox that the user clicked with the onclick event of the textbox. This calls the getClientID function which effectively sets the value of the hidden input control to the clientID of the textbox.
Now when onclick event of chkList checkboxlist is triggered, the checkitem() function first reads the value of the hidden input control txtVal and then uses that value to get to the right textbox into txtbox variable, to which the value of var s is then assigned.

 
In order to fix undefined showing up in the textbox when using microsoft explorer, change innerType to innerHTML as shown below in function CheckItem():
 
 // Changed by SH: innerType changed to innerHTML else undefined shows in textbox in firefox
            s = s + ", "+ arrayOfCheckBoxLabels[i].innerHTML; 
 
Here’s how it looks:
 
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MultiCheckCombo.ascx.cs" Inherits="SCAIR_SSRS_Report.MultiCheckCombo" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
 
<script type = "text/javascript">
    // Source: www.codeproject.com/Articles/66572/A-Multiple-Selection-DropDownList-a-CheckBoxList-I
    // Open Lisence: www.codeproject.com/info/cpol10.aspx
    // Source Code and Executable Files can be used in commercial applications;

function getClientID (tBox)
{
    document.getElementById('<%=txtVal.ClientID %>').value = tBox;
}
function CheckItem(checkBoxList)
{
    var options = checkBoxList.getElementsByTagName('input');
    var arrayOfCheckBoxLabels= checkBoxList.getElementsByTagName("label");
    var s = "";
 
    for(i=0;i<options.length;i++)
    {
        var opt = options[i];
        if(opt.checked)
        {
            // Changed by SH: innerType changed to innerHTML else undefined shows in textbox in firefox
            s = s + ", "+ arrayOfCheckBoxLabels[i].innerHTML;
        }
    }
    if(s.length > 0)
    {
       s = s.substring(2, s.length); //handling comma
    }
//    // Changed by SH
//    if (s.length == 0)
//    {
//        s = 'Selection...';
//    }

    // Added by SH
    // getting clientID of current textbox clicked

    var currentClientID = document.getElementById('<%=txtVal.ClientID %>').value;
 
    // Changed by SH
    //var TxtBox = document.getElementById("<%=txtCombo.ClientID%>");
    var TxtBox = document.getElementById(currentClientID);
 
    TxtBox.value = s;
    document.getElementById('<%=hidVal.ClientID %>').value = s;
 

}
</script>
 

<asp:TextBox ID="txtCombo" runat="server" ReadOnly="true" Width="200" Font-Size="X-Small" onclick="getClientID(this.id)"></asp:TextBox>
<cc1:PopupControlExtender ID="PopupControlExtender111" runat="server"
    TargetControlID="txtCombo" PopupControlID="Panel111" Position="Bottom" >
</cc1:PopupControlExtender>
 
<input type="hidden" name="hidVal" id="hidVal" runat="server" />
 
<input type="hidden" name="txtVal" id="txtVal" runat="server" />
 

<asp:Panel ID="Panel111" runat="server" ScrollBars="Vertical" Width="250" Height="150" BackColor="AliceBlue" BorderColor="Gray" BorderWidth="1">
 
    <asp:CheckBoxList ID="chkList"
        runat="server"
        Height="150" onclick="CheckItem(this)">
    </asp:CheckBoxList>
 
</asp:Panel>
http://sh-programmer-cornwall.blogspot.com

AnswerRe: RESOLVED FOR C#: Multiple MultiCheckCombo controls on same page, textboxes getting wrong selections / Plus solution to undefined showing up in explorermemberMember 415786215-Sep-12 6:47 
I've implemented several boxes on a page but am having trouble getting/using the values. The boxes populate just fine but when I try to read their text I only get the value of the last box clicked. boxname.Text displays for only the last instance with the values of the last box checked.
 
Anyone help would be greatly appreciated.
GeneralRe: RESOLVED FOR C#: Multiple MultiCheckCombo controls on same page, textboxes getting wrong selections / Plus solution to undefined showing up in explorermemberoozz_6-Dec-12 2:15 
I've got the same problem. When I try the get text to multiCheckCombo, i got nothing.
 
Pls help...
AnswerRe: RESOLVED FOR C#: Multiple MultiCheckCombo controls on same page, textboxes getting wrong selections / Plus solution to undefined showing up in explorermembercooldiv4u31-May-13 6:06 
Hi, thanks for the update, it did resolve the multiple control issue for me. But i need help for some other thing as well. I am using this control in gridview, i am loading data in to grid from two different tables, one for other columns and one for this chechbox controllist. Now i am able to load data into the gridview. but i dont how to save data with the list of selected checkboxes to be uupdated to the database again and reload the updated data into gridview again. Kindly help me into this. It is very urgent.
 
Thanks
Divyesh
Divyesh

QuestionTakes up multiple lines in datagridmemberMember 219182726-Oct-11 8:13 
I integrated the control/code into a datagrid, and it works fine but I get the checkbox on one line and the text (name) on the next line (instead of [x] {Text} like the example). Maybe because I use a template column and set it to text-only unless editing? ASPX code below.
 
<asp:TemplateColumn HeaderText="Employee Name (ID) List" Visible="False">
    <HeaderStyle Width="250px"></HeaderStyle>
    <ItemTemplate>
        <uc1:MultiCheckCombo ID="MultiCheckCombo1" runat="server"/>
    </ItemTemplate>
    <EditItemTemplate>
        <uc1:MultiCheckCombo ID="MultiCheckCombo2" runat="server"/>
    </EditItemTemplate>
</asp:TemplateColumn>
 
Confused | :confused:
AnswerRe: Takes up multiple lines in datagridmembers.hashmi20-May-12 22:15 
Do it in stylesheets like shown in
http://community.sgdotnet.org/blogs/chuawenching/archive/2007/03/22/ASP.NET-2.0-Autowrapping-in-GridView--_2D00_-Is-that-possible_3F00_.aspx[^]
 
Or try setting
 
<ItemStyle Wrap="false"></ItemStyle>
http://sh-programmer-cornwall.blogspot.com

AnswerRe: Takes up multiple lines in datagridmembercooldiv4u31-May-13 5:26 
hi
I want to use this control in datagrid/gridview but not able to do it. can you please share your code how are you binding the control and how the values will be updated back in Row Databound event. Also how to show updated values back on the grid in the control. Your help will be immensely helpful.
Divyesh

QuestionUndefined value in text boxmemberfaisalharoon3-Oct-11 18:38 
hi,
when i check the checkbox value then it shows undefined in the textbox
and also unable to get the selected text and there values in code behind.
Please help.
Thanks in advance.
AnswerRe: Undefined value in text boxmemberleoivix4-Oct-11 2:10 
Hi faisalharoon. This problem sometimes happens in some versions of Firefox. Its a javascript problem and I dont know how to solve it. If anyone can solve this, please post it.
By the way, I send you a modification for the Text property of MultiCheckCombo.ascx.cs. Replace it. It will still show you the word Undefined in the control, but the server will read it in the correct way.
 

///
/// Get or Set the Text shown in the Combo
///

public string Text
{
get
{
string s = "";
for (int i = 0; i < chkList.Items.Count; i++)
{
if (chkList.Items[i].Selected)
{
s += "," + chkList.Items[i].Text;
}
}
if (s.Length > 0) s = s.Remove(0, 1);
return s;
}
set { txtCombo.Text = value; }
}
GeneralRe: Undefined value in text boxmemberfaisalharoon5-Oct-11 22:59 
Thanks a lot leoivix
it worked very fine.
Please need a little more help.
I am using this control in gridview. On button click i extract some ifno from gridview and some info from dropdown list.
then after some operation i rebind the grid to update data.
when page is post back then drop down list remains expanded.
it does not close (collapse).
I ll be very grateful if you could please help.
 
Thanks alot!
AnswerRe: Undefined value in text boxmemberbimboy_14311-Nov-11 8:49 
to get rid of the undefined error.. try using.. this line of code instead.
 

arrayOfCheckBoxLabels[i].innerHTML;
Questioninstantiate via codemembermikeng11121-Sep-11 7:37 
Hi,
 
Thanks for this control and the detail instructions. However, even with the instructions; I am trying to figure out how to do it dynamically via codes.
 
1. I have added the three files into my project and changed the namespace to match mine.
 
In my file .cs, I instantiated:
 
                    MultiCheckCombo dropdown = new MultiCheckCombo();
                    ArrayList array = new ArrayList();
                    for (int i = 0; i < 100; i++) array.Add(i.ToString());
                    dropdown.AddItems(array);
                    this.Controls.Add(dropdown);
 

I am trying to instantiate the dropdown, then manipulate it via the javascript. My .net skills is a little limited, I know I need a reference somewhere. I have a webpart for sharepoint that does not uses any of the regular aspx file that your instructions mention, so I can't really drag and drop the control anywhere. With the current code, I get the error message: "Object reference not set to an instance of an object".
 
Can you tell me what reference I have to add in order for it to work?
Questionget ID and Text from itmemberyasserzaid28-Aug-11 15:40 
how can i get ID and Text from that control
AnswerRe: get ID and Text from it [modified]memberleoivix30-Aug-11 2:24 
Hi yasserzaid. You can get the Text whit MultiCheckCombo1.Text; and the Id whit MultiCheckCombo1.Id. I think that this was your question, wasn't it?
Leoivix

modified on Tuesday, August 30, 2011 12:16 PM

GeneralMy vote of 5memberMember 798862126-Jul-11 23:35 
excellent
Generalmultiple MultiCheckCombo in same pagememberMarco Trova16-Aug-10 23:04 
If you are using multiple MultiCheckCombo controls in the same page, javascript seems to not recognize the correct textbox to fill selected values..
--
Marco
mark@mclink.it

GeneralRe: multiple MultiCheckCombo in same pagememberboonjiann16-Sep-10 18:23 
i have face same problem too. have you get it solved, or have any others solution?Confused | :confused:
GeneralRe: multiple MultiCheckCombo in same pagemembermath2021-Jul-11 18:33 
Use this solution, was a pain to find but I'm happy with the result.
 
http://stackoverflow.com/questions/1106336/multiple-user-controls-with-javascript[^]
BugRe: multiple MultiCheckCombo in same pagememberbhfaisal9-Aug-11 21:55 
I also facing the same problem. When I am using multiple MultiCheckCombo in same page,its only showing the test in one text box. Sigh | :sigh: Sigh | :sigh:
 
Plz help.
GeneralRe: multiple MultiCheckCombo in same page [modified]member07_irfan1-Mar-12 4:28 
1-Change the CheckItem() method like below
function CheckItem(checkBoxList, textBox, hiddenVal)
{
    var options = checkBoxList.getElementsByTagName('input');
    var arrayOfCheckBoxLabels= checkBoxList.getElementsByTagName("label");
    var s = "";
 
    for(i=0;i<options.length;i++)
    {
        var opt = options[i];
        if(opt.checked)
        {
            s = s + ", "+ arrayOfCheckBoxLabels[i].innerText;
        }
    }
    if(s.length > 0)
    {
       s = s.substring(2, s.length); //sacar la primer 'coma'
    }
 
     document.getElementById(textBox).value = s;
     document.getElementById(hiddenVal).value = s;
}
 
2-Remove the onclick attribute of the chkList from the ascx file of the user control.
 
3-Add this lines to code-behind file of the user control
 
Public Overloads Sub Oninit(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Init
    Me.chkList.Attributes.Add("onclick", String.Format("javascript:CheckItem(this, '{0}', '{1}');", txtCombo.ClientID, hidVal.ClientID))
End Sub
 
it seems working.

modified 1-Mar-12 14:44pm.

GeneralRe: multiple MultiCheckCombo in same pagemembers.hashmi20-May-12 22:24 
Solution is here: A Multiple Selection DropDownList (a CheckBoxList Inside a DropDownList)[^]
http://sh-programmer-cornwall.blogspot.com

QuestionEvents for this conrolmemberThushar Saseendran4-Aug-10 3:11 
Hi leoivix,
Thanks for this control. The coding has been done in a very neat and simple style. But I was wondering how you detect on the server when the selection has been changed.
 
Thanks,
Thushar
AnswerRe: Events for this conrolmembers.hashmi20-May-12 22:21 
Selection on what has been changed? Selection of the checkboxes? Like you mean which checkbox is checked / unchecked?
 
That is done here in MultiCheckCombo.ascx:
 
<asp:CheckBoxList ID="chkList" 
        runat="server" 
        Height="150" onclick="CheckItem(this)">                                                                                                                                                                        
    </asp:CheckBoxList>
See how onclick is sending to a javascript function called CheckItem(), thats where.
http://sh-programmer-cornwall.blogspot.com

GeneralLoad ErrormemberMegha0922-Jul-10 1:33 
Hi !!!
 
I have followed all the steps, still I'm getting the following error -
 
Error 3 Could not load type 'TestMultiCheck.MultiCheckCombo'. D:\Dot Net Hands On\TestMultiCheck\MultiCheckCombo.ascx 1
 
Please, send me the solution on mail4megha@gmail.com
 
-regards
Megha
Generalsome doutsmemberravanth18-Mar-10 18:30 
its working fine, but i have some error
 

Error 2 Could not load type 'SRL.UserControls.MultiCheckCombo'. D:\vs2008\DDLCheckbox\MultiCheckCombo.ascx 1
 
so please send whole project to my id : ravanthkannan@gmail.com
Sir/Mam,
 
I'm Kannan.I Like very much for the coding for the project
THANKNG YOU

KANNAN

GeneralRe: some doutsmemberleoivix19-Mar-10 3:17 
Hi Kannan.
Replace the namespace in both ascx and ascx.cs files with [YourProjectName].MultiCheckCombo.
 
E.g: Let´s suppose your project's name is TestMultiCheck, then replace in the ascx file:
 
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MultiCheckCombo.ascx.cs" Inherits="SRL.UserControls.MultiCheckCombo" %>
with
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MultiCheckCombo.ascx.cs" Inherits="TestMultiCheck.MultiCheckCombo" %>
And in your ascx.cs file change the namespace to:
namespace TestMultiCheck
I will modify the original post in order to add this trick.
I hope you can make it work now.
Bye.
GeneralRe: some doutsmemberravanth22-Mar-10 18:38 
Dear leoivix,
 
Thanks for reply,
 
but still i have some error , i change the namespae both ascx and ascx.cs file.
 

error message :
 
Error 2 Could not load type 'MultiCheckComboBox.MultiCheckCombo'. D:\vs2008\MultiCheckComboBox\MultiCheckCombo.ascx 1
Sir/Mam,
 
I'm Kannan.I Like very much for the coding for the project
THANKNG YOU

KANNAN

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 19 Mar 2010
Article Copyright 2010 by leoivix
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid