比较DBgrid和ClientDataSet字段名称

时间:2018-03-01 14:28:02

标签: delphi delphi-10-seattle

如何比较clientdataset和dbgrid的字段名?例如,如果在dgbrid中存在,则检查clientdataset中可见的每个字段?

1 个答案:

答案 0 :(得分:2)

<强>解决方案:

for i := 0 to cds.Fields.Count-1 do begin
   for j := 0 to grid.Columns.Count-1 do begin
       if cds.Fields[i].FieldName = grid.Columns[j].FieldName then begin
          ShowMessage('Field: ' + cds.Fields[i].FieldName);
          Break;
       end;
   end;
end;

工作示例

unit frmMain;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, DB, DBClient, Grids, DBGrids;

type
  TForm1 = class(TForm)
    btnCheck: TButton;
    ds: TDataSource;
    cds: TClientDataSet;
    grid: TDBGrid;
    procedure btnCheckClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btnCheckClick(Sender: TObject);
var
   i, j: Integer;
begin
   // Controls
   if cds.Active then cds.Close;
   ds.DataSet := cds;
   grid.DataSource := ds;

   // Dataset. Create dataset with three fields.
   cds.FieldDefs.Clear;
   cds.FieldDefs.Add('FIELD1', ftString, 10, False);
   cds.FieldDefs.Add('FIELD2', ftString, 20, False);
   cds.FieldDefs.Add('FIELD3', ftString, 30, False);
   try
      cds.CreateDataSet;
      cds.Open;
   except
      on E: Exception do begin
         ShowMessage('Error: ' + E.Message);
         Exit;
      end{on};
   end{try};

   // Grid. Set grid with one column.
   grid.Columns.Clear;
   with grid.Columns.Add do begin
      FieldName := 'FIELD1';
   end{with};

   // Check every field
   for i := 0 to cds.Fields.Count-1 do begin
      for j := 0 to grid.Columns.Count-1 do begin
          if cds.Fields[i].FieldName = grid.Columns[j].FieldName then begin
             ShowMessage('Field: ' + cds.Fields[i].FieldName);
             Break;
          end{if};
      end{if};
   end{if};
end;

end.

备注:

您可以检查TField.Visible和/或TColumn.Visible属性。