delphitdbgrid

How to add a column to a DBGrid by code?


Using a TDBGrid, I want to add a new column and set its name by code.

How to do this at runtime?


Solution

  • TColumn class doesn't have a Name property. Note that it doesn't inherits from TComponent (TColumn -> TCollectionItem -> TPersistent -> TObject) and its parent classes don't add any Name property.

    Anyhow, you can add a new column to a TDBGrid by simply calling the Add method of the Columns collection:

    var
      Col : TColumn;
    begin
      Col := DBGrid1.Columns.Add;
      //then you can set its properties as your needs
      Col.Title.Caption := 'MyNewColumn';
    end;