Home > Enterprise >  How to display invalid value text to the user in Combo Box in WinForm C#
How to display invalid value text to the user in Combo Box in WinForm C#

Time:06-06

I have a Combobox in WinForms with a set of values in it. Now I'll check if the value selected in the combo box is valid or not. Once done, if the value is invalid, I need to show the value in red colour. How to do it? For example: Consider a ComboBox with elements {apple, mango, orange}. Now a new element is added to the list, say, Carrot. Given that, the carrot is an invalid value, I want to show the value carrot in Red Color in the UI. Please let me know how to do it.

Thanks in advance.

CodePudding user response:

Set DrawMode property of your combo box to OwnerDrawFixed

this.comboBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;

Define method for custom drawing of combo box items

private void ComboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var text = comboBox1.Items[e.Index] as string;
    e.DrawBackground();
    if (text == "orange")
    {
        TextRenderer.DrawText(e.Graphics,
            text, e.Font, e.Bounds.Location, Color.Red);
    }
    else
    {
        TextRenderer.DrawText(e.Graphics,
            text, e.Font, e.Bounds.Location, e.ForeColor);
    }
}

Subscribe this method to event DrawItem of your combo box

this.comboBox1.DrawItem  = 
    new System.Windows.Forms.DrawItemEventHandler(this.ComboBox1_DrawItem);
  • Related