【问题标题】:How put 1st item of ComboBox as already selected?如何将 ComboBox 的第一项设置为已选择?
【发布时间】:2021-05-14 14:56:16
【问题描述】:

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

【问题讨论】:

  • 你试过ComboBox1.ItemIndex := 0;吗?

标签: delphi combobox delphi-10.3-rio


【解决方案1】:

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

【讨论】:

  • 阿门重新“与”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 2016-05-06
  • 1970-01-01
相关资源
最近更新 更多