delphi - 如何将 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;
解决方案
只需设置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,但它也不会抛出错误。
推荐阅读
- c# - C# - 是否有理由不实例化一个类并在一行代码中使用它?
- c++ - 我在循环中用 XStoreName 杀死了我的 Linux Mint,我该如何修复它?
- excel-formula - 如何使用 Excel 公式获取列中第一个非零单元格?
- java - 无法从控制器中的 src/main/webapp/WEB-INF/resources/img 访问图像文件以在 jsp 中显示
- azure-devops - 如何在 Azure DevOps 中定义发布管道以实现可维护的蓝绿部署
- javascript - 表单验证和提交未按预期工作
- python-3.x - 简单表创建中的 Python sqlite3 OperationalError
- xero-api - 在 Xero-API 查询中添加“或”
- android - 为我的项目启用 Google Cloud Build API 时出错?
- jenkins - “按名称过滤分支”在 Jenkins 构建触发器中显示错误