Colour Individual Items in a winforms ComboBox?

Mike picture Mike · Jan 12, 2011 · Viewed 48.6k times · Source

I have a dilemma whereby I have a form which contains a number of comboboxes that contain information/options/items that may be invalid/out-of-date in certain circumstances.

I can't simply remove the out-of-date information from the items, but I do want to give the user a visual-clue when options are invalid.

I was thinking of colouring in the Items (probably red) to indicate if & when they are invalid. I don't necessarily need to prevent a user from selecting an invalid option, just make them visually aware that they are doing so.

Can this be done? Can you - dyamically - change the colo(u)r of combobox items?

Thanks,

Answer

Pabuc picture Pabuc · Jan 12, 2011

You may try DrawItem event of ComboBox. Keep your dates on a list and compare them with ID's and brush your items.

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{    
    // Draw the background 
    e.DrawBackground();        

    // Get the item text    
    string text = ((ComboBox)sender).Items[e.Index].ToString();

    // Determine the forecolor based on whether or not the item is selected    
    Brush brush;
    if (YourListOfDates[e.Index] < DateTime.Now)// compare  date with your list.  
    {
        brush = Brushes.Red;
    }
    else
    {
        brush = Brushes.Green;
    }

    // Draw the text    
    e.Graphics.DrawString(text, ((Control)sender).Font, brush, e.Bounds.X, e.Bounds.Y);
}

To fire this event (thanks to @Bolu)

You need to change ComboBox.DrawMode to OwnerDrawFixed/OwnerDrawVariable to fire the comboBox_DrawItem