如何将ComboBox的第一个项(索引0)设置为默认选中状态?
如何将ComboBox的第一个项(索引0)设置为已选中状态?
实现方法非常简单,只需要将ComboBox控件的ItemIndex属性设置为0即可。你可以选择两种实现方式:
- 静态设置:在Delphi窗体设计器的属性面板中,直接找到对应ComboBox控件的
ItemIndex属性,填入数值0即可 - 动态设置:在代码中条目添加完成后,手动给
ItemIndex赋值,你提供的代码修改后如下:
procedure TForm1.FormCreate(Sender: TObject); begin with ComboBox1.Items do begin Add('1st Item'); Add('2nd Item'); Add('3rd Item'); end; // 选中索引为0的第一个条目 ComboBox1.ItemIndex := 0; end; // 备注:将ComboBox1的Style属性设置为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;
注意:动态设置时一定要保证赋值操作在条目添加完成后执行,否则会因为索引不存在导致赋值无效。如果后续清空并重载了ComboBox的条目,需要重新执行赋值操作才能再次选中第一个条目。
内容的提问来源于stack exchange,提问作者user13342561
相关产品推荐
相关产品推荐

