Click here to Skip to main content
14,216,534 members
Click here to Skip to main content
Posted 28 May 2007


106 bookmarked

A Separator Combo/List Box

Rate this:
4.89 (27 votes)
Please Sign up or sign in to vote.
4.89 (27 votes)
28 May 2007     CPOL    
The Custom Combo Box and List Box Control with Separators

Screenshot - cssepcb1.jpg


This article would be a late follow-up to my previous article, A Separator Combo Box, regarding a control class derived from MFC CCombobox. Since it was posted, several readers have asked for a similar separator combo box in C#. While touching C# programming, I found it easier to write such a custom combo box control as shown in above screen shot. The main point in implementing the separator in a combo box is that a separator should not be selected either from UI or in code logic. We have two choices: let a separator occupy an item space or let a separator reside between items without extra space. I like the latter; it simply draws a line between items, saving space for the whole combo box.

Since both combo box and list box are derived from Windows.Forms.ListControl, they have the same virtual OnDrawItem() and OnMeasureItem() functions available in my customization. Here, the implementation of adding a separator to the combo box can also be applied to the list box. So, I present both SeparatorComboBox and SeparatorListBox, giving the demo as you see it in the screen shot. For simplicity, I only discuss the combo box in the following sections.

Using SeparatorComboBox

Suppose that comboBox1 is a SeparatorComboBox object. Let's add the items as a string:

comboBox1.AddString("All Fruits");
comboBox1.AddString("*Add/Edit Fruit");

For your convenience, AddString() is simply a wrapper for Items.Add() in ComboBox. Next, set the separator positions like this:


As shown in the image, SetSeparator(1) sets a separator before the item "Banana" at index 1. The second line sets at position -1, meaning a separator set at the last item. That is: before "*Add/Edit Fruit". This is the method to set a separator by position, a zero-based index. However, if you need to update a combo box by insertion, deletion, or sorting, then setting by position is not appropriate. I provide another method to set a separator by content. Thus, in this example, instead of using:

comboBox1.AddString("*Add/Edit Fruit");

You can set a separator related to the text "*Add/Edit Fruit" like this:

comboBox1.AddStringWithSeparator("*Add/Edit Fruit");

Then a separator is always stuck on "*Add/Edit Fruit", regardless of its position. To summarize, SeparatorComboBox has three methods as follows:

  • AddString(string s): Appends a string item, equivalent to Items.Add(s).
  • AddStringWithSeparator(string s): Adds a string item with a separator before the text s.
  • SetSeparator(int pos): Adds a separator by a zero-based index position or by a negative from the bottom.

In addition, SeparatorComboBox provides five optional properties for visual effects:

  • DashStyle SeparatorStyle: Sets the separator style defined in DashStyle, such as solid, dot, dash, etc. Default is DashStyle.Solid.
  • Color SeparatorColor: Sets the separator color defined in Color. Default is Color.Black.
  • int SeparatorWidth: Sets the separator width based on the default unit, e.g., in pixels. Default is 1.
  • int SeparatorMargin: Sets the separator horizontal margin at both ends. Default is 1.
  • bool AutoAdjustItemHeight: Indicates whether you allow automatic adjustment for the item height based on SeparatorWidth. Default is false.

For the demo combo box, I call:

comboBox1.SeparatorColor = Color.DarkBlue;
comboBox1.SeparatorWidth = 2;
comboBox1.AutoAdjustItemHeight = true;

I leave SeparatorStyle as solid and SeparatorMargin to 1. To make greater intervals between items, I set AutoAdjustItemHeight to true. As for the list box in the demo, I use default values for SeparatorColor (black), SeparatorWidth (1), AutoAdjustItemHeight (false) and call:

listBox1.SeparatorStyle = DashStyle.Dash;
listBox1.SeparatorMargin = 2;

Alternatively, you can set five properties in the form designer:

Screenshot - cssepcb2.jpg


The main job is to override OnDrawItem() and draw a line between items. Yet before drawing, we should have an information collection ready for all separators. This is the _separators ArrayList, a heterogeneous container storing positions or stings for all separators:

public void SetSeparator(int position)

public void AddStringWithSeparator(string s)

In OnDrawItem(), I search _separators to find a match for the current index passed from the DrawItemEventArgs parameter. This is done by comparing either a string or a position:

protected override void OnDrawItem(DrawItemEventArgs e)
    if (-1 == e.Index) return;                      // Not selected

    bool sep = false;
    object o;
    for (int i=0; !sep && i<_separators.Count; i++)
        o = _separators[i];                         // Get a separator

        if (o is string)                            // Set by content
            if ((string)this.Items[e.Index] == o as string) 
                sep = true;                         // Match content
        else                                        // Set by position
            int pos = (int)o;
            if (pos<0) pos += Items.Count; // Negative position, reversed
            if (e.Index == pos) sep = true;         // Match position

    Graphics g = e.Graphics;
    int y = e.Bounds.Location.Y +_separatorWidth-1; // Adjust top Location
                                                    // if _separatorWidth>1
    if (sep)
        Pen pen = new Pen(_separatorColor, _separatorWidth);
        pen.DashStyle = _separatorStyle;             // Apply all properties

        g.DrawLine(pen, e.Bounds.Location.X+_separatorMargin, y, 
                    e.Bounds.Location.X+e.Bounds.Width-_separatorMargin, y);

    Brush br = DrawItemState.Selected == (DrawItemState.Selected & e.State)? 
        SystemBrushes.HighlightText: new SolidBrush(e.ForeColor);

    g.DrawString((string)Items[e.Index], e.Font, br, e.Bounds.Left, y+1);    


Now, if an item has a separator, I draw a line along the top of its boundary with the properties of _separatorColor, _separatorWidth, _separatorStyle, and _separatorMargin. Finally, regardless of whether a separator is drawn or not, I have to draw the item text myself. To adjust item height automatically, I override OnMeasureItem() like this:

protected override void OnMeasureItem(MeasureItemEventArgs e)
    if (_autoAdjustItemHeight)
        e.ItemHeight += _separatorWidth;


The caveat: Because OnMeasureItem() is getting called each time, immediately after an item is added or inserted, you must set SeparatorWidth and AutoAdjustItemHeight right before calling AddString() and AddStringWithSeparator(). Otherwise, you can't achieve expected results. Also, e.ItemHeight is the original item height that you may initialize manually in code or in the designer.

Points of interest

As a derived class, SeparatorComboBox inherits all public members from ComboBox. In the demo, I create a handler for the event SelectedIndexChanged and a handler for TextChanged, since I set the DropDown combo box style. Also, I add the Insert and Delete buttons to call ComboBox's methods.

Screenshot - cssepcb3.jpg

Here, the code is nothing different from that using ComboBox directly. When trying insertion and deletion, you can verify two different separators: if set by position it always sticks on a specified index, and if set with content it always sticks on that specified text.

private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
    textBox1.Text = "Selected: " +comboBox1.SelectedItem;

private void comboBox1_TextChanged(object sender, System.EventArgs e)
    textBox1.Text = "Changed to: " +comboBox1.Text;

private void buttonInsert_Click(object sender, System.EventArgs e)
    comboBox1.Items.Insert(comboBox1.Items.Count, comboBox1.Text);

private void buttonDelete_Click(object sender, System.EventArgs e)
        int n = int.Parse(comboBox1.Text);
        if (n>comboBox1.Items.Count-1) throw new Exception();
    catch (Exception)
        MessageBox.Show("Please enter a valid index to delete an item.", 

These are just trivial samples. To fit your needs, you have to fine-tune your boxes. The only unsatisfactory aspect I noticed in the combo box is that if AutoAdjustItemHeight is set to true, the height of the dropdown list is not correctly calculated. This causes a vertical scroll bar always appearing, even with fewer items.


  • 28 May, 2007 - Original version posted


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


About the Author

Zuoliu Ding
Software Developer
United States United States
An Adjunct Faculty and Software Developer in Los Angeles and Orange County, CA

* Typical articles published in Dr. Dobb’s Journal and Windows Developer Magazine:

- A Silent Component Update for Internet Explorer
- Silent Application Update
- An MDI-Style Web Browser and Load Spy Monitor
- Implementing Wireless Print for WinNT/Win2K
- Multi-State Checkbox Tree Views
- A Generic Tool Tip Class
- An Easy Way to Add Tool Tips to Any MFC Control

- More from Google...

Comments and Discussions

GeneralMy vote of 5 Pin
Kanasz Robert27-Sep-12 10:51
memberKanasz Robert27-Sep-12 10:51 
GeneralRe: My vote of 5 Pin
Zuoliu Ding27-Sep-12 11:05
memberZuoliu Ding27-Sep-12 11:05 
GeneralRe: My vote of 5 Pin
Kanasz Robert27-Sep-12 22:13
memberKanasz Robert27-Sep-12 22:13 
QuestionNicely Done Pin
Mike Hankey1-Dec-11 18:59
professionalMike Hankey1-Dec-11 18:59 
QuestionGood Job, Suggest Change for Data Binding Pin
PhillipFromAZ12-Jul-11 6:47
memberPhillipFromAZ12-Jul-11 6:47 
AnswerRe: Good Job, Suggest Change for Data Binding Pin
Zuoliu Ding12-Jul-11 17:15
memberZuoliu Ding12-Jul-11 17:15 
GeneralMy vote of 5 Pin
Mark Guo1-Feb-11 12:31
memberMark Guo1-Feb-11 12:31 
GeneralMy vote of 3 Pin
imamul.karim26-Nov-10 22:52
memberimamul.karim26-Nov-10 22:52 
GeneralMy vote of 3 Pin
imamul.karim12-Nov-10 23:39
memberimamul.karim12-Nov-10 23:39 
AnswerBug (and fix) Pin
Ravi Bhavnani20-Sep-10 12:30
professionalRavi Bhavnani20-Sep-10 12:30 
GeneralRe: Bug (and fix) Pin
Zuoliu Ding20-Sep-10 14:07
memberZuoliu Ding20-Sep-10 14:07 
GeneralRe: Bug (and fix) Pin
Ravi Bhavnani20-Sep-10 14:48
professionalRavi Bhavnani20-Sep-10 14:48 
AnswerCorrected fix Pin
Ravi Bhavnani21-Sep-10 5:47
professionalRavi Bhavnani21-Sep-10 5:47 
GeneralRe: Corrected fix Pin
Zuoliu Ding21-Sep-10 8:03
memberZuoliu Ding21-Sep-10 8:03 
GeneralCouple of additions Pin
cormacmiller30-Apr-08 16:32
membercormacmiller30-Apr-08 16:32 
GeneralRe: Couple of additions Pin
Zuoliu Ding30-Apr-08 16:50
memberZuoliu Ding30-Apr-08 16:50 
GeneralFont size changes Pin
mikepc31-Oct-07 3:15
membermikepc31-Oct-07 3:15 
GeneralNice work + a couple of improvements Pin
MarkGladding21-Oct-07 15:45
memberMarkGladding21-Oct-07 15:45 
GeneralRe: Nice work + a couple of improvements Pin
Zuoliu Ding21-Oct-07 19:05
memberZuoliu Ding21-Oct-07 19:05 
GeneralRe: Nice work + a couple of improvements Pin
MarkGladding25-Oct-07 1:42
memberMarkGladding25-Oct-07 1:42 
QuestionCan I use it in web.form instead of window.form? Pin
Mary Du11-Jul-07 20:16
memberMary Du11-Jul-07 20:16 
AnswerRe: Can I use it in web.form instead of window.form? Pin
zyprexia219-Jun-08 1:28
memberzyprexia219-Jun-08 1:28 
NewsVB.NET Grouped Combo... Pin
J Sullivan5-Jun-07 13:28
memberJ Sullivan5-Jun-07 13:28 
Generaltest Pin
purshi_alur29-May-07 19:10
memberpurshi_alur29-May-07 19:10 
Generaldfgdfs Pin
purshi_alur29-May-07 19:09
memberpurshi_alur29-May-07 19:09 

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.