Changing the text color of 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 text color of a ListBox's second item.  The code is virtually identical for a ComboBox.  Note: The ListBox must be owner-drawn (Style set to lbOwnerDrawFixed or lbOwnerDrawVariable)
 

KEYWORDS:  owner-drawn, OnDrawItem, TextOut, FillRect 
 



const int target_index = 1;  // second 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 the 
    // item that we want to color red
    if (Index == target_index) 
    { 
        // Color the text
        ListBox1->Canvas->Font->Color = clRed; 
    } 

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

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