Iterating Through Rows in Borland TDBGrid

Applies to TestComplete 15.47, last modified on January 20, 2023

This topic explains how you can iterate through rows of the TDBGrid controls and save the data, which is displayed by the control, to an XML file.

Iterating through grid rows means accessing rows in a series, one by one. You may need to iterate through TDBGrid rows if you need to locate a particular row, or perform the same set of operations on each row.

To iterate through grid rows, you can either simulate the keystrokes over the grid window (Up Arrow, Down Arrow and others) or use methods and properties of the TDataset object, whose data the grid displays. In general, using the methods and properties of the dataset object is preferable, since, if the TDBGrid control supports multiple row selection, simulating keystrokes will remove the selection from the selected rows.

The methods of the TDataset object changes the active record in the dataset and when this happens, the TDBGrid control automatically selects the appropriate grid row. To iterate through grid rows you can use the following dataset methods and properties:

Method (Property) Description
RecordCount Returns the number of records in the dataset. If the dataset is filtered, the property will return the number of records that match the filter.
First Activates the first record in the dataset.
Last Activates the last record in the dataset.
Next Activates the next record in the dataset.
Prior Activates the previous record in the dataset.
MoveBy (Distance) Activates the record that resides a specified number of records away from the current record. Positive value of the Distance parameter means forward movement. Negative value means backward movement.
BOF Returns True if the first record of the dataset is selected.
EOF Returns True if the last record of the dataset is selected.
In order for TestComplete to be able to access these methods and properties, the Delphi and C++Builder Application Support plugin must be installed and enabled, and the tested application must be compiled with debug information (see Debug Info Agent).

Below is a script sample that demonstrates how you can iterate through the TDBGrid rows using methods and properties of the TDataset object.

Example

View description

JavaScript

function Main ()
{
  var p, Grid, FileName;

  // Obtain the grid object
  p = Sys.Process("csdemos");
  p.VCLObject("FrmLauncher").VCLObject("BtnViews").ClickButton();
  Grid = p.VCLObject("FrmViewDemo").VCLObject("Panel2").VCLObject("DBGrid1");

  // Save grid data to a file
  FileName = "C:\\GridData.xml";
  ExportToXml (Grid, FileName);
  Log.File(FileName, "Exported grid data");
}

// Iterate through rows and save the grid contents to a file
function ExportToXml (GridObject, FileName)
{
  var FSO, f, Overwrite, Unicode, CellText;

  Indicator.PushText("Exporting grid data...");

  // Create a text file and open it for writing
  Overwrite = true;
  Unicode = true;
  FSO = getActiveXObject("Scripting.FileSystemObject");
  f = FSO.CreateTextFile (FileName, Overwrite, Unicode);
  
  // Write the root tag (grid)
  f.WriteLine ("<?xml version=\"1.0\"?>");
  f.WriteLine ("<grid>");
  
  // Save the list of grid columns to the file
  f.WriteLine (" <columns>");
  for (let i = 0; i < GridObject.wColumnCount; i++)
    f.WriteLine (" <column>" + ReplaceSpecialChars (GridObject.wColumn(i)) + "</column>");
  f.WriteLine (" </columns>");
  
  // Save the data
  // Activate the first record
  GridObject.DataSource.DataSet.First();
  // Iterate through records
  while (! aqConvert.VarToBool(GridObject.DataSource.DataSet.EOF))
  {
    // The row element corresponds to grid rows
    f.WriteLine (" <row>");

    // Process cells
    for (let i = 0; i < GridObject.wColumnCount; i++)
    {
      // Obtain the cell value
      CellText = GridObject.Columns.Items(i).Field.AsString;
      CellText = ReplaceSpecialChars (CellText); // Replace special characters

      // Write the cell tag
      f.WriteLine (" <cell>" + CellText + "</cell>");
    }

    // Close the row tag
    f.WriteLine (" </row>");

    // Move to the next record
    GridObject.DataSource.DataSet.Next();
  }

  // Close the root tag
  f.WriteLine ("</grid>");

  // Close the file
  f.Close();

  Indicator.PopText();
}

// Replace special characters in the specified string
function ReplaceSpecialChars (str)
{
  var s = aqString.Replace (str, "&", "&amp;", true);
  s = aqString.Replace (s, "<", "&lt;", true);
  s = aqString.Replace (s, ">", "&gt;", true);
  s = aqString.Replace (s, "\"", "&quot;", true);
  s = aqString.Replace (s, "'", "&apos;", true);
  return s;
}

JScript

function Main ()
{
  var p, Grid, FileName;

  // Obtain the grid object
  p = Sys.Process("csdemos");
  p.VCLObject("FrmLauncher").VCLObject("BtnViews").ClickButton();
  Grid = p.VCLObject("FrmViewDemo").VCLObject("Panel2").VCLObject("DBGrid1");

  // Save grid data to a file
  FileName = "C:\\GridData.xml";
  ExportToXml (Grid, FileName);
  Log.File(FileName, "Exported grid data");
}

// Iterate through rows and save the grid contents to a file
function ExportToXml (GridObject, FileName)
{
  var FSO, f, Overwrite, Unicode, i, CellText;

  Indicator.PushText("Exporting grid data...");

  // Create a text file and open it for writing
  Overwrite = true;
  Unicode = true;
  FSO = new ActiveXObject ("Scripting.FileSystemObject");
  f = FSO.CreateTextFile (FileName, Overwrite, Unicode);
  
  // Write the root tag (grid)
  f.WriteLine ("<?xml version=\"1.0\"?>");
  f.WriteLine ("<grid>");
  
  // Save the list of grid columns to the file
  f.WriteLine (" <columns>");
  for (i = 0; i < GridObject.wColumnCount; i++)
    f.WriteLine (" <column>" + ReplaceSpecialChars (GridObject.wColumn(i)) + "</column>");
  f.WriteLine (" </columns>");
  
  // Save the data
  // Activate the first record
  GridObject.DataSource.DataSet.First();
  // Iterate through records
  while (! aqConvert.VarToBool(GridObject.DataSource.DataSet.EOF))
  {
    // The row element corresponds to grid rows
    f.WriteLine (" <row>");

    // Process cells
    for (i = 0; i < GridObject.wColumnCount; i++)
    {
      // Obtain the cell value
      CellText = GridObject.Columns.Items(i).Field.AsString;
      CellText = ReplaceSpecialChars (CellText); // Replace special characters

      // Write the cell tag
      f.WriteLine (" <cell>" + CellText + "</cell>");
    }

    // Close the row tag
    f.WriteLine (" </row>");

    // Move to the next record
    GridObject.DataSource.DataSet.Next();
  }

  // Close the root tag
  f.WriteLine ("</grid>");

  // Close the file
  f.Close();

  Indicator.PopText();
}

// Replace special characters in the specified string
function ReplaceSpecialChars (str)
{
  var s = aqString.Replace (str, "&", "&amp;", true);
  s = aqString.Replace (s, "<", "&lt;", true);
  s = aqString.Replace (s, ">", "&gt;", true);
  s = aqString.Replace (s, "\"", "&quot;", true);
  s = aqString.Replace (s, "'", "&apos;", true);
  return s;
}

Python

def Main ():

  # Obtain the grid object
  p = Sys.Process("csdemos")
  p.VCLObject("FrmLauncher").VCLObject("BtnViews").ClickButton()
  Grid = p.VCLObject("FrmViewDemo").VCLObject("Panel2").VCLObject("DBGrid1")

  # Save grid data to a file
  FileName = "C:\\GridData.xml"
  ExportToXml (Grid, FileName)
  Log.File(FileName, "Exported grid data")

# Iterate through rows and save the grid contents to a file
def ExportToXml (GridObject, FileName):

  Indicator.PushText("Exporting grid data...")

  # Create a text file and open it for writing
  Overwrite = True
  Unicode = True
  FSO = Sys.OleObject['Scripting.FileSystemObject']
  f = FSO.CreateTextFile (FileName, Overwrite, Unicode)
  
  # Write the root tag (grid)
  f.WriteLine ("<?xml version=\"1.0\"?>")
  f.WriteLine ("<grid>")
  
  # Save the list of grid columns to the file 
  f.WriteLine (" <columns>")
  for i in range(0, GridObject.wColumnCount):
    f.WriteLine (" <column>" + ReplaceSpecialChars (GridObject.wColumn[i]) + "</column>")
  f.WriteLine (" </columns>")
  
  # Save the data
  # Activate the first record
  GridObject.DataSource.DataSet.First()
  # Iterate through records
  while not aqConvert.VarToBool(GridObject.DataSource.DataSet.EOF):
    # The row element corresponds to grid rows 
    f.WriteLine (" <row>")

    # Process cells 
    for i in range(0, GridObject.wColumnCount):
      # Obtain the cell value
      CellText = GridObject.Columns.Items[i].Field.AsString
      CellText = ReplaceSpecialChars (CellText) # Replace special characters

      # Write the cell tag
      f.WriteLine (" <cell>" + CellText + "</cell>")

    # Close the row tag
    f.WriteLine (" </row>")

    # Move to the next record
    GridObject.DataSource.DataSet.Next()

  # Close the root tag
  f.WriteLine ("</grid>")

  # Close the file
  f.Close()

  Indicator.PopText()

# Replace special characters in the specified string
def ReplaceSpecialChars (str):
  s = aqString.Replace (str, "&", "&amp;", True)
  s = aqString.Replace (s, "<", "&lt;", True)
  s = aqString.Replace (s, ">", "&gt;", True)
  s = aqString.Replace (s, "\"", "&quot;", True)
  s = aqString.Replace (s, "'", "&apos;", True)
  return s

VBScript

Sub Main
  Dim p, Grid, FileName

  ' Obtain the grid object
  Set p = Sys.Process("csdemos")
  p.VCLObject("FrmLauncher").VCLObject("BtnViews").ClickButton
  Set Grid = p.VCLObject("FrmViewDemo").VCLObject("Panel2").VCLObject("DBGrid1")

  ' Save grid data to a file
  FileName = "C:\GridData.xml"
  Call ExportToXml (Grid, FileName)
  Call Log.File (FileName, "Exported grid data")
End Sub

' Iterate through rows and save the grid contents to a file
Sub ExportToXml (GridObject, FileName)
  Dim FSO, f, Overwrite, Unicode, i, CellText

  Indicator.PushText ("Exporting grid data...")

  ' Create a text file and open it for writing
  Overwrite = True
  Unicode = True
  Set FSO = CreateObject ("Scripting.FileSystemObject")
  Set f = FSO.CreateTextFile (FileName, Overwrite, Unicode)

  ' Write the root tag (grid)
  Call f.WriteLine ("<?xml version=""1.0""?>")
  f.WriteLine ("<grid>")

  ' Save the list of grid columns to the file
  f.WriteLine (" <columns>")
  For i = 0 To GridObject.wColumnCount-1
    f.WriteLine (" <column>" & ReplaceSpecialChars (GridObject.wColumn(i)) & "</column>")
  Next
  f.WriteLine (" </columns>")

  ' Save the data
  ' Activate the first record
  GridObject.DataSource.DataSet.First
  ' Iterate through records
  While Not aqConvert.VarToBool(GridObject.DataSource.DataSet.EOF)
    ' The row element corresponds to grid rows
    f.WriteLine (" <row>")

    ' Process cells
    For i = 0 To GridObject.wColumnCount-1
      ' Obtain the cell value
      CellText = GridObject.Columns.Items(i).Field.AsString
      CellText = ReplaceSpecialChars (CellText) ' Replace special characters

      ' Write the cell tag
      f.WriteLine (" <cell>" & CellText & "</cell>")
    Next

    ' Close the row tag
    f.WriteLine (" </row>")

    ' Move to the next record
    GridObject.DataSource.DataSet.Next
  Wend

  ' Close the root tag
  f.WriteLine ("</grid>")

  ' Close the file
  f.Close

  Indicator.PopText
End Sub

' Replace special characters in the specified string
Function ReplaceSpecialChars (str)
  Dim s
  s = aqString.Replace (str, "&", "&amp;", True)
  s = aqString.Replace (s, "<", "&lt;", True)
  s = aqString.Replace (s, ">", "&g;t", True)
  s = aqString.Replace (s, """", "&quot;", True)
  s = aqString.Replace (s, "'", "&apos;", True)
  ReplaceSpecialChars = s
End Function

DelphiScript

procedure ExportToXml (GridObject, FileName); forward;
function ReplaceSpecialChars (str); forward;

procedure Main;
var p, Grid, FileName : OleVariant;
begin
  // Obtain the grid object
  p := Sys.Process('csdemos');
  p.VCLObject('FrmLauncher').VCLObject('BtnViews').ClickButton();
  Grid := p.VCLObject('FrmViewDemo').VCLObject('Panel2').VCLObject('DBGrid1');

  // Save grid data to a file
  FileName := 'C:\GridData.xml';
  ExportToXml (Grid, FileName);
  Log.File(FileName, 'Exported grid data');
end;

// Iterate through rows and save the grid contents to a file
procedure ExportToXml (GridObject, FileName);
var FSO, f, Overwrite, Unicode, i, CellText : OleVariant;
begin
  Indicator.PushText('Exporting grid data...');

  // Create a text file and open it for writing
  Overwrite := true;
  Unicode := true;
  FSO := Sys.OleObject['Scripting.FileSystemObject'];
  f := FSO.CreateTextFile (FileName, Overwrite, Unicode);

  // Write the root tag (grid)
  f.WriteLine ('<?xml version="1.0"?>');
  f.WriteLine ('<grid>');

  // Save the list of grid columns to the file
  f.WriteLine (' <columns>');
  for i := 0 to GridObject.wColumnCount-1 do
    f.WriteLine (' <column>' + ReplaceSpecialChars(GridObject.wColumn[i]) + '</column>');
  f.WriteLine (' </columns>');

  // Save the data
  // Activate the first record
  GridObject.DataSource.DataSet.First;
  // Iterate through records
  while not aqConvert.VarToBool(GridObject.DataSource.DataSet.EOF) do
  begin
    // The row element corresponds to grid rows
    f.WriteLine (' <row>');

    // Process cells
    for i := 0 to GridObject.wColumnCount-1 do
    begin 
      // Obtain the cell value
      CellText := GridObject.Columns.Items[i].Field.AsString;
      CellText := ReplaceSpecialChars (CellText); // Replace special characters

      // Write the cell tag
      f.WriteLine (' <cell>' + CellText + '</cell>');
    end;

    // Close the row tag
    f.WriteLine (' </row>');

    // Move to the next record
    GridObject.DataSource.DataSet.Next;
  end;

  // Close the root tag
  f.WriteLine ('</grid>');

  // Close the file
  f.Close;

  Indicator.PopText;
end;

// Replace special characters in the specified string
function ReplaceSpecialChars (str);
var s : OleVariant;
begin
  s := aqString.Replace (str, '&', '&amp;', true);
  s := aqString.Replace (s, '<', '&lt;', true);
  s := aqString.Replace (s, '>', '&gt;', true);
  s := aqString.Replace (s, '"', '&quot;', true);
  s := aqString.Replace (s, '''', '&apos;', true);
  Result := s;
end;

C++Script, C#Script

function Main ()
{
  var p, Grid, FileName;

  // Obtain the grid object
  p = Sys["Process"]("csdemos");
  p["VCLObject"]("FrmLauncher")["VCLObject"]("BtnViews")["ClickButton"]();
  Grid = p["VCLObject"]("FrmViewDemo")["VCLObject"]("Panel2")["VCLObject"]("DBGrid1");

  // Save grid data to a file
  FileName = "C:\\GridData.xml";
  ExportToXml (Grid, FileName);
  Log["File"](FileName, "Exported grid data");
}

// Iterate through rows and save the grid contents to a file
function ExportToXml (GridObject, FileName)
{
  var FSO, f, Overwrite, Unicode, i, CellText;

  Indicator["PushText"]("Exporting grid data...");

  // Create a text file and open it for writing
  Overwrite = true;
  Unicode = true;
  FSO = new ActiveXObject ("Scripting.FileSystemObject");
  f = FSO["CreateTextFile"](FileName, Overwrite, Unicode);

  // Write the root tag (grid)
  f["WriteLine"]("<?xml version=\"1.0\"?>");
  f["WriteLine"]("<grid>");

  // Save the list of grid columns to the file
  f["WriteLine"](" <columns>");
  for (i = 0; i < GridObject["wColumnCount"]; i++)
    f["WriteLine"](" <column>" + ReplaceSpecialChars (GridObject["wColumn"](i)) + "</column>");
  f.WriteLine (" </columns>");

  // Save the data
  // Activate the first record
  GridObject["DataSource"]["DataSet"]["First"]();
  // Iterate through records
  while (! aqConvert["VarToBool"](GridObject["DataSource"]["DataSet"]["EOF"]))
  {
    // The row element corresponds to grid rows
    f.WriteLine (" <row>");

    // Process cells
    for (i = 0; i < GridObject["wColumnCount"]; i++)
    {
      // Obtain the cell value
      CellText = GridObject["Columns"]["Items"](i)["Field"]["AsString"];
      CellText = ReplaceSpecialChars (CellText); // Replace special characters

      // Write the cell tag
      f["WriteLine"](" <cell>" + CellText + "</cell>");
    }

    // Close the row tag
    f["WriteLine"](" </row>");

    // Move to the next record
    GridObject["DataSource"]["DataSet"]["Next"]();
  }

  // Close the root tag
  f["WriteLine"]("</grid>");

  // Close the file
  f["Close"]();

  Indicator["PopText"]();
}

// Replace special characters in the specified string
function ReplaceSpecialChars (str)
{
  var s = aqString["Replace"](str, "&", "&amp;", true);
  s = aqString["Replace"](s, "<", "&lt;", true);
  s = aqString["Replace"](s, ">", "&gt;", true);
  s = aqString["Replace"](s, "\"", "&quot;", true);
  s = aqString["Replace"](s, "'", "&apos;", true);
  return s;
}

See Also

Working With Borland TDBGrid
Searching for Records in Borland TDBGrid
Obtaining and Setting Cell Values in Borland TDBGrid

Highlight search results