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

Multiselect DropDown ListBox Control for Web Applications

By , , 3 Dec 2008
 
MultiSelect-DropDown

Introduction

The developer community has come across many scenarios where the customer would like to make multiple choices and the developer wishes to make intelligent usage of screen space. The objective of "multi select drop down list" (MSDD) control is to allow the user to select multiple options as in a check box list that behaves like a dropdown list. The multi select dropdown list (MSDD) will consume the space as of a dropdown list and deliver the functionality of a Check Box list.

Motivation Factor

By default, the .NET web programmers go by using the ListBox control with multi select option or the checkbox list. No doubt many of us would have felt the need to integrate the dropdown list and the checklist box. We have done just that in this article.

Features

This user control is built using C# as server side and JavaScript for client side scripting. The following lists the unique features:

  1. Ability to select multiple items
  2. Ability to attach JavaScript functions to check/uncheck events
  3. Higher z-index compared to the other web controls such as Listbox and dropdown which have relatively higher Z-index than the normal web controls. This prevents the Listbox/dropdown list in a page overriding the multi select dropdown panel.
  4. Highlight property - highlights the item when the mouse hovers over the item. The highlight color is fixed
  5. Filter property - moves to the item with the alphabet keyed, only when the scroll bar appears

About the Control

Important Properties

  1. Client scripts can be added using attributes to the control
  2. The selected items can be read as either comma separated values or as array list. The selected items will also be displayed by the tooltip.
  3. The text "All" and "Please select" will be displayed when all the options are selected or none selected respectively. 
  4. Hooking the event handlers.

Usage Flow

Initialising the Control

The control has to be initialized on page load, if the properties size, colors, etc. are set at runtime rather than at design time.

  private void InitialiseDropDownControls()
        {
            // To set the background colors
            // multiselect_foodItems.TextBoxBackColor = 
			System.Drawing.Color.FromName("#FFFFE6");
            // multiselect_foodItems.DropDownBackColor = System.Drawing.Color.Aqua;
            // Set the height and width of dropdown controls.
            // The default size is set in pixels.
            multiselect_foodItems.Width = 160;
            multiselect_foodItems.Height = 15;

            multiselect_Juices.Width = 160;
            multiselect_Juices.Height= 15;
//Any attributes to be added to the checkboxlist.
//These events will be performed ahead of the default events that come with the control
            multiselect_foodItems.AddAttribute("onclick", "alert('test');");
        }

Setting the Datasource 

The multiselect drop-down supports the dataset and the list items as the data source. It is not yet tested with other data sources such as object, XML, etc.

private void LoadData()
        {
            //Binding the Dataset as the datasource
            multiselect_foodItems.DataSource = GetFoodItems().Tables[0];
            multiselect_foodItems.DataTextField = "FoodItems";
            multiselect_foodItems.DataBind();
            // Using the list item to add items
            multiselect_Juices.Items.Add("Apple");
            multiselect_Juices.Items.Add(new ListItem("Orange"));
            ListItem item = new ListItem("Grapes");
            multiselect_Juices.Items.Add(item);
        }

Attaching Scripts

The JavaScript functions can be attached to the check/uncheck event as follows:

 multiselect_foodItems.AddAttribute("onclick", "alert('test');"); 

Any events that are added to the default events (those that come along with the control such as the "onclick" event) will be performed after the default event. This will help the user to perform actions apart from the defaults. For e.g.: Enable another control based on the value selected.

Collapse dropdown

The dropdown opens up when user clicks anywhere on the control and is hidden when the user clicks anywhere outside the control.

Events

The server side event handler for checkbox selected item change has been provided. The event has to be hooked on the containing class as follows:

multiselect_Juices.OnMSDDSelectedIndexChanged += 
	new Controls.MultiselectDropDownListBox.OnList_SelectedIndexChangedEventHandler
	(multiselect_Juices_OnMSDDSelectedIndexChanged);

multiselect_Juices_OnMSDDSelectedIndexChanged is the method that will be invoked on the event.

Changing the Highlight Color

If the user is interested in changing the highlight color, he can do so in the style sheet class itemSelected.

Challenges Faced

Why CheckBoxList Rather than Adding the HTML Checkbox at Runtime?

Initially, we thought of constructing a dynamic checkbox within a div on the server side and display/hide the div on click events. However, we realized that we will have problems in retaining state, for server side operations and will need to loop through the items when bound to the dataobjects. Hence, the checkbox list was chosen which will make things easier.

Attributes of ListItem

In .NET Frameworks 1.0 and 1.1, the attributes added to the listitem are not rendered. This is a bug with all the controls using the listitem. This had to be circumvented while the page is rendered. In .NET Framework 2.0, this has been rectified and the attributes of the listitem are rendered. However, when the dataset or any other datasource is bound to the checkbox list, item highlight "onmouseover" and to check/uncheck items when clicked anywhere on the item (not specifically on the label/checkbox) will need to be handled while the control is rendered.

Positioning of the CheckBoxList

The positioning of the checkbox list to be in alignment with the textbox has been calculated based on the offsetLeft of all its parents, but cannot be guaranteed for accuracy in all cases. For proper positioning, if the control is placed inside HTML tables, remember to set the cellpadding and cellspacing attributes. When these attributes are set to values other than zero and you feel that the checkbox list does not align with the textbox, try modifying the curleft variable set in the Left function in MultiselectListBox.js file. Please note that this is valid only when the "RepeatLayout" property of the checkbox list has been set to "Table" (default value of the control).

if(obj.parentElement.tagName.toUpperCase() == "TABLE")
	{
	        curleft -= Number(obj.parentElement.getAttribute('cellspacing'));
	        curleft -= Number(obj.parentElement.getAttribute('cellpadding'));
	}

Higher Z-index for the Checkboxlist Control

When the div is positioned dynamically, the checkboxlist inside the div is overridden by controls such as the listbox which are actually placed beneath the div and the containing checkboxlist. To overcome this issue, an iframe was positioned as the div, so that the div gets a higher z-index value. The iframe overrides the listbox control and hence the div and the checkboxlist are shown. Here the src of the iframe is not set.

Enhancements

A MultiselectEventArgs derived from EventArgs can be used. This can hold the list of selected items and its corresponding indexes.

The code has been tested only on Internet Explorer. It needs changes to make it compatible with other browsers.

History

  • Version - v1.1. - Fixed the scrolling issue

License

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

About the Authors

Saleena
India India
Member
No Biography provided

Thangavel Murugesan
Software Developer iNautix Technologies India Pvt Ltd
India India
Member
No Biography provided

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   
GeneralMy vote of 1memberziaalam22 Feb '12 - 23:26 
childish control with no browser compatibility
GeneralMultiselect DropDown ListBox Control for Web Applicationsmembermmdba2 Aug '10 - 12:09 
Hi,
could you send me source code VS 2008. the current code is not opening..
 
REg
Benne
5mm.dba@gmail.com
 
Multiselect DropDown ListBox Control for Web Applications
By Saleena, Thangavel Murugesan | 4 Dec 2008
GeneralMultiselect combobox - simpler solutionmemberlianaent4 Dec '09 - 8:55 
There's a much simpler solution to achieving this result. I haven't fully tested it yet, but the functionality is exactly like window forms multiselect comboboxes.
 
All I did was add to my form a read-only textbox and a normal web listbox with display = "none" and selectionmode = multiple. The textbox attributes are set to onclick = hide textbox, show listbox, and the listbox to onblur = show textbox, hide listbox, and display in the textbox the listbox's chosen values.
 
The code is very simple, but if anyone wants it I'll provide it. It works beautifully!
GeneralRe: Multiselect combobox - simpler solutionmemberK_kevin483353 Sep '10 - 7:19 
Can u send the code for your simple solution?
QuestionDatasetmemberDanielHH27 Nov '08 - 7:20 
I am trying to get the data from a dataset but the "All" option disapear everytime that I add this code
 
DataFactory _oDF = new DataFactory();
_oDF.StatementName = "spLadderRegion";
DataSet _Ds = _oDF.GetDataSet();
RegionList.DataSource = _Ds.Tables[0];
RegionList.DataTextField = _Ds.Tables[0].Columns["Region"].ColumnName.ToString();
RegionList.DataBind();
 
The only way that I get it back is by adding the options using this, but I don't want to add every item statically.Any suggestion?
 

RegionList.Items.Add("Brazil");
RegionList.Items.Add("Canada");
 
Thanks,
 
Daniel HH

AnswerRe: DatasetmemberSaleena29 Nov '08 - 1:29 
Thanks for raising the issue. Currently, the "All" item appears when we add individual listitems. However, there are two ways to achieve what you are trying for:
 
1. RegionList.Items.InsertItem at index 0 adter the dataset has been bound in your code.
2. Modify the source code when the dataset is set.
perform step 1 at the datasource property in source code (i.e) at Multiselect.aspx.cs file as below
 
public object DataSource
{
get { return MSDDLB_cblst.DataSource; }
set
{
MSDDLB_cblst.DataSource = value;
// Bind the data and insert All item here
}
}
 


 
Let us know if you have any more problems
QuestionRe: DatasetmemberDanielHH29 Nov '08 - 5:00 
First of all, thanks for your help on this. I followed step one by doing the following but for some reason I got the word "Region" in the dropdown list instead of the list of countries that I have in my table. Also I used Items.Insert because I didn't find InsertItem that you mentioned.
 
DataFactory _oDF = new DataFactory();
_oDF.StatementName = "spLadderRegion";
DataSet _Ds = _oDF.GetDataSet();
multiselect_Juices.Items.Insert(0, _Ds.Tables[0].Columns["Region"].ColumnName.ToString());
multiselect_Juices.DataBind();
 
Also I tried step two but I am missing something because I got an error that says "Object reference not set to an instance of an object".
 
private void LoadData()
{
multiselect_Juices.Items.Insert(0,DataSource.ToString());
 
}
 
public object DataSource
{
get { return multiselect_Juices.DataSource; }
set
{
multiselect_Juices.DataSource = value;
// Bind the data and insert All item here
DataFactory _oDF = new DataFactory();
_oDF.StatementName = "spLadderRegion";
DataSet _Ds = _oDF.GetDataSet();
multiselect_Juices.DataTextField = _Ds.Tables[0].Columns["Region"].ColumnName.ToString();
multiselect_Juices.DataBind();
 
}
}
 
Thanks again for your help.
Daniel
 
Daniel HH

AnswerRe: DatasetmemberSaleena29 Nov '08 - 20:40 
Hi Daniel,
 
can you please try this piece of code below. you need not modify anything the datasource property in the multiselect.aspx.cs file.
DataFactory _oDF = new DataFactory();
_oDF.StatementName = "spLadderRegion";
DataSet _Ds = _oDF.GetDataSet();
multiselect_Juices.DataSource = _Ds;
multiselect_Juices.DataBind();
multiselect_Juices.Items.Insert(0,"All");
 
Thanks,
Saleena
GeneralRe: DatasetmemberDanielHH30 Nov '08 - 10:00 
Saleena,
 
I really apreciate your help on this. The dropdownlist is working great! Big Grin | :-D
 
Thanks again,
Daniel H
 
Daniel HH

GeneralRe: DatasetmemberSaleena30 Nov '08 - 20:12 
Glad to know that its working fine!!! Hope its of some use to you!! Poke tongue | ;-P
QuestionRe: DatasetmemberDanielHH2 Dec '08 - 7:12 
Saleena,
 
Hi, I was finishing a program and I noticed that dropdownlist sometimes blocks and then I noticed that I can unblock if I move the scroll to the top. Then I checked your default.aspx and I changed the height of the field set from 413px to 913px and I moved the scroll down a bit and I was not able to expand the dropdownlist until I moved it back to the top.
Any suggestion?
 
Thanks in advance,
Daniel H
 
Daniel HH

AnswerRe: DatasetmemberSaleena3 Dec '08 - 6:57 
Hi Daniel..Ya thats right, we noticed that too and we have fixed that issue, will soon upload the next version. else its only a small change in the javascript part - Multiselectlistbox.js
Can you please replace the Top function with the one below and try. I shall upload the latest version tomorrow.
 
//Returns 'Top' position of the given Object
function Top(obj)
{
var curtop = 0;
if (obj.offsetParent)
{
obj = (obj.offsetParent)
 
while (obj.offsetParent)
{
curtop += obj.offsetTop
obj = obj.offsetParent;
}
}
else if (obj.offsetTop)
curtop += obj.offsetTop;
return curtop;
}
 
Thanks
Saleena
QuestionRe: DatasetmemberDanielHH3 Dec '08 - 10:12 
Saleena,
 
I replaced the "function top" with the code that you gave me and now the dropdownlist of the top is blocked and I am only able to unblock it if I move the navigation pane a little bit to the bottom. You can replicate the issue in the default.aspx if you move the dropdownlist named "multiselect_foodItems" below of the ListBox named "LBItemsListBox".
 
Any suggestion?
 
Thanks for all your help.
 
Regards,
Daniel
 
Daniel HH

AnswerRe: DatasetmemberSaleena3 Dec '08 - 18:49 
Hi Daniel,
We have uploaded the latest version with some fixes. Can you please update the files from Controls.zip and check if you still face issues with it.
 
Thanks,
Saleena
QuestionRe: DatasetmemberDanielHH4 Dec '08 - 11:07 
I updated the controls but for some reason the drop down list do an auto post back every time that I select an item. I added autopostback=false i n the aspx and in the code. But it is still doing the autopostback.
 
Any suggestion?
 
Regards,
Daniel
 
Daniel HH

AnswerRe: DatasetmemberSaleena5 Dec '08 - 6:22 
Not sure why this happens. Have you tried the sample that is attached with the article. I do have one sample with autopostback set to false. The juices drop down. can you check that one please. If youare still not able to solve then email me the code. I will have a look at it.
 
Cheers,
Saleena
QuestionRe: DatasetmemberDanielHH6 Dec '08 - 3:07 
Saleena,
 
I found the error. The template:fragment was the issue. The dropdowns are working correctly. These are the rows removed:

 

I really really appreciate all your help and support
Many thanks
Daniel H
 
Daniel HH

AnswerRe: DatasetmemberSaleena6 Dec '08 - 6:35 
Glad to know that Daniel..good luck with your project..
GeneralMy vote of 1memberSandeep Mewara26 Nov '08 - 0:52 
Not that elegant!
GeneralRe: My vote of 1memberSaleena26 Nov '08 - 23:37 
Thanks,Any suggestions to enhance the elegance? We were more focussed on the functionality rather than the elegance.
RantRe: My vote of 1 - for your message!membertimh_em3 Dec '08 - 22:21 
It seems to me if you are going to take the time to rate an article low, then leave a message to point out he fact that you rated the article so low, you owe the author more feedback than a single, terse sentence.
 
I don't particularly care for the method the authors used, nor do I think the control is very useful. However, I am not going to slam them for taking the time to contribute. Perhaps you could have included a link to your more elegant solution so we could all benefit? Big Grin | :-D
AnswerRe: My vote of 1 - for your message!memberSandeep Mewara7 Dec '08 - 6:25 
Sure...
 
Here is one of the link:
http://www.codeproject.com/KB/webforms/MultiSelectDropDown.aspx[^]
 
Earlier, I just gave my personal opinion.
GeneralPlease fix your linksmemberfwsouthern11 Nov '08 - 9:21 
Only your "images" link is functional -- please correct.
GeneralRe: Please fix your linksmemberSaleena11 Nov '08 - 18:45 
Hi..Thanks very much for letting us know about this. We have rectified the links. You will be able to download the controls and the demo application now. Thanks very much!

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.130523.1 | Last Updated 4 Dec 2008
Article Copyright 2008 by Saleena, Thangavel Murugesan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid