Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Poor Man's CheckBoxList using a DropDownList for ASP.NET/C#

4.67/5 (2 votes)
17 Jul 2013CPOL 24.4K  
Quick solution to convert a dropdownlist into a poor man's checkboxlist without having to import a 3rd party control.

Introduction

Quick solution to convert a dropdownlist into a poor man's checkboxlist without having to import a 3rd party control.

Background

I really like the dropdownlist in that it collapses nicely and has scrollbars. This is functionality I really need in a checkboxlist control. I looked for a long time at 3rd party controls and decided against them as you risk unpredictable issues and make portability more complex. For folks who like a home grown solution this will be extremely workable and easy to do.....

Using the code

Basically you need to commandeer the SelectedIndexChanged event of the dropdown list with the following code and include the function below it as well.  Any item that is clicked on will be preceded with a checkmark. If it is clicked on a second time the checkmark will be removed. If one item is left it will not be allowed to be unchecked.

To process the list, you need to wind through the items and look for any item that contains the checkmark character.

Also in my particular case I default a known item with a checkmark in the databound event of the dropdownlist that I am sure will always be in the list.

C#
const char chkMark = (char)(0X2713); 
protected void MyDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{     
    DropDownList TheDropDownList = (DropDownList)sender;
    bool itemUnchecked = false;
    int numberChecked = NumberofItemsChecked();
    if (TheDropDownList.SelectedItem.Text.Contains(chkMark) && numberChecked > 1)
    {
        TheDropDownList.SelectedItem.Text = TheDropDownList.SelectedItem.Text.Substring(1);
        itemUnchecked = true;
    }
    else if (!TheDropDownList.SelectedItem.Text.Contains(chkMark))
    TheDropDownList.SelectedItem.Text = chkMark + TheDropDownList.SelectedItem.Text;
    numberChecked = NumberofItemsChecked();
    //Display next checked item
    if (itemUnchecked)
    {
        foreach (ListItem theItem in TheDropDownList.Items)
        {
            if (theItem.Text.Contains(chkMark)) 
              { TheDropDownList.SelectedValue = theItem.Value; break; }
        }
    }
}
protected int NumberofItemsChecked()
{
    int numberChecked = 0;
    foreach (ListItem theItem in MyDropDownList.Items)
    {
        if (theItem.Text.Contains(chkMark)) numberChecked++;
    }
    return numberChecked;
}

License

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