Get component index at runtime

Posted in Components

Use IndexInParent function:

procedure TForm1.Button3Click(Sender: TObject);
begin
  MessageBox(
    Handle, 
    PChar('Index = '+IntToStr(IndexInParent(Button3))),
    'Information',  
    MB_OK);
end;

function TForm1.IndexInParent(VControl: TControl): Integer;
var
  ParentControl: TWinControl;
begin
  ParentControl:=TForm(VControl.Parent);
  if (ParentControl<>nil) then
    for Result:=0 to ParentControl.ControlCount-1 do
      if (ParentControl.Controls[Result]=VControl) then
        Exit;
  Result:=-1;
end;