Decrease Font Size
Increase Font Size
   BLOG

ASP.NET Multiple Selection DropDownList with AJAX HoverMenuExtender

ASP.NET Multiple Selection DropDownList

Multiple select DropDownList

Multiple selections in dropdownlist |

multi-select dropdownlist with checkboxes |

Dropdownlist with multiple selection |

How to get the CheckBoxlist Value using Javascript |

ASP.NET AJAX HoverMenuExtender |

Multi select Dropdown list in ASP.NET |

Multiple Selection DropDownList for asp.net |

ASP.NET Multiple Selection DropDownList with AJAX HoverMenuExtender

Update 02/01/2017

select all
deselect all

Added option to select all and deselect all per member request. As usual, you can follow the link to the demo to see the control in action and download the source code.


Result 1 Result 2

Introduction

Recently, I was looking for a multiple selection dropdownlist control for my new project. After spending some time researching for it, I decided to put together all my finding in one web user control. This web user control consists of an ASP.NET AJAX HoverMenuExtender, JavaScript, StyleSheet and CheckBoxListExCtrl . The final product will work with or without a MasterPage and you can drag and drop more than one instances of the control on to the page. This is not a perfect control, feel free to modify it to tailor your requirement and share your thoughts. Below is a step by step tutorial on how I have accomplished this. Hope this tutorial will give someone an idea on how to use ASP.NET AJAX HoverMenuExtender and create multiple selection dropdownlist.

Before we begin, here is the structure of my project.

Project Structure

Using the code

This is a usercontrol, just drag and drop. But make sure you include the ScriptManager.

 

The project includes:

  • Default.aspx – this page do not use master page and user control
  • MS_With_UserControl.aspx – this page use multiple instances of the user control and no master page.
  • MS_With_UserControl_and_Masterpage.aspx – this page use multiple instances of the user control and a master page.
  • CheckBoxListExCtrl - How to get the CheckBoxlist Value using Javascript?
  • The rest of the files are fairly self explanatory.

CheckBoxListExCtrl

The popup panel with a CheckBoxList control will appear whenever the user moves the mouse over the DropDownList. In order to capture the CheckBoxList selected value and text without any complication; I utilized the CheckBoxListExCtrl class by Trilochan Nayak. This class inherits the CheckBoxList property and allows us to access its selected value and text through the JavaScript. The code is pretty much the same except I have made a few changes to return the text of the selected checkbox. Please see the comments.

string clientID = UniqueID + this.ClientIDSeparator + repeatIndex.ToString(NumberFormatInfo.InvariantInfo); //09042009 BT - var

writer.WriteBeginTag("input");
writer.WriteAttribute("type", "checkbox");
writer.WriteAttribute("name", UniqueID + this.IdSeparator + repeatIndex.ToString(NumberFormatInfo.InvariantInfo));
writer.WriteAttribute("id", clientID);
writer.WriteAttribute("value", Items[repeatIndex].Value);
if (Items[repeatIndex].Selected)
	writer.WriteAttribute("checked", "checked");
System.Web.UI.AttributeCollection attrs = Items[repeatIndex].Attributes;
foreach (string key in attrs.Keys)
{
	writer.WriteAttribute(key, attrs[key]);
}
writer.Write("/>"); //09042009 BT - close the input tag 
writer.Write("<label for='" + clientID + "'>"); //09042009 BT - added label to hold the checkbox text
writer.Write(Items[repeatIndex].Text); //text
writer.Write("</label>"); //close label tag

MultipleSelectionDDLCSS.css – style sheet

 

MultipleSelectionDDLJS.js

Here is the content of the JavaScript, please read the comments. The tooltip (title) is displaying correctly in IE 7.0, 8.0, Firefox, and Google Chrome, but not in IE 6.0. In order to remedy the problem, I included a separate function call showIE6Tooltip to show and hide the tooltip. The function getCheckBoxListItemsChecked will return the selected value, text and index of the CheckBoxList in an array. The readCheckBoxList function will takes the CheckBoxListExCtrl, DropDownList and all the hidden fields ClientID as parameters and set the hidden fields value.

/*detect the browser version and name*/
var Browser = {
  Version: function() {
    var version = 999; // we assume a sane browser
    if (navigator.appVersion.indexOf("MSIE") != -1)
      // bah, IE again, lets downgrade version number
      version = parseFloat(navigator.appVersion.split("MSIE")[1]);
    return version;
  }
}

function showIE6Tooltip(e){
    //we only want this to execute if ie6
    if (navigator.appName=='Microsoft Internet Explorer' && Browser.Version() == 6) {
        if(!e){var e = window.event;}
        var obj = e.srcElement;
        
        tempX = event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft);
        tempY = event.clientY + (document.documentElement.scrollTop || document.body.scrollTop);
        
        var tooltip = document.getElementById('ie6SelectTooltip');
        tooltip.innerHTML = obj.options.title; //set the title to the div
        //display the tooltip based on the mouse location
        tooltip.style.left = tempX;
         tooltip.style.top = tempY+10;
        tooltip.style.width = '100%';
        tooltip.style.display = 'block';
      }
    }
    function hideIE6Tooltip(e){
     //we only want this to execute if ie6
       if (navigator.appName=='Microsoft Internet Explorer' && Browser.Version() == 6) {
        var tooltip = document.getElementById('ie6SelectTooltip');
        tooltip.innerHTML = '';
        tooltip.style.display = 'none';
       }
    }

/* get and set the selected checkbox value and 
text and selected index to a hidden field */
function getCheckBoxListItemsChecked(elementId) {
    
    //var
    var elementRef = document.getElementById(elementId);
    var checkBoxArray = elementRef.getElementsByTagName('input');
    var checkedValues = '';
    var checkedText = '';
    var checkedSelIndex = '';
    var myCheckBox = new Array();

    for (var i = 0; i < checkBoxArray.length; i++) {
        var checkBoxRef = checkBoxArray[i];

        if (checkBoxRef.checked == true) {
        
        //selected index
            if (checkedSelIndex.length > 0)
                checkedSelIndex += ', ';
            checkedSelIndex +=i;     
        
        //value
            if (checkedValues.length > 0)
                checkedValues += ', ';

            checkedValues += checkBoxRef.value;

        //text
            var labelArray = checkBoxRef.parentNode.getElementsByTagName('label');

            if (labelArray.length > 0) {
                if (checkedText.length > 0)
                    checkedText += ', ';
                checkedText += labelArray[0].innerHTML;
            }

        }
    }

    myCheckBox[0] = checkedText;
    myCheckBox[1] = checkedValues;
    myCheckBox[2] = checkedSelIndex;

    return myCheckBox;
}

function readCheckBoxList(chkBox, ddlList, hiddenFieldText, hiddenFieldValue, hiddenFieldSelIndex) {
    var checkedItems = getCheckBoxListItemsChecked(chkBox);

    $get(ddlList).options[0].innerHTML = checkedItems[1]; //set the dropdownlist value
    $get(ddlList).title = checkedItems[0]; //set the title for the dropdownlist
    //set hiddenfield value
    $get(hiddenFieldValue).value = checkedItems[1];
    $get(hiddenFieldText).value = checkedItems[0];
    $get(hiddenFieldSelIndex).value = checkedItems[2];
}

MultipleSelection.ascx

In this page, I have HoverMenuExtender, DropDownList, CheckBoxListExCtrl, a few hidden fields and a div to display tooltip information for IE 6.0. And I have added some dummy data to my CheckBoxList so it wouldn't look empty when I drag it into the page.

<div>
    <cc2:HoverMenuExtender ID="HoverMenuExtender1"
      runat="server" TargetControlID="MultiSelectDDL" 
      PopupControlID="PanelPopUp" PopupPosition="bottom" 
      OffsetX="6" PopDelay="25" HoverCssClass="popupHover" />

      <asp:DropDownList ID="MultiSelectDDL" CssClass="ddlMenu regularText" runat="server">
           <asp:ListItem Value="all">Select</asp:ListItem>  
      </asp:DropDownList>
         
      <asp:Panel ID="PanelPopUp" CssClass="popupMenu" runat="server">
          <cc1:CheckBoxListExCtrl ID="CheckBoxListExCtrl1" CssClass="regularText" runat="server">
             <asp:ListItem Value="d1">Dummy 1</asp:ListItem>
             <asp:ListItem Value="d2">Dummy 2</asp:ListItem>
             <asp:ListItem Value="d3">Dummy 3</asp:ListItem>
             <asp:ListItem Value="d4">Dummy 4</asp:ListItem>
             <asp:ListItem Value="d5">Dummy 5</asp:ListItem>
             <asp:ListItem Value="d6">Dummy 6</asp:ListItem>
             <asp:ListItem Value="d7">Dummy 7</asp:ListItem>
             <asp:ListItem Value="d8">Dummy 8</asp:ListItem>
            </cc1:CheckBoxListExCtrl>
       </asp:Panel>
        <asp:HiddenField ID="hf_checkBoxValue" runat="server" />
        <asp:HiddenField ID="hf_checkBoxText" runat="server" />
        <asp:HiddenField ID="hf_checkBoxSelIndex" runat="server" />
</div>   
<div id="ie6SelectTooltip" style="display:none;position:absolute;padding:1px;border:1px solid #333333;;background-color:#fffedf;font-size:smaller;z-index: 99;"> </div>

MultipleSelection.ascx.cs

Here is the code behind for the user control. In the Page_Load method, I added a client script onclick event to the CheckBoxListExCtrl control. The JavaScript function readCheckBoxList will assign the selected value, text and index to the hidden fields. I also added the onmousemove and onmouseout events for the DropDownList control which will show the tolltip for IE6.0. The LoadJScript() and the LoadCSS() method will load the JavaScript and style sheet dynamically with no duplicates. If you drag and drop multiple instances of the control onto the page, it will only register the StyleSheet and JavaScript one time only. Notice that I utilized the ResolveUrl() method so that the usercontrol will never have problem locating the style sheet and JavaScript. /p>

LoadJScript();
LoadCss();
//add onclick attributes, call the readCheckBoxList function with parameters
        CheckBoxListExCtrl1.Attributes.Add("onclick", "readCheckBoxList('" +
                    CheckBoxListExCtrl1.ClientID + "','" + MultiSelectDDL.ClientID + "','" +
                    hf_checkBoxText.ClientID + "','" +
                    hf_checkBoxValue.ClientID + "','" + hf_checkBoxSelIndex.ClientID + "');");

//for IE 6.0
        MultiSelectDDL.Attributes.Add("onmousemove", "showIE6Tooltip();");
        MultiSelectDDL.Attributes.Add("onmouseout", "hideIE6Tooltip();");

I have a method to load the Style Sheet and JavaScript separately with no duplicates, if you drag and drop multiple instances of the control onto the page, it will only register the StyleSheet and JavaScript one time only. Notice that I also included ResolveUrl method so that the usercontrol will never have problem locating the StyleSheet and JavaScript.

//load style css
    internal void LoadCss()
    {
        //prevent loading multiple css style sheet
        HtmlControl css = null;
        if (Session["MultipleSelectionDDLCSSID"] != null)
        {
            css = Page.Header.FindControl(Session["MultipleSelectionDDLCSSID"] as string) as HtmlControl;
        }
       
        if (css == null)
        {
            //load the style sheet
            HtmlLink cssLink = new HtmlLink();
            cssLink.ID = "MultipleSelectionDDLCSSID";
            cssLink.Href = ResolveUrl("~/MS_Control/MultipleSelectionDDLCSS.css");    
            cssLink.Attributes.Add("rel", "stylesheet");
            cssLink.Attributes.Add("type", "text/css");

            // Add the HtmlLink to the Head section of the page.
            Page.Header.Controls.Add(cssLink);
            Session["MultipleSelectionDDLCSSID"] = cssLink.ID;
        }
    }
    //load the javascript
    internal void LoadJScript()
    {
        ClientScriptManager script = Page.ClientScript;
        //prevent duplicate script
        if (!script.IsStartupScriptRegistered(this.GetType(), "MultipleSelectionDDLJS"))
        {
            script.RegisterStartupScript(this.GetType(), "MultipleSelectionDDLJS",
            "<script type='text/javascript' src='"+ResolveUrl("~/MS_Control/MultipleSelectionDDLJS.js") +"'></script>");
        }
    } 

MS_With_UserControl_and_Masterpage.aspx

<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Label ID="Label1" CssClass="regularText" runat="server" Text="Month:" />
<uc1:MultipleSelection ID="MultipleSelection1" runat="server" />

MS_With_UserControl_and_Masterpage.aspx.cs - How to bind the data

DataTable dt = new DataTable();

DataColumn dcValue = new DataColumn("Value", typeof(string));
DataColumn dcText = new DataColumn("Text", typeof(string));

dt.Columns.Add(dcText);
dt.Columns.Add(dcValue);

DataRow dr;
dr = dt.NewRow();
dr["Text"] = "January";
dr["Value"] = "m1";
dt.Rows.Add(dr);
…
//datasource, dataTextField, dataValueField
 MultipleSelection1.CreateCheckBox(dt, "Text", "Value");

How to set selected value

MultipleSelection1.selectedIndex = "1,5,7";

How to get the SelectedIndex, SelectedValue, SelectedText

MultipleSelection1.sText;
MultipleSelection1.sValue;
MultipleSelection1.selectedIndex;

Points of Interest

For some reason I didn't load the ScriptManager dynamically. So, make sure you include a ScriptManager on the page before using the usercontrol or you will come across this error message: "The control with ID 'HoverMenuExtender1' requires a ScriptManager on the page. The ScriptManager must appear before any controls that need it."

 

" Invalid postback or callback argument. Event validation is enabled using…". Initially, I was trying to modify the value of the dropdownlist through the JavaScript and I kept getting the error whenever I hit the submit button. The easiest solution was to set the EnableEventValidation = false on the page directive, but instead, I found another work around by using hidden field.

 

The tooltip (title) were displaying correctly on IE 7.0, 8.0, FireFox and Google Chrome but not in IE6.0. In order to remedy the problem, I included a separate function to show and hide the tooltip.

I am using a CheckBoxList controls and having difficulty to get the CheckBoxList value and text using JavaScript. After conducting some research, I came across a class library by Trilochan Nayak. I have modified his class so that I can retrieve the value and text of the selected checkbox through the JavaScript.

 

Resources

How do you get the value from a CheckBoxList using JavaScript
How to get the CheckBoxlist Value using Javascript?
Easiest way to check IE version with JavaScript
How to display tooltip for Select control in HTML?
Injecting Client-Side Script from an ASP.NET Server Control
How Do I: Use the ASP.NET AJAX HoverMenu Extender?

 

Watch this script in action

Demo

Downloads

Download

Comments (29) -

  • Aion Powerleveling

    9/5/2009 7:39:17 PM |

    This is the best post on this topic i have ever read.


    Regards

    ricky

  • Aion Powerleveling

    9/6/2009 3:41:51 AM |

    Wonder full writing skills you got mate.


    Regards

    katiz

  • Ken Hull

    9/13/2009 2:20:21 PM |

    This looks great.  Just a thought though,  any chance this could be combined with the cascading combobox concept?
    Say for athletics meet,  first choose the disciplines offered (track, field BUT not raod) then the events based on this selection ([100m, 200m BUT not 1000m] , [javelin, shotput]) etc.

      

  • Michael Haren

    9/15/2009 3:43:09 PM |

    What is the license for this?

  • Deepak

    9/23/2009 3:25:21 PM |

    This is really what we required from a long time, thanks for such a nice post.

  • Pham Son

    9/30/2009 2:55:19 AM |

    Thanks this post.

  • traslochi internazionali milano

    10/8/2009 9:59:29 PM |

    This post is really interesting and helpful.Thanks for sharing.

  • Yachika Verma

    10/8/2009 10:36:43 PM |

    I run a blog called content writer online. Your blog post has really helped me. Thanks a lot.

  • Bibiana Zuluaga

    12/6/2009 11:58:55 AM |

    thanks a lot for the post...

    I need help:

    How to add an event to the DropDownList to charge another DropDownList depending of the first DropDown.

    Sample:
    Cuntry and Regions

    Multiselect Country and charge Regions of the Country selecteds

  • bill,rony

    12/8/2009 12:25:49 AM |

    great your site very inspirition ,make me many good idea for my job,as interior designer,thank for article and image.

  • bryian

    12/11/2009 7:44:38 AM |

    Bibiana Zuluaga,

    Sorry, the current version do not have the features you mentioned.

    Thanks,
    Bryian Tan

  • peninggi badan

    12/28/2009 1:13:57 PM |

    I am grateful to you ...
    now I'm back burning passion ....
    it's all because of your article ....
    very easy to understand and interesting ...
    I will learn a lot from you ..

  • Auto Loans

    12/30/2009 1:55:29 AM |

    I am trying to figure out the code. Good example by the way.

  • batu permata

    1/9/2010 8:05:07 PM |

    I really needed this example
    great post
    me and my friends will come back to see your other articles

  • overseas removals

    1/20/2010 5:15:46 AM |

    How long have you been in this field? You seem to know a lot more than I do, I’d love to know your sources!

  • live jasmine

    1/28/2010 6:38:24 PM |

    Aw, this was a really quality post. In theory I'd like to write like this too - taking time and real effort to make a good article... but what can I say... I procrastinate alot and never seem to get something done

  • Online Tutoring

    2/6/2010 11:36:20 PM |

    Interesting blog. Actually google made searching of information easy on any topic. Well keep it up and post more interesting blogs.

  • Yachtcharter Griechenland

    2/19/2010 4:28:51 AM |

    That's great, I never thought about ASP.NET Multiple Selection DropDownList with AJAX HoverMenuExtender like that before.

  • nowGoogle.com Adalah Multiple Search Engine Popular

    2/25/2010 3:09:11 AM |

    thank you for share it

  • wow gold

    2/25/2010 6:51:33 PM |

    good

  • laptop sale     

    3/1/2010 1:04:02 AM |

    good work…unique site and interesting too… keep it up…i am looking forward for more updates.

  • locali notturni roma

    3/2/2010 11:32:01 PM |

    Love your blog I'm going to subscribe

  • Breanne

    3/20/2010 3:50:24 PM |

    I downloaded your project. Could you show me how to disable the actual drop down from droping down and only have the hover menu work when you pass the mouse over it? Users tend to "click" everything and I think the dropdown part might be less confusing if it didn't still drop down when clicked.

    Thanks!

  • Mazda

    6/5/2010 11:12:55 AM |

    This post is really interesting and helpful.Thanks for sharing.

  • sssssonya

    7/14/2010 5:25:38 PM |

    great post

  • Yachtcharter Griechenland

    9/28/2010 7:48:48 PM |

    I really appreciate your professional approach. These are pieces of very useful information that will be of great use for me in future.

  • flowers to poland

    11/26/2010 10:35:52 PM |

    Great post. It really contains valuable information. Thanks for sharing!

  • Mozoot

    1/15/2011 12:38:36 AM |

    Interesting post! Thanks for writing and sharing informative post!
    I appreciate it...

Pingbacks and trackbacks (1)+

Add comment

Loading