Home > front end >  How to avoid having a fixed column when adding columns dynamically to a TStringGrid at runtime?
How to avoid having a fixed column when adding columns dynamically to a TStringGrid at runtime?

Time:01-06

I am using Lazarus 0.9.30.2. I have a standard TForm with a standard TStringGrid on it. The string grid has no columns or rows on it at design time. In the Object Inspector the following values are set.

ColCount = 0
Columns = 0
FixedCols = 0
FixedRows = 0
RowCount = 0

I want to add a number of TGridColumns at run time, and have been able to do so but always get a fixed column, which I don't want. I have written code very similar to the sample below to do so. When I compile and run it I get the following.

enter image description here

How do I get rind of the fixed column at run time and just leave the remaining columns?

unit test;

{$mode objfpc}{$H }

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Grids;

type
  TForm1 = class(TForm)
    SgGrid: TStringGrid;
    procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1; 

implementation

{$R *.lfm}

procedure TForm1.FormCreate(Sender: TObject);
var
  GridColumn : TGridColumn;
  anIndex    : integer;
begin
  for anIndex := 0 to 5 do
    begin
      GridColumn := SgGrid.Columns.Add;
      GridColumn.Width := 50;
      GridColumn.Title.Caption := 'Col '   inttostr(anIndex);
    end; {for}
end;

end.                                                                                                                                              

CodePudding user response:

I think it's such kind of a feature (or bug from another point of view). If you have at design time your string grid empty (0 cols, 0 rows), at runtime when you add a column, the following properties are being set to the default, stored values.

How to workaround it:

  • either set the TStringGrid.FixedCols to 0 at runtime after you add at least one column, for your case simply after when you add all of them

  • or set the TStringGrid.ColCount and TStringGrid.FixedRows to 1 at designtime, you will see the column, but the TStringGrid.Columns collection remains empty, so there's no need to worry that you will get one extra column at runtime (in Delphi e.g. you can't even set the column nor row count to 0)

I'm suspecting the TCustomGrid.AdjustCount procedure, but it's just a wild guess and off topic here.

  • Related