Click here to Skip to main content
15,880,905 members
Articles / Programming Languages / C#

An OwnerDraw ComboBox with CheckBoxes in the Drop-Down

Rate me:
Please Sign up or sign in to vote.
4.74/5 (27 votes)
24 May 2007CPOL3 min read 271.9K   15.5K   64   33
An OwnerDraw ComboBox with CheckBoxes in the Drop-Down

Screenshot - DropDown.jpg

Introduction

I needed to add filtering to a list view. The list view already had a ToolStrip to which I could add the appropriate widget. I decided a drop-down ComboBox with CheckBoxes to turn items on and off was the most space-efficient, and intuitive way to implement it. However, this requires an owner-draw ComboBox. Fortunately, the .NET Framework as of 2.0 includes a helper class, CheckBoxRenderer, that will render the check box into the drop-down list for you, given the right parameters.

Using the Code

The first step was to subclass the System.Windows.Forms.ComboBox class:

C#
public partial class CheckComboBox : ComboBox
{
    public CheckComboBox()
    {
        this.DrawMode = DrawMode.OwnerDrawFixed;
        ...
    }

    ...
}

Notice that I set the DrawMode property to tell the ComboBox that we intend to render the drop-down list items ourselves. The next step was to define a class to contain our drop-down list item data and maintain the state. This is a simple class:

C#
public class CheckComboBoxItem
{
    public CheckComboBoxItem( string text, bool initialCheckState )
    {
        _checkState = initialCheckState;
        _text = text;
    }

    private bool _checkState = false;
    public bool CheckState
    {
        get { return _checkState; }
        set { _checkState = value; }
    }

    private string _text = "";
    public string Text
    {
        get { return _text; }
        set { _text = value; }
    }

    public override string ToString()
    {
        return "Select Options";
    }
}

Then we wire up a delegate to the ComboBox's DrawItem event:

C#
this.DrawItem += new DrawItemEventHandler(CheckComboBox_DrawItem);

and implement it as follows:

C#
void CheckComboBox_DrawItem( object sender, DrawItemEventArgs e )
{
    if (e.Index == -1)
    {
        return;
    }

    if( !( Items[ e.Index ] is CheckComboBoxItem ) )
    {
        e.Graphics.DrawString( 
            Items[ e.Index ].ToString(), 
            this.Font, 
            Brushes.Black, 
            new Point( e.Bounds.X, e.Bounds.Y ) );
        return;
    }

    CheckComboBoxItem box = (CheckComboBoxItem)Items[ e.Index ];

    CheckBoxRenderer.RenderMatchingApplicationState = true;
    CheckBoxRenderer.DrawCheckBox( 
        e.Graphics, 
        new Point( e.Bounds.X, e.Bounds.Y ), 
        e.Bounds, 
        box.Text, 
        this.Font, 
        ( e.State & DrawItemState.Focus ) == 0, 
        box.CheckState ? CheckBoxState.CheckedNormal : 
            CheckBoxState.UncheckedNormal );
}

In this delegate, the first thing we do is to verify that the item we are rendering was added as a CheckComboBoxItem. If it is not, we render it as a simple string. Otherwise, we get the appropriate CheckComboBoxItem from the Items collection (using the DrawItemEventArgs.Index property). Then we call the CheckBoxRenderer.DrawCheckBox() method, passing in the Graphics object, into which we want to render the CheckBox, and the location, size, text, font, focus and check states.

The result is that it will render our drop-down list items to look like check boxes:

Screenshot - DropDown.jpg

Next we want to toggle the check state when one of the items is selected. So we wire up another delegate, but this time to the SelectedIndexChanged event:

C#
this.SelectedIndexChanged += 
    new EventHandler( CheckComboBox_SelectedIndexChanged );

and implement it as follows:

C#
void CheckComboBox_SelectedIndexChanged( object sender, EventArgs e )
{
    CheckComboBoxItem item = (CheckComboBoxItem)SelectedItem;
    item.CheckState = !item.CheckState;
    ...
}

This allows us to toggle the check box in the drop-downs, but doesn't allow the user of this control to know that anything has happened. So we also add a public event to notify the control's users of a change to the check state of an item in the drop-down list:

C#
public event EventHandler CheckStateChanged;

and we fire this event when we toggle the state above, so the full method looks like this:

C#
void CheckComboBox_SelectedIndexChanged( object sender, EventArgs e )
{
    CheckComboBoxItem item = (CheckComboBoxItem)SelectedItem;
    item.CheckState = !item.CheckState;
    if (CheckStateChanged != null)
        CheckStateChanged(item, e);
}

Using the Control

To use the control, you simply add it to the container of your choice and add items to it like this:

C#
checkComboBox1.Items.Add(new CheckComboBox.CheckComboBoxItem("One", true));
checkComboBox1.Items.Add(new CheckComboBox.CheckComboBoxItem("Two", true));
checkComboBox1.Items.Add(new CheckComboBox.CheckComboBoxItem("Three", true));

To get notifications that a check state has been changed by the user:

C#
this.checkComboBox1.CheckStateChanged += 
    new EventHandler(this.checkComboBox1_CheckStateChanged);

That can be handled like this:

C#
private void checkComboBox1_CheckStateChanged(object sender, EventArgs e)
{
    if (sender is CheckComboBox.CheckComboBoxItem)
    {
        CheckComboBox.CheckComboBoxItem item = 
            (CheckComboBox.CheckComboBoxItem)sender;
        ... 
    }
}

Screenshot - DropDownTest1.jpg

The finished sample application.


Screenshot - DropDownTest2.jpg

The drop-down.

Points of Interest

There was one annoyance that I'm sure there's a better solution to than the one I came up with. I'd like the TextBox portion of the control to contain fixed text and not be editable. So, as a stop-gap I initialize it to the string "Select Options" and override the CheckComboBoxItem class' ToString() method to always return that same string. This way, whichever item the user selects last, the string never changes. This does not make it non-editable.

There are many additions I'd like to make as time permits:

  • Correctly align the text so it left-justifies (need to find out how to calculate the width of the check box bitmap to do this correctly)
  • Add "Select All" and "Select None" items with a separator to the top of the drop-down
  • Allow other control types into the drop-down (e.g. - radio buttons)

History

  • 24th May, 2007: Original version posted

License

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


Written By
Software Developer (Senior)
United States United States
Developer with over twenty years of coding for profit, and innumerable years before that of doing it at a loss.

Comments and Discussions

 
QuestionHow you link the ToString() method of CheckComboBoxItem to defoult text of Combobox? Pin
Member 1382197815-Jul-18 22:54
Member 1382197815-Jul-18 22:54 
Questioncant open in vs 15 Pin
Member 1332630528-Oct-17 11:57
Member 1332630528-Oct-17 11:57 
AnswerRe: cant open in vs 15 Pin
Derek Viljoen3-Jan-18 9:57
Derek Viljoen3-Jan-18 9:57 
Questioncannot bind Pin
RiccardoG25-Feb-16 22:45
RiccardoG25-Feb-16 22:45 
GeneralThank you Pin
Girish Nama3-Dec-13 18:39
Girish Nama3-Dec-13 18:39 
QuestionHow can I keep the combo box open after clicknig ? Pin
AsfK3-Jun-13 20:00
AsfK3-Jun-13 20:00 
AnswerRe: How can I keep the combo box open after clicknig ? Pin
Derek Viljoen4-Jun-13 2:31
Derek Viljoen4-Jun-13 2:31 
QuestionDataGridViewComboBoxCell C# Pin
d.allen10121-Apr-13 11:16
d.allen10121-Apr-13 11:16 
QuestionCannot open project in vs 2008 Pin
Why so Serious7-Oct-12 23:42
Why so Serious7-Oct-12 23:42 
AnswerRe: Cannot open project in vs 2008 Pin
Derek Viljoen16-Oct-12 6:41
Derek Viljoen16-Oct-12 6:41 
GeneralVisual Studio Version Pin
Katalin Kalman7-Dec-10 4:51
Katalin Kalman7-Dec-10 4:51 
GeneralRe: Visual Studio Version Pin
Derek Viljoen7-Dec-10 6:46
Derek Viljoen7-Dec-10 6:46 
GeneralRe: Visual Studio Version Pin
Katalin Kalman8-Dec-10 3:39
Katalin Kalman8-Dec-10 3:39 
GeneralRe: left align text Pin
wojtazz13-Feb-09 0:21
wojtazz13-Feb-09 0:21 
Generalmulti-select Pin
Member 385422518-Aug-08 14:11
Member 385422518-Aug-08 14:11 
GeneralRe: multi-select Pin
Stelios Alexandrakis20-Nov-08 6:06
Stelios Alexandrakis20-Nov-08 6:06 
Hi, I had the same problem and I ended up writing my own version which solves it. Have a look at: A ComboBox with a CheckedListBox as a Dropdown[^]. Hope that is of help. Smile | :)
QuestionKeep dropdown open [modified] Pin
Massalla9-Aug-07 20:42
Massalla9-Aug-07 20:42 
AnswerRe: Keep dropdown open Pin
Derek Viljoen10-Aug-07 2:07
Derek Viljoen10-Aug-07 2:07 
GeneralRe: Keep dropdown open Pin
Massalla10-Aug-07 8:48
Massalla10-Aug-07 8:48 
Questionleft align text Pin
teeJay000126-Jun-07 0:41
teeJay000126-Jun-07 0:41 
AnswerRe: left align text Pin
Derek Viljoen26-Jun-07 2:28
Derek Viljoen26-Jun-07 2:28 
GeneralRe: left align text Pin
teeJay000126-Jun-07 2:51
teeJay000126-Jun-07 2:51 
GeneralRe: left align text Pin
Derek Viljoen26-Jun-07 3:15
Derek Viljoen26-Jun-07 3:15 
GeneralRe: left align text Pin
pavvel31-Jul-07 3:55
pavvel31-Jul-07 3:55 
GeneralRe: left align text Pin
Derek Viljoen31-Jul-07 4:03
Derek Viljoen31-Jul-07 4:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.