首页 > 解决方案 > 如何将 ComboBox 的第一项设置为已选择?

问题描述

如何将 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;

标签: delphicomboboxdelphi-10.3-rio

解决方案


只需设置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,但它也不会抛出错误。


推荐阅读