如何在Delphi 7中创建两列(一个隐藏)的组合框?
发布时间:2020-12-15 10:11:22 所属栏目:大数据 来源:网络整理
导读:如何创建一个TComboBox,其中有两列隐藏了其中一列,以便它可以保存id值以及其中的实际项目?然后如何以编程方式获取该id值? 解决方法 这里不需要两列. 您可以利用TComboBox.Items(与Delphi中的许多其他东西一样,如TStringList,TMemo.Lines和TListBox.Items)
如何创建一个TComboBox,其中有两列隐藏了其中一列,以便它可以保存id值以及其中的实际项目?然后如何以编程方式获取该id值?
解决方法
这里不需要两列.
您可以利用TComboBox.Items(与Delphi中的许多其他东西一样,如TStringList,TMemo.Lines和TListBox.Items)来自TStrings的事实,TStrings同时具有字符串和对象属性.对象存储TObject大小的任何东西,它是一个指针. 这意味着您可以存储整数值,只需在添加时将其类型化为TObject,并在检索时将其强制转换回Integer. 像这样的东西应该工作: procedure TForm1.FormCreate(Snder: TObject); var i: Integer; sItem: String; begin for i := 0 to 9 do begin sItem := Format('Item %d',[i]); ComboBox1.Items.AddObject(sItem,TObject(i)); end; end; 要检索值: procedure TForm1.ComboBox1Click(Sender: TObject); var Idx: Integer; Value: Integer; begin Idx := ComboBox1.ItemIndex; if Idx <> -1 then begin Value := Integer(ComboBox1.Items.Objects[Idx]); // Do something with value you retrieved end; end; 请注意,由于Objects属性实际上是用于存储对象,因此这为您提供了很大的灵活性.这是一个示例(故意非常简单)将客户的联系信息存储在关联的对象实例中,并在选择列表框中的项目时将其显示在标签中. unit Unit1; interface uses Windows,Messages,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls; type TCustomer=class private FContact: string; FPhone: string; public constructor CreateCustomer(const AContact,APhone: string); property Contact: string read FContact write FContact; property Phone: string read FPhone write FPhone; end; TForm1 = class(TForm) ListBox1: TListBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; lblContact: TLabel; lblPhone: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ListBox1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} { TCustomer } constructor TCustomer.CreateCustomer(const AContact,APhone: string); begin inherited Create; FContact := AContact; FPhone := APhone; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); var i: Integer; begin for i := 0 to ListBox1.Items.Count - 1 do ListBox1.Items.Objects[i].Free; end; procedure TForm1.FormCreate(Sender: TObject); begin lblContact.Caption := ''; lblPhone.Caption := ''; // Create some customers. Of course in the real world you'd load this // from some persistent source instead of hard-coding them here. ListBox1.Items.AddObject('N Company',TCustomer.CreateCustomer('Nancy','555-3333')); ListBox1.Items.AddObject('B Company',TCustomer.CreateCustomer('Brad','555-1212')); ListBox1.Items.AddObject('A Company',TCustomer.CreateCustomer('Angie','555-2345')); end; procedure TForm1.ListBox1Click(Sender: TObject); var Cust: TCustomer; begin if ListBox1.ItemIndex <> -1 then begin Cust := TCustomer(ListBox1.Items.Objects[ListBox1.ItemIndex]); lblContact.Caption := Cust.Contact; lblPhone.Caption := Cust.Phone; end; end; end. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |