Pages

Wednesday, November 9, 2011

A Multiple Selection DropDownList (a CheckBoxList Inside a DropDownList)

http://www.codeproject.com/KB/aspnet/MultiCheckCombo/MultiCheckCombo.zip



<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MultiCheckCombo.ascx.cs" Inherits="SRL.UserControls.MultiCheckCombo" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<script type = "text/javascript">
//Script para incluir en el ComboBox1 cada item chekeado del chkListMateriales
function CheckItem(checkBoxList)
{
    var options = checkBoxList.getElementsByTagName('input');
    var arrayOfCheckBoxLabels= checkBoxList.getElementsByTagName("label");
    var s = "";
   
    for(i=0;i<options.length;i++)
    {
        var opt = options[i];
        if(opt.checked)
        {
            s = s + ", "+ arrayOfCheckBoxLabels[i].innerText;
        }
    }
    if(s.length > 0)
    {      
       s = s.substring(2, s.length); //sacar la primer 'coma'
    }
    var TxtBox = document.getElementById("<%=txtCombo.ClientID%>");      
    TxtBox.value = s;
    document.getElementById('<%=hidVal.ClientID %>').value = s;
}
</script>


<asp:TextBox ID="txtCombo" runat="server" ReadOnly="true" Width="200" Font-Size="X-Small"></asp:TextBox>
<cc1:PopupControlExtender ID="PopupControlExtender111" runat="server"
    TargetControlID="txtCombo" PopupControlID="Panel111" Position="Bottom" >
</cc1:PopupControlExtender>

<input type="hidden" name="hidVal" id="hidVal" runat="server" />

<asp:Panel ID="Panel111" runat="server" ScrollBars="Vertical" Width="250" Height="150" BackColor="AliceBlue" BorderColor="Gray" BorderWidth="1">
   
    <asp:CheckBoxList ID="chkList"
        runat="server"
        Height="150" onclick="CheckItem(this)">                                                                                                                                                                      
    </asp:CheckBoxList>
   
</asp:Panel>



---------------------------------------

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Odbc;

namespace SRL.UserControls
{
    public partial class MultiCheckCombo : System.Web.UI.UserControl
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }
        /// <summary>
        /// Set the Width of the CheckBoxList
        /// </summary>
        public int WidthCheckListBox
        {
            set
            {
                chkList.Width = value;
                Panel111.Width = value + 20;                  
            }          
        }
        /// <summary>
        /// Set the Width of the Combo
        /// </summary>
        public int Width      
        {
            set { txtCombo.Width = value; }
            get { return (Int32)txtCombo.Width.Value; }
        }
        public bool Enabled
        {
            set { txtCombo.Enabled = value; }
        }
        /// <summary>
        /// Set the CheckBoxList font Size
        /// </summary>
        public FontUnit fontSizeCheckBoxList
        {
            set { chkList.Font.Size = value; }
            get { return chkList.Font.Size; }
        }
        /// <summary>
        /// Set the ComboBox font Size
        /// </summary>
        public FontUnit fontSizeTextBox
        {
            set { txtCombo.Font.Size = value; }          
        }
       


        /// <summary>
        /// Add Items to the CheckBoxList.
        /// </summary>
        /// <param name="array">ArrayList to be added to the CheckBoxList</param>
        public void AddItems(ArrayList array)
        {
            for (int i = 0; i < array.Count; i++)
            {
                chkList.Items.Add(array[i].ToString());
            }
        }


        /// <summary>
        /// Add Items to the CheckBoxList
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="nombreCampoTexto">Field Name of the OdbcDataReader to Show in the CheckBoxList</param>
        /// <param name="nombreCampoValor">Value Field of the OdbcDataReader to be added to each Field Name (it can be the same string of the textField)</param>
        public void AddItems(OdbcDataReader dr, string textField, string valueField)
        {
            ClearAll();
            int i = 0;
            while (dr.Read())
            {
                chkList.Items.Add(dr[textField].ToString());
                chkList.Items[i].Value = i.ToString();              
                i++;
            }
        }


        /// <summary>
        /// Uncheck of the Items of the CheckBox
        /// </summary>
        public void unselectAllItems()
        {
            for (int i = 0; i < chkList.Items.Count; i++)
            {
                chkList.Items[i].Selected = false;
            }
        }

        /// <summary>
        /// Delete all the Items of the CheckBox;
        /// </summary>
        public void ClearAll()
        {
            txtCombo.Text = "";          
            chkList.Items.Clear();
        }

        /// <summary>
        /// Get or Set the Text shown in the Combo
        /// </summary>
        public string Text
        {          
            get { return hidVal.Value; }
            set { txtCombo.Text = value; }
        }
    }
}
--------------------------




Introduction

This ascx user control, the MultiCheckCombo, allows the user to select more than one option inside aDropDownList. The different items that are being checked are being copied in the box area of the control.
The great thing of this control is that it doesn't close the check panel until you click outside the control. Example: you can check more than one item at once.
In ASP.NET C#, if you need a web control that allows the user to check more than one option in a DropDownList, you can use this user control freely.

Background

Well, first of all, this control was made in Microsoft Visual Studio 2008, with .NET 3.5 (2.0) and was written in C#. To use it, you need to have properly installed the AjaxControlToolkit in your project.

Using the Code

Again: You need to have installed the AjaxControlToolkit in your project.
This control is fairly easy to implement. Simply copy the 3 ascx files into your project.
Then replace the namespace in both ascx and ascx.cs files with [YourProjectName].MultiCheckCombo.

E.g.: Let's suppose your project's name is TestMultiCheck, replace in the ascx file the Control tag with the name of your namespace/project:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MultiCheckCombo.ascx.cs" 
    Inherits="TestMultiCheck.MultiCheckCombo" %>
And in your ascx.cs file, change the namespace to:
namespace TestMultiCheck
Well, then drag and drop the main file (MultiCheckCombo.ascx) to your Page Designer.
You may drag the control inside or outside an UpdatePanel, but you need a ScriptManager at the beginning of the body tag of your aspx page.
<asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> 
When you drag the control, the following line should be added automatically to the beginning of your aspx page:
<%@ Register src="MultiCheckCombo.ascx" tagname="MultiCheckCombo" tagprefix="uc1" %>
And the code of the control looks like this (it also will be added automatically):
<uc1:MultiCheckCombo ID="MultiCheckCombo1" runat="server" />        
Then, in the code behind (C#), you have to fill the values of the control.
You can fill it with an ArrayList or with an OdbcDataReader.
A: Easy mode: Filling the MultiCheckCombo with an ArrayList:
ArrayList array = new ArrayList();
for (int i=0;i<100;i++) array.Add(i.ToString());
MultiCheckCombo1.AddItems(array);
B: Other option is to fill the MultiCheckCombo with an OdbcDataReader:
OdbcConnection con = /* get YOUR connection string*/
con.Open();
OdbcCommand cmd = new OdbcCommand();
cmd.Connection = con;
cmd.CommandText = "select text,id from ...........";
OdbcDataReader dr = cmd.ExecuteReader();
MultiCheckCombo1.ClearAll();
dr.Read(); 
MultiCheckCombo1.AddItems(dr, "text", "id");
And that's it. You can now test it.
Some important properties of this controls are:
MultiCheckCombo1.WidthCheckListBox = 200; //Set the Width of the CheckBoxList inside DDL.
MultiCheckCombo1.Width = 250; //Set the Width of the DropDownList
MultiCheckCombo1.Enabled = true;
MultiCheckCombo1.fontSizeCheckBoxList = FontUnit.Small; 
MultiCheckCombo1.fontSizeTextBox = FontUnit.XSmall;
MultiCheckCombo1.Text; //Get or Set the Text shown in the Combo
Some important methods of this control are:
MultiCheckCombo1.unselectAllItems(); //Uncheck all of the Items of the CheckBox
MultiCheckCombo1.ClearAll(); //Delete all the Items of the CheckBox;

Points of Interest

I hope you can make it work. Cheers! ENJOY IT!

No comments:

Post a Comment