Title: ComboBox with Icon
Question: How can I have a TComboBox which has Icons for its items?
Answer:
This is just a sample code to show you how you can do it.
You can change the code for your own purpose.
Follow these steps :
1. Create a new application (I did it using Delphi5).
2. Add an ImageList and a ComboBox to Form1.
3. Double click on ImageList1 and add some icons to it. (At least 3 icons for this example)
4. Add this code for OnCreate of Form1 :
procedure TForm1.FormCreate(Sender: TObject);
begin
with ComboBox1.Items do begin
Add('1st Item');
Add('2nd Item');
Add('3rd Item');
end
end;
5. Change the Style property of ComboBox1 to csOwnerDrawFixed
6. Write the following code for OnDrawItem of ComboBox1
procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
AnIcon : TIcon;
begin
AnIcon := TIcon.Create;
try
ImageList1.GetIcon (Index,AnIcon);
with Control as TComboBox do begin
Canvas.Draw (Rect.Left,Rect.Top,AnIcon);
Canvas.TextOut (Rect.Left + ImageList1.Width,Rect.Top,Items[Index]);
end;
finally
AnIcon.Free;
end;
end;
Run the application and enjoy it,
Newstar.