Save records from a tcxgrid into an xml file - Delphi XE2

1.1k views Asked by At

I would like to know the simplest way to get what you see in a tcxgrid and at the click of a button, will then save the records into an xml file.

1

There are 1 answers

0
MartynA On BEST ANSWER

The only slight problem with using the ExportGridToXML procedure is that it's fairly well hidden - you need to add the cxGridExportLink unit to your uses list.

uses
  cxGridExportLink;

procedure TForm1.SaveToXML1;
var
  FileName : String;
begin
  FileName := IncludeTrailingPathDelimiter(GetEnvironmentVariable('Temp'));
  FileName := FileName + 'Grid.XML';
  ExportGridToXML(FileName, cxGrid1);
end;

That will save the XML file to \users[your name]\appdata\local\Temp. Note that it will include only the dataset fields that have columns in the grid, which may be what you want, or not, depending.

The procedure below shows another way of saving a dataset to XML that bypasses the grid, and saves the data values for all of the dataset's fields, regardless of whether they have columns in a cxGrid. It works by copying the dataset's data to a temporary TClientDataSet via a TDataSetProvider and then using the TClientDataSet's built-in facility to save its data to XML. It will respect any filter that the dataset passed to it might have in place.

procedure TForm1.SaveToXML2(DataSet : TDataSet);
var
  FileName : String;
  DSP : TDataSetProvider;
  CDS : TClientDataSet;
begin
  FileName := IncludeTrailingPathDelimiter(GetEnvironmentVariable('Temp'));
  FileName := FileName + 'Grid2.XML';

  DSP := TDataSetProvider.Create(Self);
  CDS := TClientDataSet.Create(Self);

  try
    DSP.DataSet := DataSet;
    DSP.Name := 'TempProvider';
    CDS.ProviderName := DSP.Name;
    DataSet.DisableControls;  // otherwise you will see the source dataset scrolling 
    // if it's shown in a grid
    CDS.Open;
    CDS.SaveToFile(FileName, dfXML);
  finally
    DataSet.EnableControls;
    CDS.Free;
    DSP.Free;
  end;
end;