<

MultiSelect Drop Down Box, in .Net

Published on
10,076 Points
4,076 Views
Last Modified:
Approved
Normally the drop down box control found in the .Net framework tools is able to select just one data and value at a time, which is displayed on the text area.   But what if you want to have multiple values to be selected in the drop down box?

As a normal case you can use a <div> to populate the checkbox items and, depending on the selected check boxes, you can add them to the selected array.  But in this case, dynamic population of the drop down is big problem.

Here my article describes creating a usercontrol in .Net, which can be used as a multiselect drop down box.

Create a control

The following example shows creating a web user control, adding one textbox, an imagebutton, and two checkboxes.
<div id="divMultiSelect">
    <table cellpadding="0" cellspacing="0" border="0" style=" border: 1px solid #7F9DB9;background-color: White ;">
        <tr >
            <td>
                <asp:TextBox ID="txtMultiSelect" runat="server" ReadOnly="True" Style="width: 150px;
                    font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #36478B; font-weight: normal" />
            </td>
            <td>
                <asp:ImageButton ID="imgMultiSelect" runat="server" Width="20px" OnClick="imgMultiSelect_Click"
                    ImageUrl="~/Images/MultiSelectDropDown.bmp" />
            </td>
        </tr>
    </table>
    <asp:CheckBoxList ID="cblSelectAll" runat="server" CellPadding="0" CellSpacing="0" BackColor="#F2F2F2" BorderColor="#7F9DB9" BorderWidth="1px"
        Width="163px" AutoPostBack="true" ToolTip="NotSelected" Style="border-bottom: 0px; vertical-align: top; height: 20px; clear: both;" RepeatLayout="Flow" 
		OnSelectedIndexChanged="cblSelectAll_SelectedIndexChanged">
    </asp:CheckBoxList>
    <br />
    <asp:CheckBoxList ID="cblMultiSelect" runat="server" BackColor="White" BorderColor="#7F9DB9" BorderWidth="1px" Width="163px" 
		Style="border-top: 0px; overflow: auto; overflow-y: scroll; margin-top: 8px; height: 200px;" RepeatLayout="Flow" AutoPostBack="true" 
		OnSelectedIndexChanged="cblMultiSelect_SelectedIndexChanged"
        OnDataBound="cblMultiSelect_DataBound">
        </asp:CheckBoxList>
</div>

Open in new window


Server Side Control

Here is the code in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NRMA.NRMAServices;
using System.Collections;

/// <summary>
/// MultiSelect DropDown UserControl
/// </summary>
public partial class UserControl_MultiSelectDropDown : System.Web.UI.UserControl
{
    #region "Property Region"
    /// <summary>
    /// To get the selected values of a multi select drop down in a comma seperated string
    /// </summary>
    private string selectValues;
    /// <summary>
    /// To get the selected values of a multi select drop down in a comma seperated string
    /// </summary>
    public string SelectValues
    {
        get { return ViewState[this.ClientID] == null ? "0" : ViewState[this.ClientID].ToString(); }
        set
        {
            ViewState[this.ClientID] = value;
            selectValues = ViewState[this.ClientID].ToString();
        }
    }
    /// <summary>
    /// To get the selected values of a multi select drop down in a comma seperated string
    /// </summary>
    private string selectItems;
    /// <summary>
    /// To get the selected values of a multi select drop down in a comma seperated string
    /// </summary>
    public string SelectItems
    {
        get { return ViewState["name" + this.ClientID] == null ? "0" : ViewState["name" + this.ClientID].ToString(); }
        set
        {
            ViewState["name" + this.ClientID] = value;
            selectItems = ViewState["name" + this.ClientID].ToString();
        }
    }

    /// <summary>
    /// To get the multi select image button control
    /// </summary>
    private ImageButton imageMultiSelect;
    /// <summary>
    /// To get the multi select image button control
    /// </summary>
    public ImageButton ImageMultiSelect
    {
        get { return imgMultiSelect; }
        set { imageMultiSelect = value; }
    }

    /// <summary>
    /// To get the check box multi select control
    /// </summary>
    private CheckBoxList checkMultiSelect;
    /// <summary>
    /// To get the check box multi select control
    /// </summary>
    public CheckBoxList CheckMultiSelect
    {
        get { return cblMultiSelect; }
        set { checkMultiSelect = value; }
    }

    /// <summary>
    /// To get the check box select all control
    /// </summary>
    private CheckBoxList checkSelectAll;
    /// <summary>
    /// To get the check box select all control
    /// </summary>
    public CheckBoxList CheckSelectAll
    {
        get { return cblSelectAll; }
        set { checkSelectAll = value; }
    }
	
	/// <summary>
    /// Abstract class for classes with ID and Name 
    /// </summary>
    public  class IDNamePair
    {
        /// <summary>
        /// ID
        /// </summary>
        protected long iD;

        /// <summary>
        /// Name
        /// </summary>
        protected string name;

        /// <summary>
        /// ID
        /// </summary>
        public long ID
        {
            get { return iD; }
            set { iD = value; }
        }

        /// <summary>
        /// Name
        /// </summary>
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
    #endregion

    #region "Events"
    /// <summary>
    /// Page load event of multi select drop down user control
    /// </summary>
    /// <param name="sender">sender object</param>
    /// <param name="e">event arguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        int _countOfSelectedItems = 0;
        if (!IsPostBack)
        {
            cblSelectAll.Visible = false;
            cblMultiSelect.Visible = false;
            cblSelectAll.Style.Add("position", "absolute");
            cblMultiSelect.Style.Add("position", "absolute");
        }
        if (cblSelectAll.Items.Count >= 1)
        {
            if (cblSelectAll.Items[0].Selected == true)
            {
                this.SelectValues = "0";
            }
        }
        else
        {
            for (int i = 0; i < cblMultiSelect.Items.Count; i++)
            {
                if (cblMultiSelect.Items[i].Selected == true)
                {
                    this.SelectValues = selectValues + cblMultiSelect.Items[i].Value.ToString() + ", ";
                    this.SelectItems = selectItems + cblMultiSelect.Items[i].Text.ToString() + ", ";
                    _countOfSelectedItems++;
                }

            }
            if (_countOfSelectedItems > 0)
            {
                this.SelectValues = selectValues.Substring(0, selectValues.Length - 2);
                this.SelectItems = selectItems.Substring(0, selectItems.Length - 2);
            }
        }
    }

    /// <summary>
    /// Onclick event of the Multi Select Image Button
    /// </summary>
    /// <param name="sender">sender object</param>
    /// <param name="e">image click event arguments</param>
    protected void imgMultiSelect_Click(object sender, ImageClickEventArgs e)
    {
        if (cblSelectAll.Visible == true && cblMultiSelect.Visible == true)
        {
            cblMultiSelect.Visible = false;
            cblSelectAll.Visible = false;
        }
        else
        {
            cblMultiSelect.Visible = true;
            cblSelectAll.Visible = true;
        }
    }

    /// <summary>
    /// Checkbox list multi select control selected index change event
    /// </summary>
    /// <param name="sender">sender object</param>
    /// <param name="e">event arguments</param>
    protected void cblMultiSelect_SelectedIndexChanged(object sender, EventArgs e)
    {
        int _countOfSelectedItems = 0;
        int _countOfUnSelectedItems = 0;
        cblSelectAll.Items[0].Selected = false;
        cblSelectAll.ToolTip = "NotSelected";
        for (int i = 0; i < cblMultiSelect.Items.Count; i++)
        {
            if (cblMultiSelect.Items[i].Selected == true)
            {
                this.selectValues = this.selectValues + cblMultiSelect.Items[i].Value.ToString() + ", ";
                this.SelectItems = this.selectItems + cblMultiSelect.Items[i].Text.ToString() + ", ";
                _countOfSelectedItems++;
            }
            else
            {
                _countOfUnSelectedItems++;
            }
        }
        if (_countOfSelectedItems == 1)
        {
            txtMultiSelect.Text = cblMultiSelect.SelectedItem.Text;
            this.SelectValues = cblMultiSelect.SelectedValue.ToString();
            this.SelectItems = cblMultiSelect.SelectedItem.ToString();

        }
        else if (_countOfSelectedItems > 1)
        {
            txtMultiSelect.Text = _countOfSelectedItems.ToString() + " Items Selected";
        }

        else
        {
            txtMultiSelect.Text = "";
            this.selectValues = "";
            this.SelectItems = "";
        }
        if (_countOfSelectedItems > 0 && _countOfSelectedItems != 1)
        {
            this.SelectValues = selectValues.Substring(0, selectValues.Length - 2);
            this.SelectItems = selectItems.Substring(0, selectItems.Length - 2);
        }
        if (_countOfUnSelectedItems == 0)
        {
            cblSelectAll.Items[0].Selected = true;
            cblSelectAll.ToolTip = "Selected";
            txtMultiSelect.Text = cblSelectAll.SelectedItem.Text;
            this.SelectValues = cblSelectAll.SelectedValue.ToString();
            this.SelectItems = cblSelectAll.SelectedItem.ToString();
        }
    }
    /// <summary>
    /// cblMultiSelect on data bound
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void cblMultiSelect_DataBound(object sender, EventArgs e)
    {
        int _index = 1;
        for (int i = 0; i <= cblMultiSelect.Items.Count - 1;i++ )
        {
            ListItem lst = cblMultiSelect.Items[i];
            if (_index % 2 == 0)
            {
                lst.Attributes.Remove("class");
                lst.Attributes.Add("class", "GraySpan");
            }
            else
            {
                lst.Attributes.Remove("class");
                lst.Attributes.Add("class", "WhiteSpan");
            }
            _index = _index + 1;
        }
    }
    /// <summary>
    /// Checkbox list select all control selected index change event
    /// </summary>
    /// <param name="sender">sender object</param>
    /// <param name="e">event arguments</param>
    protected void cblSelectAll_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cblSelectAll.ToolTip == "NotSelected")
        {
            txtMultiSelect.Text = cblSelectAll.SelectedItem.Text;
            selectValues = cblSelectAll.SelectedValue.ToString();
            selectItems = cblSelectAll.SelectedItem.ToString();
            for (int i = 0; i < cblMultiSelect.Items.Count; i++)
            {
                cblMultiSelect.Items[i].Selected = true;
            }
            cblSelectAll.ToolTip = "Selected";
            if (cblSelectAll.Visible == true && cblMultiSelect.Visible == true)
            {
                cblMultiSelect.Visible = false;
                cblSelectAll.Visible = false;
            }
            else
            {
                cblMultiSelect.Visible = true;
                cblSelectAll.Visible = true;
            }
        }
        else if (cblSelectAll.ToolTip == "Selected")
        {
            txtMultiSelect.Text = "";
            selectValues = "";
            selectItems = "";
            for (int i = 0; i < cblMultiSelect.Items.Count; i++)
            {
                cblMultiSelect.Items[i].Selected = false;
            }
            cblSelectAll.ToolTip = "NotSelected";
        }
    }
    #endregion

    #region "Custom Methods"
    /// <summary>
    /// To Load the data into the Drop Down based on the super value
    /// </summary>
    /// <param name="_listInfo">ID Name Pair data that do be populated into the checkbox list</param>
    /// <param name="_allOptional">Boolean value to add all option in the dropdown</param>
    public void LoadDropDown(List<IDNamePair> _listInfo, bool _allOptional)
    {
        cblMultiSelect.Items.Clear();
        int _index = 1;
        for (int i = 0; i < _listInfo.Count; i++)
        {
            ListItem _thisListItem = new ListItem();
            if (_index % 2 == 0)
            {
                _thisListItem.Text = _listInfo[i].Name.ToString();
                _thisListItem.Value = _listInfo[i].ID.ToString();
                cblMultiSelect.Items.Add(_thisListItem);
            }
            else
            {
                _thisListItem.Text =_listInfo[i].Name.ToString() ;
                _thisListItem.Value = _listInfo[i].ID.ToString();
                cblMultiSelect.Items.Add(_thisListItem);
            }
            _index = _index + 1;
           
        }
        if (_allOptional)
        {
            if (cblMultiSelect.Items.Count != 1)
            {
                ListItem _thisListItem = new ListItem();
                _thisListItem.Text = "All";
                _thisListItem.Value = "0".ToString();
                cblSelectAll.Items.Clear();
                cblSelectAll.Items.Add(_thisListItem);
            }
            else
            {
                cblSelectAll.Enabled = false;
            }

            cblSelectAll.Items[0].Selected = true;
            cblSelectAll.ToolTip = "Selected";
            txtMultiSelect.Text = cblSelectAll.SelectedItem.Text;
            selectValues = cblSelectAll.SelectedValue.ToString();
            selectItems = cblSelectAll.SelectedItem.ToString();
            for (int i = 0; i < cblMultiSelect.Items.Count; i++)
            {
                cblMultiSelect.Items[i].Selected = true;
            }
        }
        else
        {
            int _countOfSelectedItems = 0;
            int _countOfUnSelectedItems = 0;
            if (cblMultiSelect.Items.Count != 1)
            {
                for (int i = 0; i < cblMultiSelect.Items.Count; i++)
                {
                    if (cblMultiSelect.Items[i].Selected == true)
                    {
                        _countOfSelectedItems++;
                    }
                    else
                    {
                        _countOfUnSelectedItems++;
                    }
                }
                if (_countOfSelectedItems == 1)
                {
                    txtMultiSelect.Text = cblMultiSelect.SelectedItem.Text;
                    selectValues = cblMultiSelect.SelectedValue.ToString();
                    selectItems = cblMultiSelect.SelectedItem.ToString();
                }
                else if (_countOfSelectedItems > 1)
                {
                    txtMultiSelect.Text = _countOfSelectedItems.ToString() + " Items Selected";
                }
                else
                {
                    txtMultiSelect.Text = "";
                    selectValues = "";
                    selectItems = "";
                }
                if (_countOfUnSelectedItems == 0)
                {
                    cblSelectAll.Items[0].Selected = true;
                    cblSelectAll.ToolTip = "Selected";
                    txtMultiSelect.Text = cblSelectAll.SelectedItem.Text;
                    selectValues = cblSelectAll.SelectedValue.ToString();
                    selectItems = cblSelectAll.SelectedItem.ToString();
                }
            }
            else
            {
                cblMultiSelect.Items[0].Selected = true;
                txtMultiSelect.Text = cblMultiSelect.SelectedItem.Text;
                selectValues = cblMultiSelect.SelectedValue.ToString();
                selectItems = cblMultiSelect.SelectedItem.ToString();
            }
        }
       
    }

	/// <summary>
    /// Overloaded method of LoadDropDown to populate the multiselect dropdown
    /// </summary>
    /// <param name="_listInfo"></param>
    /// <param name="_allOptional"></param>
    public void LoadDropDown(Hashtable _listInfo, bool _allOptional)
    {
        cblMultiSelect.Items.Clear();
        int _index = 0;
        foreach (DictionaryEntry de in _listInfo)
        {
            ListItem _thisListItem = new ListItem();
            if (_index % 2 == 0)
            {
                _thisListItem.Text = de.Value.ToString();
                _thisListItem.Value = de.Key.ToString();
                cblMultiSelect.Items.Add(_thisListItem);
            }
            else
            {
                _thisListItem.Text = de.Value.ToString() ;
                _thisListItem.Value = de.Key.ToString();
                cblMultiSelect.Items.Add(_thisListItem);
            }
            _index = _index + 1;
            
        }
        if (_allOptional)
        {
            if (cblMultiSelect.Items.Count != 1)
            {
                ListItem _thisListItem = new ListItem();
                _thisListItem.Text = "All";
                _thisListItem.Value = "0".ToString();
                cblSelectAll.Items.Clear();
                cblSelectAll.Items.Add(_thisListItem);
            }
            else
            {
                cblSelectAll.Enabled = false;
            }

            cblSelectAll.Items[0].Selected = true;
            cblSelectAll.ToolTip = "Selected";
            txtMultiSelect.Text = cblSelectAll.SelectedItem.Text;
            selectItems = cblSelectAll.SelectedItem.ToString();
            for (int i = 0; i < cblMultiSelect.Items.Count; i++)
            {
                cblMultiSelect.Items[i].Selected = true;
            }
        }
        else
        {
            int _countOfSelectedItems = 0;
            int _countOfUnSelectedItems = 0;
            if (cblMultiSelect.Items.Count != 1)
            {
                for (int i = 0; i < cblMultiSelect.Items.Count; i++)
                {
                    if (cblMultiSelect.Items[i].Selected == true)
                    {
                        _countOfSelectedItems++;
                    }
                    else
                    {
                        _countOfUnSelectedItems++;
                    }
                }
                if (_countOfSelectedItems == 1)
                {
                    txtMultiSelect.Text = cblMultiSelect.SelectedItem.Text;
                    selectValues = cblMultiSelect.SelectedValue.ToString();
                    selectItems = cblMultiSelect.SelectedItem.ToString();
                }
                else if (_countOfSelectedItems > 1)
                {
                    txtMultiSelect.Text = _countOfSelectedItems.ToString() + " Items Selected";
                }
                else
                {
                    txtMultiSelect.Text = "";
                    selectValues = "";
                    selectItems = "";
                }
                if (_countOfUnSelectedItems == 0)
                {
                    cblSelectAll.Items[0].Selected = true;
                    cblSelectAll.ToolTip = "Selected";
                    txtMultiSelect.Text = cblSelectAll.SelectedItem.Text;
                    selectValues = cblSelectAll.SelectedValue.ToString();
                    selectItems = cblSelectAll.SelectedItem.ToString();
                }
            }
            else
            {
                cblMultiSelect.Items[0].Selected = true;
                txtMultiSelect.Text = cblMultiSelect.SelectedItem.Text;
                selectValues = cblMultiSelect.SelectedValue.ToString();
                selectItems = cblMultiSelect.SelectedItem.ToString();
            }
        }
       
    }
    
    /// <summary>
    /// To Load the data into the Drop Down based on the seleced value
    /// </summary>
    /// <param name="_selectedIds">Array of selected items values</param>
    public void LoadDropDownValue(int[] _selectedIds)
    {
        if (_selectedIds[0] == 0)
        {
            cblSelectAll.Items[0].Selected = true;
            cblSelectAll.ToolTip = "Selected";
            txtMultiSelect.Text = cblSelectAll.SelectedItem.Text;
            selectValues = cblSelectAll.SelectedValue.ToString();
            selectItems = cblSelectAll.SelectedItem.ToString();
        }
        else
        {
            cblSelectAll.Items[0].Selected = false;
            cblSelectAll.ToolTip = "NotSelected";
            for (int i = 0; i < cblMultiSelect.Items.Count; i++)
            {
                cblMultiSelect.Items[i].Selected = false;
            }
            for (int i = 0; i < cblMultiSelect.Items.Count; i++)
            {
                for (int j = 0; j < _selectedIds.Length; j++)
                {
                    if (cblMultiSelect.Items[i].Value == _selectedIds[j].ToString())
                    {
                        cblMultiSelect.Items[i].Selected = true;
                    }
                }
            }
            if (_selectedIds.Length == 1)
            {
                txtMultiSelect.Text = cblMultiSelect.SelectedItem.Text;
                selectValues = cblMultiSelect.SelectedValue.ToString();
                selectItems = cblMultiSelect.SelectedItem.ToString();
            }
            else if (_selectedIds.Length > 1)
            {
                txtMultiSelect.Text = _selectedIds.Length.ToString() + " Items Selected";
            }
        }
    }
    
	/// <summary>
    /// To Load the data into the Drop Down based on the seleced value
    /// </summary>
    /// <param name="_selectedIds">Array of selected items values</param>
    
	public void LoadDropDownValue(string[] _selectedIds)
    {
        if (_selectedIds[0] == "0")
        {
            cblSelectAll.Items[0].Selected = true;
            cblSelectAll.ToolTip = "Selected";
            txtMultiSelect.Text = cblSelectAll.SelectedItem.Text;
            selectValues = cblSelectAll.SelectedValue.ToString();
            selectItems = cblSelectAll.SelectedItem.ToString();
        }
        else
        {
            cblSelectAll.Items[0].Selected = false;
            cblSelectAll.ToolTip = "NotSelected";
            for (int i = 0; i < cblMultiSelect.Items.Count; i++)
            {
                cblMultiSelect.Items[i].Selected = false;
            }
            for (int i = 0; i < cblMultiSelect.Items.Count; i++)
            {
                for (int j = 0; j < _selectedIds.Length; j++)
                {
                    if (cblMultiSelect.Items[i].Value == _selectedIds[j].ToString())
                    {
                        cblMultiSelect.Items[i].Selected = true;
                    }
                }
            }
            if (_selectedIds.Length == 1)
            {
                txtMultiSelect.Text = cblMultiSelect.SelectedItem.Text;
                selectValues = cblMultiSelect.SelectedValue.ToString();
                selectItems = cblMultiSelect.SelectedItem.ToString();
            }
            else if (_selectedIds.Length > 1)
            {
                txtMultiSelect.Text = _selectedIds.Length.ToString() + " Items Selected";
            }
        }
    }
    #endregion
}

Open in new window


Explanation

Method LoadDropDown(), is used to fill the drop down with values.  This is an overloading method where you can pass either a list of IDNamePair entities or a Hash-table value to fill the multi-select drop down.

All the usable controls are populated into properties and exposed.  When you call this user control in a page, you can also easily access all these properties.

The SelectValues property of the multi-select drop down box control gives the selected values in a comma separated string. The SelectItems property returns the text values of the selected values.

There is a checkbox list of "select all," which is used to select all the options populated in the multi-select drop down.  And to unselect also.  There is an option to enable this in the multi-select drop down box, while binding the data to this control.
 
0
Comment
  • 2
2 Comments
 

Expert Comment

by:saswt_ds
Excellent post. It is really helpful. Multiple selection of values from a dropdownlist is clearly defined here. Coding is very neat and clear for understanding.
0
 

Expert Comment

by:saswt_ds
Excellent post. It is really helpful. Multiple selection of values from a dropdownlist is clearly defined here. Coding is very neat and clear for understanding.
0

Featured Post

Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

Join & Write a Comment

Key to your CPU's ability to stay cool is to use the right amount of thermal paste and apply it correctly. In other words you want as much thermal conductivity between CPU and the cooling block. Use a quality thermal paste and apply it in a manner…
Learn the basics of Skype For Business in office 365

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month