unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
ListBox1: TListBox;
Button1: TButton;
Edit1: TEdit;
lblColor: TLabel;
lblNumber: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ListBox1Data(Control: TWinControl; Index: Integer;
var Data: string);
function ListBox1DataFind(Control: TWinControl;
FindString: string): Integer;
procedure ListBox1DataObject(Control: TWinControl; Index: Integer;
var DataObject: TObject);
procedure Button1Click(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
ObjList: TList;
end;
TMyObj = class
fColor: string;
fNumber: Integer;
constructor create(const color: string; const Number: Integer);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TMyObj }
constructor TMyObj.create(const color: string; const Number: Integer);
begin
fColor := color;
fNumber := number;
end;
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
// create a TList and add some data to it.
ObjList := TList.Create;
ObjList.Add(TMyObj.Create('Red', 1));
ObjList.Add(TMyObj.Create('Yellow', 15));
ObjList.Add(TMyObj.Create('Blue', 21));
ObjList.Add(TMyObj.Create('Green', 37));
ObjList.Add(TMyObj.Create('Brown', 16));
ObjList.Add(TMyObj.Create('Black', 5135));
ObjList.Add(TMyObj.Create('White', 4));
ObjList.Add(TMyObj.Create('Orange', 333));
// ABSOLUTELY REQUIRED Set the count of the virtual listbox
Listbox1.Count := ObjList.Count;
end;
procedure TForm1.FormDestroy(Sender: TObject);
var
I: Integer;
begin
for I := 0 to ObjList.count - 1 do
TMyObj(ObjList.Items[I]).free;
ObjList.Free;
end;
procedure TForm1.ListBox1Data(Control: TWinControl; Index: Integer;
var Data: string);
// REQUIRED
// return a string to put in the list box
begin
Data := TMyObj(ObjList.Items[Index]).fColor;
end;
procedure TForm1.ListBox1DataObject(Control: TWinControl; Index: Integer;
var DataObject: TObject);
// USUALLY REQUIRED
// return an object associated with the current selection of the list box
begin
DataObject := ObjList.Items[Index];
end;
function TForm1.ListBox1DataFind(Control: TWinControl;
FindString: string): Integer;
// USUALLY REQUIRED
// given a string FindString, return its index
var
I: Integer;
begin
// the simplest but most brain dead approach
result := -1;
for I := 0 to TListBox(Control).Count - 1 do
if TListBox(Control).Items[I] = FindString then
result := I;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ListBox1.ItemIndex := ListBox1.Items.IndexOf(edit1.Text);
// I don't think this next should be necessary but..
ListBox1Click(Self);
end;
procedure TForm1.ListBox1Click(Sender: TObject);
begin
lblColor.Caption := TMyObj(ListBox1.Items.objects[Listbox1.ItemIndex]).fColor;
lblNumber.Caption :=
IntToStr(TMyObj(ListBox1.Items.objects[Listbox1.ItemIndex]).fNumber);
end;
end.