Iterating Through Rows in Microsoft DataGridView

Applies to TestComplete 15.45, last modified on December 01, 2022

Iterating through grid rows means accessing rows is a series, one by one. You may need to iterate through DataGridView 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 MicrosoftDataGridView object, or the grid’s “native” RowCount or Rows.Count property. 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 the number of rows minus 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 DataGridView.

TestComplete extends the DataGridView functionality with properties and methods of the MicrosoftDataGridView object only if the Microsoft Control Support plugin is installed and enabled. The internal properties and methods of the DataGridView control are accessible to TestComplete if the .NET Application Support plugin is installed and enabled.

The following example demonstrated how to process DataGridView 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 ("DataGridViewSample");
  Grid = p.WinFormsObject("Form1").WinFormsObject("dataGridView1");

  // 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, 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>" + GetValidXmlString(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 if (equal(aqObject.GetVarType (CellValue), varDispatch))
        CellText = CellValue.ToString().OleValue
      else 
        CellText = aqConvert.VarToStr(CellValue);

      DataFile.WriteLine("      <cell>" + GetValidXmlString (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 GetValidXmlString (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 ("DataGridViewSample");
  Grid = p.WinFormsObject("Form1").WinFormsObject("dataGridView1");

  // 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>" + GetValidXmlString(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 if (aqObject.GetVarType (CellValue) == varDispatch)
        CellText = CellValue.ToString().OleValue
      else 
        CellText = aqConvert.VarToStr(CellValue);

      DataFile.WriteLine("      <cell>" + GetValidXmlString (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 GetValidXmlString (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 ("DataGridViewSample")
  Grid = p.WinFormsObject("Form1").WinFormsObject("dataGridView1")

  # 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>" + GetValidXmlString(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-1):
      # Get the text representation of the cell value
      CellValue = Grid.wValue (Row, Col)
      if (CellValue == None):
        CellText = "None"
      elif (aqObject.GetVarType (CellValue) == varDispatch):
        CellText = CellValue.ToString().OleValue
      else:
        CellText = aqConvert.VarToStr(CellValue)

      DataFile.WriteLine("      <cell>" + GetValidXmlString (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 GetValidXmlString (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 ("DataGridViewSample")
  Set Grid = p.WinFormsObject("Form1").WinFormsObject("dataGridView1")

  ' 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>" & GetValidXmlString(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 aqObject.GetVarType (Grid.wValue (Row, Col)) = varDispatch Then
        If Grid.wValue (Row, Col) Is Nothing Then
          CellText = "Nothing"
        Else
          CellText = Grid.wValue (Row, Col).ToString().OleValue
        End If
      Else
        CellText = aqConvert.VarToStr(CellValue)
      End If
      DataFile.WriteLine("      <cell>" & GetValidXmlString (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 GetValidXmlString (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)
  GetValidXmlString = s
End Function

DelphiScript

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

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

  // 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>' + GetValidXmlString(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 if aqObject.GetVarType (CellValue) = varDispatch then
        CellText := CellValue.ToString.OleValue
      else 
        CellText := aqConvert.VarToStr(CellValue);

      DataFile.WriteLine('      <cell>' + GetValidXmlString (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 GetValidXmlString (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"]("DataGridViewSample");
  Grid = p["WinFormsObject"]("Form1")["WinFormsObject"]("dataGridView1");

  // 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>" + GetValidXmlString(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 if (aqObject["GetVarType"] (CellValue) == varDispatch)
        CellText = CellValue["ToString"]()["OleValue"]
      else 
        CellText = aqConvert["VarToStr"](CellValue);

      DataFile["WriteLine"]("      <cell>" + GetValidXmlString (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 GetValidXmlString (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 DataGridView
Obtaining and Setting Cell Values in Microsoft DataGridView
Searching for Records in Microsoft DataGridView
Selecting Multiple Records in Microsoft DataGridView
wRowCount Property (Grid Controls)

Highlight search results