Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » AJAX » ASP.NET Multiple Selection DropDownList with AJAX HoverMenuExtender

ASP.NET Multiple Selection DropDownList with AJAX HoverMenuExtender

An article on how to build a Multiple Selection DropDownList with AJAX HoverMenuExtender.

Total page views :  10307
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


 xaml.JPG

xaml1.JPG

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.

xaml2.JPG

Using the Code

This is a usercontrol, just drag and drop. But make sure to 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 code is pretty much the same except I had made a few changes to return the text of the selected checkbox. Please see comments.

//09042009 BT - var

string clientID = UniqueID + this.ClientIDSeparator + repeatIndex.ToString(NumberFormatInfo.InvariantInfo);

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
    }

ultipleSelectionDDLCSS.css - style sheet

MultipleSelectionDDLJS.js

Here is the content of the JavaScript, please read the comments.

/*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 onto the page.

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

<asp:DropDownList ID="MultiSelectDDL" CssClass="ddlMenu regularText" runat="server">
<asp:ListItem Value="all">Select
</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 Value="d2">Dummy 2
<asp:ListItem Value="d3">Dummy 3
<asp:ListItem Value="d4">Dummy 4
<asp:ListItem Value="d5">Dummy 5
<asp:ListItem Value="d6">Dummy 6
<asp:ListItem Value="d7">Dummy 7
<asp:ListItem Value="d8">Dummy 8
</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>

MS_With_UserControl_and_Masterpage.aspx

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<
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.

References

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?


Login to add your contents and source code to this article
 About the author
 
Bryian Tan
I have over three years of experience working with Microsoft technologies. I have earned my Microsoft Certified Technology Specialist (MCTS) certification.  I'm a highly motivated self-starter with an aptitude for learning new skills quickly.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.