Search code examples
delphidelphi-10-seattle

Comparing DBgrid and ClientDataSet field names


How to compare field names of clientdataset and dbgrid? For example check every field as visible in clientdataset if it exists in dgbrid?


Solution

  • Solution:

    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;
    

    Working example:

    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.
    

    Notes:

    You can check TField.Visible and/or TColumn.Visible properties.