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

MultiSelect Dropdown Control

, 25 Feb 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
This simple and lightweight control allows the user to select multiple items from a dropdown list of checkbox items.

MSDD_Control.jpg

Introduction

It’s an Internet era where everything is coming to the Internet. Nowadays, users seem to be more diverted towards online purchasing than ever before. Day by day, it’s getting harder for companies to make their online users happy because of tough competition. One thing which is common across all websites on the Internet in terms of getting more and more hits and making their Internet shop successful is their use of state of the art web tools and controls, and the way they are presented on the web page along with other information.

Visual Studio .NET comes with a wide range of web server controls. These controls possess DHTML characteristics (e.g. Autopostback and EnableSessionState), and at the same time are easy to use. They also require less space to present a bunch of information on the web page. Two of these controls are DropdownList and CheckboxList. Both of the controls are powerful and rich in functionality in the sense that they provide efficient ways to add and delete individual items, exhibit multi-select functionality, and also have a DataSource property which makes them qualify as data bound controls. One limitation which is common in both the controls is the way they display information on the page. In comparison to other controls, they take relatively more space to render information. But, now we have got to a stage where companies are tying up with other companies and trying to get involved in more than one businesses. They like to see as much content on their site as possible. They can't afford controls which take a huge amount of space just to display one type of information.

When I got into the same situation where I had to create a search page having 15 to 20 search filters and each with more than 25 items, I decided not to occupy the whole page with list boxes or checkbox lists, but to develop a user control that would not only display a full list of checkbox items but will also act as a dropdown.

About the User Control

It’s an easy to use and lightweight control. The code is also fairly simple to understand. I have developed it using .NET and C# on the server side and JavaScript for client side scripting. Although it’s not a full blown web server control, it does provide with some useful features that help users in displaying and managing information on the page easily. Following is a small list of those features:

  • Autopostback
  • A property by which the page will be posted back to the server automatically on firing the OnSelectedItem event, which will happen only when the value of this property is set to true and the toggle on/off button is pressed.

  • EnableViewState
  • A property that says whether the current value of the control must be saved in the __VIEWSTATE hidden field and restored during a page postback. For this control, to display the list of selected options, I have used the ASP.NET TextBox control that will take care of the view state for our control.

  • DataSource
  • Through this property, the control gets or sets the data source which is of type DataTable. It makes the control a true data bound control. Other than this property, the control also supports DataTextField and DataValueField, similar to that of a standard dropdownlist control, for text content of the list items and the value of each list item, respectively.

  • Z-Index
  • This property sets the stack order of our user control. It is very useful when more than one instance of the control are going to be used on the same page. Since the control expands in the downward direction, an instance with greater stack order is always in front of an instance with lower stack order.

    MSDD_Overlap.jpg

  • Expand/Collapse

  • Just like a normal dropdown list control, this user control can be collapsed automatically by clicking anywhere on the page or on the control itself, except on the region which displays the selection list. This is because of the fact that the user might want to select more than one item.

  • Selected Options

  • On postback, a control will pass its current state to the server in the form of a comma separated list which can be used for further processing.

Using the Code

Using this control in your ASP.NET project is fairly simple as it gets or sets everything through properties it exposes. On the page, it first needs to be registered, which can be done by pasting the following line on top of your ASPX page:

<%@ Register TagPrefix="DDMS" 
    TagName="MultiSelectDropDown" Src="MultiSelectDropDown.ascx" %>

After the registration is done, the control can be initialized by pasting the following code anywhere on the page but within the HTML body. It’s important to note that in the attached demo project, I have encapsulated the control inside <DIV> tags which is not required, of course but, as I mentioned above, to avoid z-index problems, it’s better to enclose it with <DIV> and give it an z-index value based on the order of appearance on the page.

<div id="divMultiSelectDropDown1" 
     style="Z-INDEX: 101; LEFT: 20px; POSITION: absolute; TOP: 20px">
   <ddms:multiselectdropdown id="MultiSelectDropDown1" runat="server">
   </ddms:multiselectdropdown><br>
   <br>
</div>

<div id="divMultiSelectDropDown2" 
     style="Z-INDEX: 100; LEFT: 20px; POSITION: absolute; TOP: 60px">
   <ddms:multiselectdropdown id="Multiselectdropdown2" runat="server">
   </ddms:multiselectdropdown>
</div>

That’s all from the ASPX side. It’s time to write a bit of server-side code. To load and configure the control, the following lines of code can be pasted in the Page_OnLoad event. Two separate instances of the control, MultiSelectDropDown1 and MultiSelectDropDown2, are being used in the code below. CallingPage is a property exposed by the control that will supply a reference of the host page to the control. By using this reference, the user control will emit the necessary code for the __doPostBack method.

protected void Page_Load(object sender, System.EventArgs e)
{
    if(!this.IsPostBack)
    {
        this.MultiSelectDropDown1.DataSource = GetCurrencyDataSource();
        this.MultiSelectDropDown1.DataTextField = "Description";            
        this.MultiSelectDropDown1.DataValueField = "CurrencyID";

        this.MultiSelectDropDown1.AutoPostBack = true;
        this.MultiSelectDropDown1.DataBind();                            

        this.Multiselectdropdown2.DataSource = GetEmployeeDataSource();
        this.Multiselectdropdown2.DataTextField = "EmpName";
        this.Multiselectdropdown2.DataValueField = "EmpID";
                
        this.Multiselectdropdown2.AutoPostBack = false;
        this.Multiselectdropdown2.DataBind();    
    }
    
    this.MultiSelectDropDown1.CallingPage = this;
    this.Multiselectdropdown2.CallingPage = this;

    this.MultiSelectDropDown1.OnItemsSelected += 
      new MultiSelectDropDownDelegate(MultiSelectDropDown1_OnItemsSelected);
}

One last thing is to register the OnSelectedItem event and to provide its event handler. For event arguments, I have created a separate class with the name MultiSelectDropDownItemSelectedEventArgs. That will wrap the arguments (__EVENTARGUEMNT) and pass them to the event handler. The demo project will give you the output shown below:

private void MultiSelectDropDown1_OnItemsSelected(object sender, 
             MultiSelectDropDownItemSelectedEventArgs args)
{
    this.tbSelectedFullText.Text = string.Empty;
    this.tbSelectedOptionsValue.Text = string.Empty;
    this.lbSelectedItemList.Items.Clear();

    this.tbSelectedOptionsValue.Text = args.SelectedOptionValueText;
    this.tbSelectedFullText.Text = args.SelectedOptionText;
    foreach(string selectedOption in args.SelectedOptionList)
        this.lbSelectedItemList.Items.Add(selectedOption);
}

MSDD_ResultView.jpg

Scope

Before I actually started working on the control, like most other developers, I tried to find a control with the similar look and functionality on the internet to support code re-usability (you know what I mean Wink | ;) . After failing to do so, I decided to take on this endeavor myself and for those who might be interested in using it in their projects.

As far as the scope of the control is concerned, it can be extended to both versions of .NET (1.1 and 2.0). Note that, not only web pages but also other user controls can host this user control.

Points of Interest

I would like to comment on a few things that I learned, and a few small problems I faced while writing this control.

  • CheckBoxList and <ASP:CheckBox> were not the right choice:

  • It took some of my time to decide which control I will use to display the list of checkboxes, because CheckBoxList doesn't provide any facility to set the attributes for its individual items. Even the server side <ASP:Checkbox> was not a feasible option as it doesn't have a Value property unlike an HTML checkbox.

  • UserControl's CLIENTID

  • It’s important to remember that while developing a user control that will act as a container for other child controls and will have multiple instances on a page, always access child controls by concatenating their IDs with that of the parent control.

  • __doPostBack , EVENTARGUMENT and EVENTTARGET
  • I had to write my own version of __doPostBack because the default version of __doPostBack is available if and only if there is at least one .NET built-in server control on a page. Since our user control was going to act as a server side control in itself, I couldn't rely on the __doPostBack generated by other .NET server controls as they might or might not be present on the page at all.

Below are some of the features I would like to see in the control. I would be glad If anyone out there upgrades the control by implementing the following features; otherwise, I will do it myself whenever time permits me (which means never!!)

  • Add method for the Items collection, i.e., Items.Add().
  • Changing the orange color for OnMouseOver to the Windows default 'blue' color.
  • Ability to change the size of the control through a property.
  • Postback through AJAX.

Update 1.1

  1. Firefox support has been added.
  2. VB.NET version added in the attached demo project (only the main file with the name "MultiSelectDropDown.ascx.vb").
  3. All style related code is now separated from HTML. A new CSS file has been added to increase performance and speed.

License

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

Share

About the Author

m_irfan
Software Developer (Senior) The Hiring Solutions Company
Pakistan Pakistan
Irfan is currently working as a Systems Analyst with one of the largest E-Recruitment solutions provider in the ME region. He has been in the Software industry for 5 years now. He started his careers with C++ and VB, slowly moved onto open source development (LAMP) and now consistently working on all Microsoft technologies. He specializes in .NET and loves to work on lightweight platforms/tools like JavaScript, XHTML, HTML, JQuery etc. He believes in changing his course of development as the technology advances. You can reach him on his blog (http://irfaann.blogspot.com) where he shares his views and experiences with software design and development.

Comments and Discussions

 
QuestionRepeater1 PinmemberBruce Palmer10-Aug-13 1:10 
QuestionShowing error on click event...Saying Object not found SHMulSel PinmemberSanjaykmurali28-Nov-12 5:39 
QuestionNullReferenceException -- object reference not set to instance of object Pinmembervsnewcomer25-Apr-12 11:21 
QuestionControlClientID&#39; is ambiguous because multiple kinds of members with this name exist in class Pinmemberchrisbonk14-Jan-12 10:46 
QuestionHow can I get it to work in .VB ? Help! Pinmemberchrisbonk13-Jan-12 20:00 
GeneralI get messages like "Microsoft JScript runtime error: Object expected" PinmemberRoshan Purohit13-Jun-11 9:26 
AnswerError when publishing [modified] PinmemberMember 77569633-Jun-11 5:52 
GeneralAbout SelectAll PinmemberMember 77569632-Jun-11 13:08 
GeneralMy vote of 5 Pinmemberyux00827-Jan-11 21:20 
GeneralRe: My vote of 5 PinmemberSheeraz Raza6-Feb-11 22:18 
GeneralIssues in control PinmemberSheeraz Raza4-Jan-11 23:54 
GeneralMy vote of 5 Pinmemberjayendrasinh1-Jan-11 3:20 
QuestionHow to embed Control in application? Which files are needed to place in application? Pinmembersheerazraza26-Dec-10 1:38 
AnswerRe: How to embed Control in application? Which files are needed to place in application? Pinmemberm_irfan27-Dec-10 9:03 
GeneralRe: How to embed Control in application? Which files are needed to place in application? Pinmembersheerazraza29-Dec-10 2:40 
GeneralIrfan Pinmemberabhinav8647-Dec-10 8:05 
GeneralRe: Irfan Pinmemberm_irfan11-Dec-10 1:23 
GeneralRe: Irfan PingroupSyed Rehman24-Feb-14 19:43 
GeneralNeed a select All in the checkboxes Pinmemberabhinav8645-Dec-10 20:09 
GeneralUsing SQL datasource Pinmemberabhinav86410-Nov-10 14:12 
GeneralRe: Using SQL datasource Pinmemberm_irfan12-Nov-10 12:28 
GeneralMy vote of 4 PinmemberInOneSpot22-Jul-10 9:32 
GeneralI can't get it working in my project PinmemberInOneSpot21-Jul-10 13:10 
GeneralRe: I can't get it working in my project Pinmemberm_irfan21-Jul-10 22:47 
GeneralRe: I can't get it working in my project PinmemberInOneSpot22-Jul-10 3:00 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 26 Feb 2009
Article Copyright 2008 by m_irfan
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid