Question

i was wondering if it is possible to create a combo box (drop down list) and to paint specific cells in the drop down list. so, if i have five items in the drop down list, the second item and the last item will be painted in blue for example and the others in gray.. is it possible?

System.Windows.Forms.ComboBox comboBox;
comboBox = new System.Windows.Forms.ComboBox();
comboBox.AllowDrop = true;
comboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
comboBox.FormattingEnabled = true;
comboBox.Items.AddRange(excel.getPlanNames());
comboBox.Location = new System.Drawing.Point(x, y);
comboBox.Name = "comboBox1";
comboBox.Size = new System.Drawing.Size(sizeX, sizeY);
comboBox.TabIndex = 0;
group.Controls.Add(comboBox);

thank's for any help..

Was it helpful?

Solution

You can use the DrawItem Event.

First you have to set the DrawMode of the ComboBox to OwnerDrawFixed

Then you set the DrawItem to something like the following:

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    Font font = (sender as ComboBox).Font;
    Brush backgroundColor;
    Brush textColor;

    if (e.Index == 1 || e.Index == 3)
    {
        if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
        {
            backgroundColor = Brushes.Red;
            textColor = Brushes.Black;
        }
        else
        {
            backgroundColor = Brushes.Green;
            textColor = Brushes.Black;
        }
    }
    else
    {
        if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
        {
            backgroundColor = SystemBrushes.Highlight;
            textColor = SystemBrushes.HighlightText;
        }
        else
        {
            backgroundColor = SystemBrushes.Window;
            textColor = SystemBrushes.WindowText;
        }
    }
    e.Graphics.FillRectangle(backgroundColor, e.Bounds);
    e.Graphics.DrawString((sender as ComboBox).Items[e.Index].ToString(), font, textColor, e.Bounds);
}

This example will make the default background colour Green with black text, and the highlighted item will have a red background and black text, of the items at indexes 1 and 3.

You could also set the font of individual items using the font variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top