Click here to Skip to main content
15,860,861 members
Articles / Web Development / HTML

MultiSelect Dropdown Control

Rate me:
Please Sign up or sign in to vote.
4.24/5 (18 votes)
25 Feb 2009CPOL7 min read 329.8K   17.2K   80   72
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:

ASP.NET
<%@ 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.

ASP.NET
<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.

C#
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:

C#
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 ;). 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)


Written By
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

 
GeneralRe: __doPostBack Pin
m_irfan5-Dec-09 2:48
m_irfan5-Dec-09 2:48 
GeneralControl off focus mechanism Pin
smitaa24-Sep-09 3:45
smitaa24-Sep-09 3:45 
GeneralRe: Control off focus mechanism Pin
m_irfan3-Oct-09 7:19
m_irfan3-Oct-09 7:19 
GeneralUable to have multiple control in the same page. Pin
pingustar13-Sep-09 20:49
pingustar13-Sep-09 20:49 
GeneralObject reference not set to an instance of an object. Pin
Ana D.13-Aug-09 9:31
Ana D.13-Aug-09 9:31 
GeneralRe: Object reference not set to an instance of an object. Pin
m_irfan14-Aug-09 0:44
m_irfan14-Aug-09 0:44 
GeneralCan't select the item Pin
daraseng23-Jun-09 15:44
daraseng23-Jun-09 15:44 
QuestionMeasures is neither a DataColumn nor a DataRelation for table DefaultView. Pin
Ramy Mahrous22-Feb-09 1:11
Ramy Mahrous22-Feb-09 1:11 
I used it, and my datasource is OLAP
My code works fine with CheckBoxList but when I use your control I got an exception "Measures is neither a DataColumn nor a DataRelation for table DefaultView"

yourControl.DataSource = DimUserStatusDataSource;
yourControl.DataTextField = "[Measures].[ParameterCaption]";
yourControl.DataValueField = "[Measures].[ParameterValue]";
yourControl.DataBind(); // The exception raises here

AnswerRe: Measures is neither a DataColumn nor a DataRelation for table DefaultView. Pin
Ramy Mahrous23-Feb-09 21:28
Ramy Mahrous23-Feb-09 21:28 
GeneralRe: Measures is neither a DataColumn nor a DataRelation for table DefaultView. Pin
m_irfan24-Feb-09 22:56
m_irfan24-Feb-09 22:56 
GeneralRe: Measures is neither a DataColumn nor a DataRelation for table DefaultView. Pin
Ramy Mahrous24-Feb-09 23:09
Ramy Mahrous24-Feb-09 23:09 
GeneralRe: Measures is neither a DataColumn nor a DataRelation for table DefaultView. Pin
m_irfan25-Feb-09 7:14
m_irfan25-Feb-09 7:14 
GeneralRe: Measures is neither a DataColumn nor a DataRelation for table DefaultView. Pin
Ramy Mahrous26-Feb-09 0:06
Ramy Mahrous26-Feb-09 0:06 
GeneralRe: Measures is neither a DataColumn nor a DataRelation for table DefaultView. Pin
Ramy Mahrous26-Feb-09 0:24
Ramy Mahrous26-Feb-09 0:24 
GeneralIs it possible to include "Select ALL"option Pin
a_varanasi20-Feb-09 1:20
a_varanasi20-Feb-09 1:20 
GeneralProblem with postback Pin
hanhnd17-Feb-09 16:03
hanhnd17-Feb-09 16:03 
GeneralRe: Problem with postback Pin
m_irfan18-Feb-09 9:14
m_irfan18-Feb-09 9:14 
QuestionIs that working to add the control inside the datagrid? Pin
D.Zhao4-Feb-09 15:27
D.Zhao4-Feb-09 15:27 
AnswerRe: Is that working to add the control inside the datagrid? Pin
m_irfan6-Feb-09 4:57
m_irfan6-Feb-09 4:57 
QuestionStep by Step explanation of the creating a Dropdown control with checkbox Pin
Sachin Mohanty23-Jul-08 7:29
Sachin Mohanty23-Jul-08 7:29 
QuestionSample WebForm1 in VB? Pin
Jay Gamblin26-Jun-08 8:37
Jay Gamblin26-Jun-08 8:37 
AnswerRe: Sample WebForm1 in VB? Pin
m_irfan27-Jun-08 11:58
m_irfan27-Jun-08 11:58 
GeneralNot working in Firefox, Safari Pin
ppp_dimple6-Jun-08 6:26
ppp_dimple6-Jun-08 6:26 
GeneralRe: Not working in Firefox, Safari Pin
ppp_dimple6-Jun-08 8:04
ppp_dimple6-Jun-08 8:04 
GeneralRe: Not working in Firefox, Safari Pin
m_irfan6-Jun-08 11:59
m_irfan6-Jun-08 11:59 

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

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