如何将 ComboBox 的第一项设置为已选中?
How put 1st item of ComboBox as already selected?
如何将 ComboBox 的第一项(索引 0)设置为已选中?
procedure TForm1.FormCreate(Sender: TObject);
begin
with ComboBox1.Items do
begin
Add('1st Item');
Add('2nd Item');
Add('3rd Item');
end;
end;
// PS: Change the Style property of ComboBox1 to csOwnerDrawFixed
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;
只需将 ItemIndex
设置为 0:
procedure TForm1.FormCreate(Sender: TObject);
begin
with ComboBox1.Items do
begin
Add('1st Item');
Add('2nd Item');
Add('3rd Item');
end;
ComboBox1.ItemIndex := 0;
end;
我完整地保留了 with
子句,但顺便说一句,我不是他们的忠实粉丝。
我只想指出一个“陷阱”。如果在添加任何项目之前设置 ItemIndex
,它将不起作用,因为还没有项目 0,但它也不会抛出错误。
如何将 ComboBox 的第一项(索引 0)设置为已选中?
procedure TForm1.FormCreate(Sender: TObject);
begin
with ComboBox1.Items do
begin
Add('1st Item');
Add('2nd Item');
Add('3rd Item');
end;
end;
// PS: Change the Style property of ComboBox1 to csOwnerDrawFixed
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;
只需将 ItemIndex
设置为 0:
procedure TForm1.FormCreate(Sender: TObject);
begin
with ComboBox1.Items do
begin
Add('1st Item');
Add('2nd Item');
Add('3rd Item');
end;
ComboBox1.ItemIndex := 0;
end;
我完整地保留了 with
子句,但顺便说一句,我不是他们的忠实粉丝。
我只想指出一个“陷阱”。如果在添加任何项目之前设置 ItemIndex
,它将不起作用,因为还没有项目 0,但它也不会抛出错误。