Search code examples
delphidelphi-xe

How can I dynamically create a StringGrid at runtime?


I'm having trouble creating a StringGrid at runtime. Baring in mind I'm not that experienced at stuff like this, can anyone explain how to do this? This is the code I have so far...

unit uDynStringGrid;

interface

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

type
  TfrmMyForm = class(TForm)
    StringGrid1: TStringGrid;
    procedure FormCreate(Sender: TObject);
  private
    MyGrid : TStringGrid ;
  public
    { Public declarations }
  end;

var
  frmMyForm: TfrmMyForm;

implementation

{$R *.dfm}

procedure TfrmMyForm.FormCreate(Sender: TObject);
var
  MyStringGrid : TStringGrid ;
begin
  MyStringGrid := TStringGrid.Create(frmMyForm);
  MyStringGrid.Visible := true ;
  MyStringGrid.left := 20 ;
  MyStringGrid.top := 20 ;
  MyStringGrid.rowcount := 5 ;
  MyStringGrid.colcount := 5 ;
  MyStringGrid.width := 100 ;
  MyStringGrid.height := 100 ;
  MyStringGrid.Enabled := true ;
  MyStringGrid.cells[1,1] := 'hi' ;
  MyGrid := TStringGrid.Create(frmMyForm) ;
  MyGrid := MyStringGrid ;
end;

end.

Solution

  • What your code is missing is setting your grid parent MyGrid.Parent := Self;

    Also, you don't need local variable MyStringGrid, since you have MyGrid variable declared at form level.

    Another thing you should avoid is referencing form, in its own code, through global variable. Use Self instead.

    procedure TfrmMyForm.FormCreate(Sender: TObject);
    begin
      MyGrid := TStringGrid.Create(Self);
      MyGrid.Parent := Self;
      MyGrid.Visible := true;
      MyGrid.left := 20;
      MyGrid.top := 20;
      MyGrid.rowcount := 5;
      MyGrid.colcount := 5;
      MyGrid.width := 100;
      MyGrid.height := 100;
      MyGrid.Enabled := true;
      MyGrid.cells[1, 1] := 'hi';
    end;