Iterating Through Microsoft DataGridView Rows, Columns and Cells
Iterating through a grid means accessing the grids elements (rows, columns and cells) in a series, one by one. You may need to iterate through the Microsoft DataGridView in TestComplete if you need to locate a particular row or column, or perform the same set of operations on multiple elements.
I'll explain how to iterate through DataGridView rows, columns and cells and, as an example, save the grid data to an XML file.
Accessing DataGridView Rows, Columns and Cells
Before iterating through the grid, you need to determine the number of its rows and columns. You can do this using the grids
ColumnCount properties respectively. Note that if the grids
AllowUserToAddRows property is True, the grid also has a special row that is used to add new records to the grid (it is shown as the last row and marked with the asterisk (*) in its row header). In this case, the number of the grids data rows is
RowCount - 1.
Once you determine the number of grid rows and columns, you can iterate through them in a loop. You can access rows and columns via the grids
Columns properties. To obtain a particular element by its index in the collection, you can use the
Item (Index) property or the
get_Item (Index) method. Note that the numeration of grid rows and columns is zero-based, so the index of the first grid row (column) is 0, and the index of the last row (column) equals the number of rows (columns) minus 1.
If you need to access a particular DataGridView cell, you do not need to obtain the object corresponding to the grid row and the column where the cell resides. You can quickly access the desired cell by using the grids
Item (ColIndex, RowIndex) property or the
get_Item (ColIndex, RowIndex) method. Here, the ColIndex and RowIndex parameters specify the indexes of the row and the column where the needed cell resides. Note again that numeration of grid rows and columns is zero-based. So, the
.Item (3, 2) statement will return the cell in the fourth column and the third row.
The example below demonstrates 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 to the test log. The example contains the following routines:
In these routines, the Grid parameter specifies the DataGridView control; RowIndex and ColIndex are row and column indexes respectively.