unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
btnLoad: TButton;
btnSelect42: TButton;
ComboBox1: TComboBox;
Label1: TLabel;
procedure btnLoadClick(Sender: TObject);
procedure btnSelect42Click(Sender: TObject);
procedure ComboBox1Select(Sender: TObject);
private
public
end;
{ TComboBoxHelper }
TComboBoxHelper = class helper for TComboBox
public
procedure ItemAdd(S: String; Id: Integer);
function SelectedId: Integer;
function SetId(Id: Integer): Boolean;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TComboBoxHelper }
procedure TComboBoxHelper.ItemAdd(S: String; Id: Integer);
begin
Items.AddObject(S, TObject(PtrInt(Id)));
end;
function TComboBoxHelper.SelectedId: Integer;
begin
if ItemIndex > -1 then
Result := Integer(PtrInt(Items.Objects[ItemIndex]))
else
Result := -1;
end;
function TComboBoxHelper.SetId(Id: Integer): Boolean;
var I: Integer;
begin
for I := 0 to Pred(Items.Count) do
if Integer(PtrInt(Items.Objects[I])) = Id then
begin
ItemIndex := I;
Exit(True);
end;
Result := False;
end;
{ TForm1 }
procedure TForm1.btnLoadClick(Sender: TObject);
begin
ComboBox1.ItemAdd('Chevrolet', 17);
ComboBox1.ItemAdd('Nissan', 22);
ComboBox1.ItemAdd('Ford', 13);
ComboBox1.ItemAdd('Toyota', 42);
ComboBox1.ItemAdd('VW', 56);
ComboBox1.ItemIndex := 0;
end;
procedure TForm1.btnSelect42Click(Sender: TObject);
begin
if ComboBox1.SetId(42) then
ShowMessage('Item with Id=42 is ' + ComboBox1.Text)
else
ShowMessage('No item 42');
end;
procedure TForm1.ComboBox1Select(Sender: TObject);
begin
Label1.Caption := ComboBox1.SelectedId.ToString;
end;
end.