Search code examples
lazarusdelphi

Add rows to StringGrid with variables as cell data?


I have a form with two TEdit components. On another form, I would like a row to be added to the TStringGrid with the data from the two TEdits. How do I do this?

This is what I have so far:

procedure TSecondForm.StartButtonClick(Sender: TObject);
begin
  string1 := Edit1.Text;
  string2 := Edit2.Text;

  MainForm.StringGrid1.RowCount := MainForm.StringGrid1.RowCount + 1; // this adds the rows, but I don't know how to make it so that the two variables are inputed into two seperate cells
end;                      

Solution

  • In Delphi and FreePascal/Lazarus, you can use the TStringGrid.Cells property after incrementing the RowCount, eg:

    procedure TSecondForm.StartButtonClick(Sender: TObject);
    var
      string1, string2: string;
      row: integer;
    begin
      string1 := Edit1.Text;
      string2 := Edit2.Text;
    
      row := MainForm.StringGrid1.RowCount;
      MainForm.StringGrid1.RowCount := row + 1;
      MainForm.StringGrid1.Cells[0, row] := string1;
      MainForm.StringGrid1.Cells[1, row] := string2;
    end;
    

    In FreePascal/Lazarus only, you can alternately use the TStringGrid.InsertRowWithValues() method instead:

    procedure TSecondForm.StartButtonClick(Sender: TObject);
    var
      string1, string2: string;
    begin
      string1 := Edit1.Text;
      string2 := Edit2.Text;
    
      MainForm.StringGrid1.InsertRowWithValues(MainForm.StringGrid1.RowCount, [string1, string2]);
    end;