unit TListIndexOf;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    PaintBox1: TPaintBox;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

// BeginExample: TListIndexOf
// Method: Classes.TList.Remove
// Method: Classes.TList.IndexOf
// Method: Graphics.TCanvas.TextOut
// Routine: System.Dispose

// BeginCode
{
The following code adds an object to MyList if it isn’t
already in the list.
}
type
  PMyList = ^AList;
  AList = record
    I: Integer;
    C: Char;
  end;
var
  Form1: TForm1;
  MyList: TList;
  ARecord1, ARecord2: PMyList;

implementation

{$R *.dfm}

procedure DisplayTList(TheList: TList);
var
  ARecord: PMyList;
  B: Byte;
  Y: Word;
begin
    { Now paint the items onto the paintbox}
    Y := 10;             {Variable used in TextOut function}
    for B := 0 to (TheList.Count - 1) do
    begin
      ARecord := TheList.Items[B];
      Form1.PaintBox1.Canvas.TextOut(10, Y, IntToStr(ARecord^.I)); {Display I}
      Y := Y + 30;  {Increment Y Value again}
      Form1.PaintBox1.Canvas.TextOut(10, Y, ARecord^.C);  {Display C}
      Y := Y + 30;  {Increment Y Value}
    end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if (MyList.IndexOf(ARecord1) = -1) then MyList.Add(ARecord1);
  DisplayTList(MyList);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  if (MyList.IndexOf(ARecord2) = -1) then MyList.Add(ARecord2);
  DisplayTList(MyList);
end;

procedure TForm1.Button3Click(Sender: TObject);
var
  ARecord: PMyList;
  B: Integer;
begin
  if (MyList.Count <> 0) then
  begin
    for B := (MyList.Count - 1) downto 0 do
    begin
      ARecord := MyList.Items[B];
      MyList.Remove(ARecord);
    end;
  end;
  Form1.PaintBox1.Repaint;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  MyList := TList.Create;
  New(ARecord1);
  ARecord1^.I := 100;
  ARecord1^.C := 'Z';
  New(ARecord2);
  ARecord2^.I := 200;
  ARecord2^.C := 'X';
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  Dispose(ARecord1);
  Dispose(ARecord2);
  MyList.Free;
end;
// EndCode
// EndExample: TListIndexOf
end.
