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

Multiselect Dropdown for Web Applications

By , 17 Dec 2008
 
Prize winner in Competition "Best ASP.NET article of September 2008"

Introduction

Whenever there is a requirement of selecting multiple values in a Web application, where space holds an importance and one needs a client-interactive User Interface – a control that has an auto-collapse feature and looks like multiple select dropdown is a good fit.

This is a control that allows a user to select multiple values through a dropdown. It clubs input element, an image and a checkboxlist to give a feel of multi-selectable dropdown. It has an auto-collapse feature apart from explicit close option giving it a total feel of a normal dropdown. The control can be tweaked by developers as per their own needs very easily. The code sample of the same is attached with the article.

Background

We needed to provide an option of multi-select in our project lately. For multiple select, ASP.NET provides CheckBoxList which takes quite a lot of space and does not always fit in the UI requirements. In our UI and as per the customer's request, we were asked to use a dropdown like feature that can select multiple values (just like one of the controls in .NET Windows). I searched on The Code Project and Googled it but could hardly find any control that gave a dropdown look and allowed multiple select. Some were there but they weren't free! So, I went ahead and made my own. And since I was making it myself, I added all the features that I thought would be user friendly.

Using the Code

The first thing was to place the controls to give the look and feel of a dropdown. This was achieved in HTML using proper CSS for the controls.

<div id="divCustomCheckBoxList" runat="server" onmouseover="clearTimeout(timoutID);"
         onmouseout="timoutID = setTimeout('HideMList()', 750);">
    <table>
        <tr>
            <td align="right" class="DropDownLook">
               <input id="txtSelectedMLValues" type="text" readonly="readonly"
                 onclick="ShowMList()" style="width:229px;" runat="server" />
            </td>
            <td align="left" class="DropDownLook">
               <img id="imgShowHide" runat="server" src="drop.gif"
                          onclick="ShowMList()" align="left" />
            </td>
        </tr>
        <tr>
            <td colspan="2" class="DropDownLook">
               <div>
                   <div runat="server" id="divCheckBoxListClose" class="DivClose">
                         <label runat="server" onclick="HideMList();"
                                   class="LabelClose" id="lblClose"> x</label>
                     </div>
                   <div runat="server" id="divCheckBoxList" class="DivCheckBoxList">
                         <asp:CheckBoxList ID="lstMultipleValues" runat="server"
                          Width="250px" CssClass="CheckBoxList"></asp:CheckBoxList>
                     </div>
                 </div>
            </td>
        </tr>
    </table>
</div> 

CSS has a very important part out here to give it a dropdown look:

.DivClose
{
         display:none;
         position:absolute;
         width:250px;
         height:220px;
         border-style:solid;
         border-color:Gray;
         border-width:1px;
         background-color:#99A479;
}

.LabelClose
{
         vertical-align:text-top;
         position:absolute;
         bottom:0px;
         font-family:Verdana;
}

.DivCheckBoxList
{
         display:none;
         background-color:White;
         width:250px;
         position:absolute;
         height:200px;
         overflow-y:auto;
         overflow-x:hidden;
         border-style:solid;
         border-color:Gray;
         border-width:1px;
}

.CheckBoxList
{
         position:relative;
         width:250px;
         height:10px;
         overflow:scroll;
         font-size:small;
}

While the CheckBoxList control was populated, a JavaScript handler was attached to it such that selection/de-selection of any option reflects in the input element (in selected values placed in a dropdown).

// Append an event to the checkboxes in the list
lstMultipleValues.Attributes.Add("onclick", "FindSelectedItems
         (this," + txtSelectedMLValues.ClientID + ");");

Using JavaScript, we keep track of what is selected in the list. Further, the open and close of the div-elements are also handled through JavaScipts using onMouseOver, onMouseOut events.

<script type="text/javascript">
   var timoutID;

   //This function shows the checkboxlist
   function ShowMList()
   {
       var divRef = document.getElementById("divCheckBoxList");
       divRef.style.display = "block";
       var divRefC = document.getElementById("divCheckBoxListClose");
       divRefC.style.display = "block";
   }

   //This function hides the checkboxlist
   function HideMList()
   {
       document.getElementById("divCheckBoxList").style.display = "none";
       document.getElementById("divCheckBoxListClose").style.display = "none";
   }

   //This function finds the checkboxes selected in the list and using them,
   //it shows the selected items text in the textbox (comma separated)
   function FindSelectedItems(sender,textBoxID)
   {
       var cblstTable = document.getElementById(sender.id);
       var checkBoxPrefix = sender.id + "_";
       var noOfOptions = cblstTable.rows.length;
       var selectedText = "";
       for(i=0; i < noOfOptions ; ++i)
       {
          if(document.getElementById(checkBoxPrefix+i).checked)
          {
             if(selectedText == "")
                selectedText = document.getElementById
                                   (checkBoxPrefix+i).parentNode.innerText;
             else
                selectedText = selectedText + "," +
                 document.getElementById(checkBoxPrefix+i).parentNode.innerText;
          }
       }
       document.getElementById(textBoxID.id).value = selectedText;
    }
</script>

The client side events of controls are used in a way such that as long as we have a mouse over the control (textbox or dropdown or checkboxlist or scroll) the list is open. Once the mouse leaves the control, after a certain time (configurable), it gets collapsed automatically. To add more flexibility for the user, a close option is also provided at the bottom of the control. Developers can tweak the control as per their requirements.

Points of Interest

The work was appreciated by the team members and the client finds it to be a good, clean way to provide users with a multi-select option! Last but not the least, it is free!

History

  • 14th December, 2008: Wordings changed
  • 25th September, 2008: Initial post

License

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

About the Author

Sandeep Mewara
Software Developer (Senior)
India India
Member
From Bangalore, India.
My blog: http://smewara.wordpress.com/

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   
AnswerRe: How to get the checkboxlist selected id?mvpSandeep Mewara23 Mar '11 - 2:31 
alyy0406 wrote:
How do I get the selected id?

Simple!
 
In Submit button click event, write:
string selectedID = string.Empty;
foreach (ListItem li in lstMultipleValues.Items)
{
    if (li.Selected)
        selectedID += li.Value + ",";
}
lblTextSelectedID.Text = "Submitted Value IDs: " + selectedID;
 
The values of checkboxlist is set. All you need is to get it. Thumbs Up | :thumbsup:

GeneralRe: How to get the checkboxlist selected id?memberE$w@r23 Mar '11 - 3:03 
Good Answer Sandeep.Thumbs Up | :thumbsup:
GeneralRe: How to get the checkboxlist selected id?memberalyy040628 Mar '11 - 15:23 
Thanks Sandeep. Big Grin | :-D
GeneralMy vote of 5memberE$w@r25 Feb '11 - 1:48 
Nice article.
 
P.S: Update with fixing of Firefox issue (If you have time)
GeneralRe: My vote of 5mvpSandeep Mewara23 Mar '11 - 2:20 
E$w@r wrote:
Nice article.

Thanks Eswar!

GeneralMy vote of 2memberAshish Tyagi 4016 Jan '11 - 6:00 
5
GeneralMy vote of 1memberAshish Tyagi 4015 Jan '11 - 9:26 
use less
Generalthe project is not working in Firefoxmemberserhatergun24 Nov '10 - 21:17 
Frown | :( Help.i have to use this application in my project.But it is working IE ,CROME, SAFARI. but it is not working Firefox.
GeneralRe: the project is not working in FirefoxmentorSandeep Mewara24 Nov '10 - 22:02 
Javascript code might need some change for Firefox.
Debug and see the exact reason for failure.
GeneralRe: the project is not working in Firefoxmemberserhatergun24 Nov '10 - 22:29 
i've been trying for hours.but i couldn't.i think that problem is here.
lstMultipleValues.Attributes.Add("onclick", "FindSelectedItems(this," + txtSelectedMLValues.ClientID + ");");
it is not working only FF.can you help me_?
GeneralRe: the project is not working in Firefoxmemberniceraj28 Dec '10 - 21:06 
Ya your are right, Not working in Firefox. The same line is not working. I also tried lot, but I couldnt.
Anybody having solution for this.
GeneralRe: the project is not working in Firefoxmembercxtay28 Feb '11 - 17:23 
Not sure is it appropriate, I make the changes in this javascript function:
 
function FindSelectedItems()
{
var cblstTable = document.getElementById('<%=lstMultipleValues.ClientID %>');
var checkBoxPrefix = "lstMultipleValues_";
var noOfOptions = cblstTable.rows.length;
var selectedText = "";

for(i=0; i < noOfOptions ; ++i)
{
if(document.getElementById(checkBoxPrefix+i).checked)
{
if(selectedText == "")
{ if(document.getElementById(checkBoxPrefix+i).parentNode.innerText != null)
selectedText = document.getElementById(checkBoxPrefix+i).parentNode.innerText;
else
selectedText = document.getElementById(checkBoxPrefix+i).parentNode.textContent
}
else
{
if(document.getElementById(checkBoxPrefix+i).parentNode.innerText != null)
selectedText = selectedText + "," + document.getElementById(checkBoxPrefix+i).parentNode.innerText;
else
selectedText = selectedText + "," + document.getElementById(checkBoxPrefix+i).parentNode.textContent
}
}
}
document.getElementById('<%=txtSelectedMLValues.ClientID %>').value = selectedText;
}
 

And remove this line in .cs file:
 
lstMultipleValues.Attributes.Add("onclick", "FindSelectedItems(this," + txtSelectedMLValues.ClientID + ");");
 

NOTE:
I face some problem in parentNode.innerText and parentNode.textContent,
while IE6, IE7, IE8, IE9, and firefox support differently in this 2 properties.
I do some checking which I think is a bit lame, hope someone can help on this.
GeneralRe: the project is not working in FirefoxmemberRajiv nayan11 Oct '12 - 0:13 
Its working with the help of your code i will cheked on all browser like IE,FF, and CROME.
GeneralRe: the project is not working in FirefoxmemberRajiv nayan11 Oct '12 - 0:16 
<script type="text/javascript">                
            var timoutID;
//           function ShowMList()
//           {
//                 var divRef = document.getElementById("divCheckBoxList");
//                 divRef.style.display = "block";
//                 var divRefC = document.getElementById("divCheckBoxListClose");
//                 divRefC.style.display = "block";
//           }
//          
//           function HideMList()
//           {
//                 document.getElementById("divCheckBoxList").style.display = "none";  
//                 document.getElementById("divCheckBoxListClose").style.display = "none";  
//           }
function ShowMList()
{
   var divRef = document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxList"); //notice the ct100_ prefix!
   divRef.style.display = "block";
   var divRefC = document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxListClose");
   divRefC.style.display = "block";
}
          
function HideMList()
{
   document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxList").style.display = "none";  
   document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxListClose").style.display = "none";  
}
            function FindSelectedItems(sender,textBoxID)
            {        
                  var cblstTable = document.getElementById(sender.id);
                  var checkBoxPrefix = sender.id + "_";
                  var noOfOptions = cblstTable.rows.length;
                  var selectedText = "";
                  //alert(checkBoxPrefix);
                  for(i=0; i < noOfOptions ; ++i)
                  {
                        if(document.getElementById(checkBoxPrefix+i).checked)
                        {
                              if(selectedText == "")
                              {
                                    if(document.getElementById(checkBoxPrefix+i).parentNode.innerText != null)
                                    {
                                          selectedText = document.getElementById(checkBoxPrefix+i).parentNode.innerText;
                                    }
                                    else
                                    {
                                          selectedText = document.getElementById(checkBoxPrefix+i).parentNode.textContent;
                                    }
                              }  
                              else
                              if(document.getElementById(checkBoxPrefix+i).parentNode.innerText != null)
                                    {
                                          selectedText = selectedText + "," + document.getElementById(checkBoxPrefix+i).parentNode.innerText;
                                    }
                                    else
                                    {
                                          selectedText = selectedText + "," + document.getElementById(checkBoxPrefix+i).parentNode.textContent;
                                    }
                        }
                  }
                  document.getElementById(textBoxID.id).value = selectedText;  
            }
      </script>
GeneralSelect Allmemberharishkakani7 Jan '10 - 4:29 
How can i select all the check box items at a time(Can we select all option)
AnswerRe: Select AllmemberSandeep Mewara7 Jan '10 - 22:18 
There can be various ways of adding it.
One would be to add extra row at the top of dataset and based on it click, 'Select all' other items.
 
This would need code changes in handling the checkboxlist control.
GeneralIts not working in the page, which have Master pagememberVishnu Narayan Mishra19 Oct '09 - 1:14 
Hi
 
I tried to debug this code, but unfortunately its not fixed on master page,
Its working fine on normal aspx pages , but when I am using master page with page I did not get the drop down list..
Can any one tries to fix it.
 
Vishnu Narayan Mishra
Software Engineer

AnswerRe: Its not working in the page, which have Master pagememberSandeep Mewara7 Jan '10 - 22:19 
It looks like you need to fix the javascript names to access correct thing in Master page.
GeneralRe: Its not working in the page, which have Master pagememberRajiv nayan11 Oct '12 - 0:18 
<script type="text/javascript">
        var timoutID;
//      function ShowMList()
//      {
//          var divRef = document.getElementById("divCheckBoxList");
//          divRef.style.display = "block";
//          var divRefC = document.getElementById("divCheckBoxListClose");
//          divRefC.style.display = "block";
//      }
//
//      function HideMList()
//      {
//          document.getElementById("divCheckBoxList").style.display = "none";
//          document.getElementById("divCheckBoxListClose").style.display = "none";
//      }
function ShowMList()
{
  var divRef = document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxList"); //notice the ct100_ prefix!
  divRef.style.display = "block";
  var divRefC = document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxListClose");
  divRefC.style.display = "block";
}
 
function HideMList()
{
  document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxList").style.display = "none";
  document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxListClose").style.display = "none";
}
        function FindSelectedItems(sender,textBoxID)
        {
            var cblstTable = document.getElementById(sender.id);
            var checkBoxPrefix = sender.id + "_";
            var noOfOptions = cblstTable.rows.length;
            var selectedText = "";
            //alert(checkBoxPrefix);
            for(i=0; i < noOfOptions ; ++i)
            {
                if(document.getElementById(checkBoxPrefix+i).checked)
                {
                    if(selectedText == "")
                    {
                        if(document.getElementById(checkBoxPrefix+i).parentNode.innerText != null)
                        {
                            selectedText = document.getElementById(checkBoxPrefix+i).parentNode.innerText;
                        }
                        else
                        {
                            selectedText = document.getElementById(checkBoxPrefix+i).parentNode.textContent;
                        }
                    }
                    else
                    if(document.getElementById(checkBoxPrefix+i).parentNode.innerText != null)
                        {
                            selectedText = selectedText + "," + document.getElementById(checkBoxPrefix+i).parentNode.innerText;
                        }
                        else
                        {
                            selectedText = selectedText + "," + document.getElementById(checkBoxPrefix+i).parentNode.textContent;
                        }
                }
            }
            document.getElementById(textBoxID.id).value = selectedText;
        }
    </script>

GeneralRe: Its not working in the page, which have Master pagememberRajiv nayan11 Oct '12 - 0:19 
<script type="text/javascript">
var timoutID;
// function ShowMList()
// {
// var divRef = document.getElementById("divCheckBoxList");
// divRef.style.display = "block";
// var divRefC = document.getElementById("divCheckBoxListClose");
// divRefC.style.display = "block";
// }
//
// function HideMList()
// {
// document.getElementById("divCheckBoxList").style.display = "none";
// document.getElementById("divCheckBoxListClose").style.display = "none";
// }
function ShowMList()
{
var divRef = document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxList"); //notice the ct100_ prefix!
divRef.style.display = "block";
var divRefC = document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxListClose");
divRefC.style.display = "block";
}

function HideMList()
{
document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxList").style.display = "none";
document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxListClose").style.display = "none";
}
function FindSelectedItems(sender,textBoxID)
{
var cblstTable = document.getElementById(sender.id);
var checkBoxPrefix = sender.id + "_";
var noOfOptions = cblstTable.rows.length;
var selectedText = "";
//alert(checkBoxPrefix);
for(i=0; i < noOfOptions ; ++i)
{
if(document.getElementById(checkBoxPrefix+i).checked)
{
if(selectedText == "")
{
if(document.getElementById(checkBoxPrefix+i).parentNode.innerText != null)
{
selectedText = document.getElementById(checkBoxPrefix+i).parentNode.innerText;
}
else
{
selectedText = document.getElementById(checkBoxPrefix+i).parentNode.textContent;
}
}
else
if(document.getElementById(checkBoxPrefix+i).parentNode.innerText != null)
{
selectedText = selectedText + "," + document.getElementById(checkBoxPrefix+i).parentNode.innerText;
}
else
{
selectedText = selectedText + "," + document.getElementById(checkBoxPrefix+i).parentNode.textContent;
}
}
}
document.getElementById(textBoxID.id).value = selectedText;
}
</script>
GeneralRe: Its not working in the page, which have Master pagememberthund3rstruck4 May '10 - 3:59 
This works fine for me in Master Pages. You need to make sure you're accessing the correct div object though because master pages prepend a prefix on controls in the content place holder.
 
Just change these javascript methods:
 
var timoutID;
function ShowMList()
{
  var divRef = document.getElementById("ctl00_divCheckBoxList"); //notice the ct100_ prefix!
  divRef.style.display = "block";
  var divRefC = document.getElementById("ctl00_divCheckBoxListClose");
  divRefC.style.display = "block";
}
    	
function HideMList()
{
  document.getElementById("ctl00_divCheckBoxList").style.display = "none";   
  document.getElementById("ctl00_divCheckBoxListClose").style.display = "none";   
}
 

http://forums.asp.net/p/1239507/2260596.aspx#2260596[^]
 
Hope this helps,
T3
 
To the author, thanks for sharing this great code!
GeneralRe: Its not working in the page, which have Master pagememberer.puneet25 Aug '10 - 21:44 
Hi,
I am using a master page. The Java script is not working in the content page.
I am getting the follwing error:
"Object Required"
 
Please help me.
 
Thanks & Regards,
Puneet Sharma
GeneralRe: Its not working in the page, which have Master pagememberRajiv nayan11 Oct '12 - 0:15 
<script type="text/javascript">                
            var timoutID;
//           function ShowMList()
//           {
//                 var divRef = document.getElementById("divCheckBoxList");
//                 divRef.style.display = "block";
//                 var divRefC = document.getElementById("divCheckBoxListClose");
//                 divRefC.style.display = "block";
//           }
//          
//           function HideMList()
//           {
//                 document.getElementById("divCheckBoxList").style.display = "none";  
//                 document.getElementById("divCheckBoxListClose").style.display = "none";  
//           }
function ShowMList()
{
   var divRef = document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxList"); //notice the ct100_ prefix!
   divRef.style.display = "block";
   var divRefC = document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxListClose");
   divRefC.style.display = "block";
}
          
function HideMList()
{
   document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxList").style.display = "none";  
   document.getElementById("ctl00_ContentPlaceHolder1_divCheckBoxListClose").style.display = "none";  
}
            function FindSelectedItems(sender,textBoxID)
            {        
                  var cblstTable = document.getElementById(sender.id);
                  var checkBoxPrefix = sender.id + "_";
                  var noOfOptions = cblstTable.rows.length;
                  var selectedText = "";
                  //alert(checkBoxPrefix);
                  for(i=0; i < noOfOptions ; ++i)
                  {
                        if(document.getElementById(checkBoxPrefix+i).checked)
                        {
                              if(selectedText == "")
                              {
                                    if(document.getElementById(checkBoxPrefix+i).parentNode.innerText != null)
                                    {
                                          selectedText = document.getElementById(checkBoxPrefix+i).parentNode.innerText;
                                    }
                                    else
                                    {
                                          selectedText = document.getElementById(checkBoxPrefix+i).parentNode.textContent;
                                    }
                              }  
                              else
                              if(document.getElementById(checkBoxPrefix+i).parentNode.innerText != null)
                                    {
                                          selectedText = selectedText + "," + document.getElementById(checkBoxPrefix+i).parentNode.innerText;
                                    }
                                    else
                                    {
                                          selectedText = selectedText + "," + document.getElementById(checkBoxPrefix+i).parentNode.textContent;
                                    }
                        }
                  }
                  document.getElementById(textBoxID.id).value = selectedText;  
            }
      </script>
GeneralThanksmemberFBR28 Jul '09 - 22:21 
Thanks for sharing Smile | :)
AnswerRe: ThanksmemberSandeep Mewara7 Jan '10 - 22:20 
Smile | :)

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 17 Dec 2008
Article Copyright 2008 by Sandeep Mewara
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid