Iterating Through Rows in Microsoft DataGrid

Applies to TestComplete 14.93, last modified on October 12, 2021

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

To determine the number of grid rows, you can use the wRowCount property of the MicrosoftDataGrid object. Once you have determined the number of data rows in the grid, you can iterate through them in a loop. Since the numeration of grid rows is zero-based, index of the first grid row is 0, and index of the last row equals to wRowCount-1. On each loop iteration, you can perform the needed actions with the current row. For example, you can modify values in its cells or save them to a file. For more information on how to obtain or modify grid cell values, see Obtaining and Setting Cell Values in Microsoft DataGrid.

TestComplete extends the DataGrid functionality with properties and methods of the MicrosoftDataGrid object only if the Microsoft Control Support plugin is installed and enabled.

The following example demonstrated how to process DataGrid rows in a loop. It iterates through the grid rows, saves the data to an XML file and adds a link to this file in the test log.

Example

View description

JavaScript

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

  // Obtain the grid object
  p = Sys.Process ("DataGridSample");
  Grid = p.WinFormsObject("Form1").WinFormsObject("dataGrid1");

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

// Saves the grid data to the XML file
function ExportToXml (Grid, FileName)
{
  var FSO, DataFile, Overwrite, Unicode, Row, CellValue, CellText;

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

  // Create a text file and open it for writing
  Overwrite = true;
  Unicode = true;
  FSO = getActiveXObject("Scripting.FileSystemObject");
  DataFile = FSO.CreateTextFile (FileName, Overwrite, Unicode);

  // Write the opening root tag
  DataFile.WriteLine ("<?xml version=\"1.0\"?>");
  DataFile.WriteLine ("<grid>");

  // Export column captions
  DataFile.WriteLine ("  <columns>");
  for (let Col = 0; Col < Grid.wColumnCount; Col++)
    DataFile.WriteLine("    <column>" + ReplaceSpecialChars(Grid.wColumn(Col)) + "</column>");
  DataFile.WriteLine ("  </columns>");

  // Export grid cells data
  DataFile.WriteLine ("  <rows>");
  for (let Row = 0; Row < Grid.wRowCount; Row++)
  {
    DataFile.WriteLine("    <row>");
    for (let Col = 0; Col < Grid.wColumnCount; Col++)
    {
      // Get the text representation of the cell value
      CellValue = Grid.wValue (Row, Col);
      if (strictEqual(CellValue, null))
        CellText = "null"
      else
        CellText = CellValue.ToString().OleValue;
      DataFile.WriteLine("      <cell>" + ReplaceSpecialChars (CellText) + "</cell>");
    }
    DataFile.WriteLine("    </row>");
  }
  DataFile.WriteLine("  </rows>");

  // Write the closing root tag
  DataFile.WriteLine("</grid>");

  // Close the file
  DataFile.Close();
  Indicator.PopText();
}

// Replaces special characters in the specified string
function ReplaceSpecialChars (str)
{
  let 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 ("DataGridSample");
  Grid = p.WinFormsObject("Form1").WinFormsObject("dataGrid1");

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

// Saves the grid data to the XML file
function ExportToXml (Grid, FileName)
{
  var FSO, DataFile, Overwrite, Unicode, Row, Col, CellValue, CellText;

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

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

  // Write the opening root tag
  DataFile.WriteLine ("<?xml version=\"1.0\"?>");
  DataFile.WriteLine ("<grid>");

  // Export column captions
  DataFile.WriteLine ("  <columns>");
  for (Col = 0; Col < Grid.wColumnCount; Col++)
    DataFile.WriteLine("    <column>" + ReplaceSpecialChars(Grid.wColumn(Col)) + "</column>");
  DataFile.WriteLine ("  </columns>");

  // Export grid cells data
  DataFile.WriteLine ("  <rows>");
  for (Row = 0; Row < Grid.wRowCount; Row++)
  {
    DataFile.WriteLine("    <row>");
    for (Col = 0; Col < Grid.wColumnCount; Col++)
    {
      // Get the text representation of the cell value
      CellValue = Grid.wValue (Row, Col);
      if (CellValue == null)
        CellText = "null"
      else
        CellText = CellValue.ToString().OleValue;
      DataFile.WriteLine("      <cell>" + ReplaceSpecialChars (CellText) + "</cell>");
    }
    DataFile.WriteLine("    </row>");
  }
  DataFile.WriteLine("  </rows>");

  // Write the closing root tag
  DataFile.WriteLine("</grid>");

  // Close the file
  DataFile.Close();
  Indicator.PopText();
}

// Replaces 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 ("DataGridSample")
  Grid = p.WinFormsObject("Form1").WinFormsObject("dataGrid1")

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

# Saves the grid data to the XML file
def ExportToXml (Grid, FileName):

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

  # Create a text file and open it for writing
  Overwrite = True
  Unicode = True
  FSO = Sys.OleObject ["Scripting.FileSystemObject"]
  DataFile = FSO.CreateTextFile (FileName, Overwrite, Unicode)

  # Write the opening root tag
  DataFile.WriteLine ("<?xml version=\"1.0\"?>")
  DataFile.WriteLine ("<grid>")

  # Export column captions
  DataFile.WriteLine ("  <columns>")
  for Col in range(0, Grid.wColumnCount-1):
    DataFile.WriteLine("    <column>" + ReplaceSpecialChars(Grid.wColumn(Col)) + "</column>") 
  DataFile.WriteLine ("  </columns>")

  # Export grid cells data
  DataFile.WriteLine ("  <rows>")
  for Row in range(0, Grid.wRowCount-1):
    DataFile.WriteLine("    <row>")
    for Col in range(0, Grid.wColumnCount):
      # Get the text representation of the cell value
      CellValue = Grid.wValue (Row, Col)
      if (CellValue == None):
        CellText = "None"
      else:
        CellText = CellValue.ToString().OleValue
      DataFile.WriteLine("      <cell>" + ReplaceSpecialChars (CellText) + "</cell>") 
    DataFile.WriteLine("    </row>")
  DataFile.WriteLine("  </rows>")

  # Write the closing root tag
  DataFile.WriteLine("</grid>")

  # Close the file
  DataFile.Close()
  Indicator.PopText()

# Replaces 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 ("DataGridSample")
  Set Grid = p.WinFormsObject("Form1").WinFormsObject("dataGrid1")

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

' Saves the grid data to the XML file
Sub ExportToXml (Grid, FileName)
  Dim FSO, DataFile, Overwrite, Unicode, Row, Col, 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 DataFile = FSO.CreateTextFile (FileName, Overwrite, Unicode)

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

  ' Export column captions
  DataFile.WriteLine ("  <columns>")
  For Col = 0 To Grid.wColumnCount-1
    DataFile.WriteLine ("    <column>" & ReplaceSpecialChars(Grid.wColumn(Col)) & "</column>")
  Next
  DataFile.WriteLine ("  </columns>")

  ' Export grid cells data
  DataFile.WriteLine ("  <rows>")
  For Row = 0 To Grid.wRowCount-1
    DataFile.WriteLine("    <row>")
    For Col = 0 To Grid.wColumnCount-1
      ' Get the text representation of the cell value
      If Grid.wValue(Row, Col) Is Nothing Then
        CellText = "Nothing"
      Else
        CellText = Grid.wValue(Row, Col).ToString.OleValue
      End If
      DataFile.WriteLine("      <cell>" & ReplaceSpecialChars (CellText) & "</cell>")
    Next
    DataFile.WriteLine("    </row>")
  Next
  DataFile.WriteLine("  </rows>")

  ' Write the closing root tag
  DataFile.WriteLine("</grid>")

  ' Close the file
  DataFile.Close
  Indicator.PopText
End Sub

' Replaces 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, ">", "&gt;", True)
  s = aqString.Replace (s, """", "&quot;", True)
  s = aqString.Replace (s, "'", "&apos;", True)
  ReplaceSpecialChars = s
End Function

DelphiScript

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

procedure Main;
var p, Grid, FileName : OleVariant;
begin
  // Obtain the grid object
  p := Sys.Process ('DataGridSample');
  Grid := p.WinFormsObject('Form1').WinFormsObject('dataGrid1');

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

// Saves the grid data to the XML file
procedure ExportToXml (Grid, FileName);
var FSO, DataFile, Overwrite, Unicode, Row, Col, CellValue, 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');
  DataFile := FSO.CreateTextFile (FileName, Overwrite, Unicode);

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

  // Export column captions
  DataFile.WriteLine ('  <columns>');
  for Col := 0 to Grid.wColumnCount-1 do
    DataFile.WriteLine('    <column>' + ReplaceSpecialChars(Grid.wColumn(Col)) + '</column>');
  DataFile.WriteLine ('  </columns>');

  // Export grid cells data
  DataFile.WriteLine ('  <rows>');
  for Row := 0 to Grid.wRowCount-1 do
  begin
    DataFile.WriteLine('    <row>');
    for Col := 0 to Grid.wColumnCount-1 do
    begin
      // Get the text representation of the cell value
      CellValue := Grid.wValue (Row, Col);
      if CellValue = nil then
        CellText := 'nil'
      else
        CellText := CellValue.ToString.OleValue;
      DataFile.WriteLine('      <cell>' + ReplaceSpecialChars (CellText) + '</cell>')
    end;
    DataFile.WriteLine('    </row>')
  end;
  DataFile.WriteLine('  </rows>');

  // Write the closing root tag
  DataFile.WriteLine('</grid>');

  // Close the file
  DataFile.Close;
  Indicator.PopText;
end;

// Replaces 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 "]("DataGridSample");
  Grid = p["WinFormsObject"]("Form1")["WinFormsObject"]("dataGrid1");

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

// Saves the grid data to the XML file
function ExportToXml (Grid, FileName)
{
  var FSO, DataFile, Overwrite, Unicode, Row, Col, CellValue, CellText;

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

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

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

  // Export column captions
  DataFile["WriteLine"]("  <columns>");
  for (Col = 0; Col < Grid["wColumnCount"]; Col++)
    DataFile["WriteLine"]("    <column>" + ReplaceSpecialChars(Grid["wColumn"](Col)) + "</column>");
  DataFile["WriteLine"]("  </columns>");

  // Export grid cells data
  DataFile["WriteLine"]("  <rows>");
  for (Row = 0; Row < Grid["wRowCount"]; Row++)
  {
    DataFile["WriteLine"]("    <row>");
    for (Col = 0; Col < Grid["wColumnCount"]; Col++)
    {
      // Get the text representation of the cell value
      CellValue = Grid["wValue"](Row, Col);
      if (CellValue == null)
        CellText = "null"
      else
        CellText = CellValue["ToString"]()["OleValue"];
      DataFile["WriteLine"]("      <cell>" + ReplaceSpecialChars (CellText) + "</cell>");
    }
    DataFile["WriteLine"]("    </row>");
  }
  DataFile["WriteLine"]("  </rows>");

  // Write the closing root tag
  DataFile["WriteLine"]("</grid>");

  // Close the file
  DataFile["Close"]();
  Indicator["PopText"]();
}

// Replaces 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 Microsoft DataGrid
Obtaining and Setting Cell Values in Microsoft DataGrid
Searching for Records in Microsoft DataGrid
Selecting Multiple Rows in Microsoft DataGrid
wRowCount Property (Grid Controls)

Highlight search results