简体   繁体   中英

Create table generator in Delphi

I'm trying to create a table generator in delphi 10, like the one in the picture. I can't find any options to edit/add buttons the "column name, column type and column size".

样机屏幕截图

procedure TForm1.AddColumnClick(Sender: TObject); 
var 
  Col : TColumn; 
begin
  Col := DBGrid2.Columns.Add; 
  Col.Title.Caption := 'MyNewColumn'; 
end; 

If this is to add a column, how do I get the code for the column type and its size?

Your edit which asks

how do I get the code for the column type and its size?

completely changes what your q is about. It is still far too broad, and it seems that you are intent on re-inventing the wheel, because Delphi's TDBGrid has the necessary facilities to do what you seem to want built-in. Here is my suggestion for further study:

  • Learn how to create persistent TFields on your dataset which will be supplying the data for the grid. See http://docwiki.embarcadero.com/RADStudio/Rio/en/Persistent_Field_Components The pont of doing this is that once the dataset has persistent TFields, the design-time facilities supporting the creation of TDBGrid columns become available.

  • Once your dataset has persistent TFields, in the IDE clear any columns the TDBGrid already has, then

  • Double-click on the DBgrid. You will get a pop-up columns editor with a caption like Editing DBGrid1.Columns . Right click in the columns editor and select Add All Fields from the context menu. That will create the columns withthe default datatypes and sizes that Delphi uses for the grid's columns, which is what you seem to be trying to do yourself.

To answer your specific question, you can get the size and datatype of a field of the dataset using

AField := DBGrid1.Columns[i].Field;
Size := AField.Size;
DataType := AField.DataType;

Working out how to set a suitable column width from the Size of the associated TField is left as an exercise to the reader.

You need to study the source code of TDBGrid to see how the grid columns adapt their behaviour to the specific TField types of the dataset.

To assist in that, add a button to your form and the following code

type
 TMyDBGrid = class(TDBGrid);

procedure TForm1.btnCreateColumnsClick(Sender: TObject);
begin
  DBGrid1.Columns.Clear;
  TMyDBGrid(DBGrid1).CreateColumns;
end;

The TMyGrid type declaration is to get access to the protected CreateColumns method of the grid. You can then put a debuuger breakpoint on the TMyDBGrid(DBGrid1).CreateColumns call and trace into it to see what it does.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM