Intrepid
Intrepid

Reputation: 2831

Owner draw combo box with color picker

I have a user control with the following code:

public partial class ColorComboBox : ComboBox
{
    public ColorComboBox()
    {
        InitializeComponent();

        this.DropDownStyle = ComboBoxStyle.DropDownList;
        this.DrawMode = DrawMode.OwnerDrawFixed;

        string[] colorNames = System.Enum.GetNames( typeof( KnownColor ) );

        this.Items.AddRange( colorNames );
    }

    protected override void OnDrawItem( DrawItemEventArgs e )
    {
        if ( e.Index < 0 ) return;

        this.SuspendLayout();

        string s = (string)this.Items[ e.Index ];

        using ( Brush b = new SolidBrush( Color.FromName( s ) ) )
        {
            e.Graphics.DrawRectangle( Pens.Black, 2, e.Bounds.Top + 1, 20, 11 );
            e.Graphics.FillRectangle( b, 3, e.Bounds.Top + 2, 19, 10 );

            e.Graphics.DrawString( s, this.Font, Brushes.Black, 25, e.Bounds.Top );
        }

        e.DrawFocusRectangle();

        this.ResumeLayout();

    }

}

After adding an instance of this ComboBox to a form, I am having a weird problem; each item under the mouse pointer is changing the entry to bold.

Does anyone have any idea why this is happening?

Thanks.

Upvotes: 1

Views: 2099

Answers (2)

A Ghazal
A Ghazal

Reputation: 2823

Thanks it's working fine

To use it:

    label1.Text = colorComboBox1.SelectedItem.ToString();
    label1.BackColor  = Color.FromName(colorComboBox1.SelectedItem.ToString());

or

    string s = (string)colorComboBox1.Items[colorComboBox1.SelectedIndex];
    label1.Text = s; 
    label1.BackColor  = Color.FromName(s);

Upvotes: 0

Intrepid
Intrepid

Reputation: 2831

I have managed to sort this out by adding the following line:

e.DrawBackground();

Upvotes: 1

Related Questions