Changing the background color individual Combobox or ListBox items

To change the text/background color of an individual item in a ListBox or ComboBox, you'll need to render the items manually by using the OnDrawItem event.  You'll also need to make the ListBox or ComboBox owner-drawn by setting the Style property accordingly.

The OnDrawItem event can sometimes be confusing.  The thing to know is that the associated event handler is called repeatedly for every item that needs repainting.  This means there's no needs for hard-coded iteration in the drawing routine.  The Index paramter is used to indicate what item is currently being drawn. 

The following code will change background color of a ListBox's first item.  The code is virtually identical for a ComboBox.  Note: The ListBox must be owner-drawn (Style set to lbOwnerDrawFixed or lbOwnerDrawVariable)
 

KEYWORDS: OwnerDrawn, OnDrawItem, TextOut, FillRect 



const int target_index = 0;  // first item for example
//---------------------------------------------------------------------------

void __fastcall TForm1::ListBox1DrawItem(TWinControl *Control, int
Index, TRect &Rect, TOwnerDrawState State) 

    // eliminate artifacts
    ListBox1->Canvas->FillRect(Rect); 

    // check to see if Index refers to our item 
    // that's to be red
    if (Index == target_index) 
    { 
        // color the line 
        ListBox1->Canvas->Brush->Color = clRed; 
        ListBox1->FillRect(Rect); 
    } 

    // check for selection rectangle 
    else if (State.Contains(odSelected)) 
    {
        ListBox1->Canvas->Brush->Color = clHighlight;
    }
    ListBox1->Canvas->Brush->Color = ListBox1->Brush->Color; 

    // render the text
    ListBox1->Canvas->TextOut(Rect.Left + 1, Rect.Top, 
                              ListBox1->Items->Strings[Index]);