change colour of combobox items.

boycoder
boycoder used Ask the Experts™
on
Hi how can i change the colour of the combobox for each item?

for the first item which is 0 i want red
for the second i want yellow and the third i want green

Thanks.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
havnt got time to do that, also i think last time i had a quick look it was about using the color picker, i really just need some simple source for the draw event or something. cheers
Commented:
Done.
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, shellapi;

type
  TForm1 = class(TForm)
    ComboBox1: TComboBox;
    procedure FormCreate(Sender: TObject);

    procedure ComboBox1DrawItem(Control: TWinControl; Index: Integer;
      Rect: TRect; State: TOwnerDrawState);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;


const Colors: array[0..2] of TColor =
 (clGreen, clRed, clYellow) ;

 implementation

{$R *.DFM}


procedure TForm1.FormCreate(Sender: TObject);
begin
 ComboBox1.Items.Add('Item 1');
 ComboBox1.Items.Add('Item 2');
 ComboBox1.Items.Add('Item 3');
 ComboBox1.ItemIndex := 0;
end;



procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
begin
 with Control as TComboBox do
 begin
   Canvas.Brush.Color := TColor(Colors[Index]);
   Canvas.FillRect(Rect);
   Canvas.TextOut(Rect.Left,Rect.Top, ComboBox1.Items[Index])
 end;
end;


end.

Open in new window

Introduction to Web Design

Develop a strong foundation and understanding of web design by learning HTML, CSS, and additional tools to help you develop your own website.

Author

Commented:
thnx but i cant seem to get it to work, what is the state of the combobox? any suggestions what culd be wrong.. It compiles, but no change.

Author

Commented:
im using flatcombobox, maybe thats the problem as i did the test on a blank app and that works with the default controls.

Author

Commented:
A

Commented:
procedure TForm1.FormCreate(Sender: TObject);
begin
 ComboBox1.Items.Add('Item 1');
 ComboBox1.Items.Add('Item 2');
 ComboBox1.Items.Add('Item 3');
 ComboBox1.ItemIndex := 0;

// Sorry, I FORGOT THIS line
 ComboBox1.Style := csOwnerDrawVariable;

end;

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial