B Vidhya
B Vidhya

Reputation: 339

Grouping ComboBox Items in Windows Forms Application

I've a ComboBox in Windows Forms Application in which the items needs to displayed as shown in the below pic. I need the solid separator only for the first grouping. Other items can just be displayed with no grouping header. Using ComboBox it can be achieved as per requirement or do I have to try any 3rd party controls. Any valuable suggestion will be helpful.

enter image description here

Upvotes: 1

Views: 3726

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

You can handle drawing items of ComboBox yourself by setting its DrawMode to OwnerDrawFixed and handling DrawItem event. Then you can draw that separator under the item which you want:

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var comboBox = sender as ComboBox;
    var txt = "";
    if (e.Index > -1)
        txt = comboBox.GetItemText(comboBox.Items[e.Index]);
    e.DrawBackground();
    TextRenderer.DrawText(e.Graphics, txt, comboBox.Font, e.Bounds, e.ForeColor,
        TextFormatFlags.VerticalCenter | TextFormatFlags.Left);
    if (e.Index == 2 && !e.State.HasFlag(DrawItemState.ComboBoxEdit)) //Index of separator
        e.Graphics.DrawLine(Pens.Red, e.Bounds.Left, e.Bounds.Bottom - 1,
            e.Bounds.Right, e.Bounds.Bottom - 1);
}

This part of code e.State.HasFlag(DrawItemState.ComboBoxEdit) is to prevent drawing separator in the edit portion of control.

enter image description here

Note

  • The answer satisfies the requirement which you asked for in the question. But some users may want grouping items with group text and not just separator. To see a ComboBox which supports such group texts you can take a look at A ComboBox Control with Grouping by Brad Smith. (Alternate link.)

Upvotes: 4

Related Questions