One of the actions you will perform most frequently while testing an application with a grid control is selecting grid cells. In this post, I will describe several approaches that can be used to select a particular cell in the DataGridView control: simulating mouse clicks, simulating keyboard shortcuts and using DataGridView control native members. In your tests, you can use any of the described approaches that suits your needs.
Simulating Cell Clicks
TestComplete adds special
Click actions to all onscreen objects. These actions can be used to simulate clicks and double-clicks on objects. The question in point is how to determine the coordinates of the cell we want to click. This is pretty easy, since most controls in .NET Framework v.2.0 include a very useful
AccessibilityObject property that contains screen coordinates of the control. So, you can determine the screen-relative coordinates of the desired cell, convert them to the grid-relative coordinates and perform a click.
Below is an example that demonstrates this approach. It consists of three routines:
Mainis the main routine.
ClickCellsimulates a click on a grid cell specified either by row and column indices, or by row index and column name. It is sometimes more useful to refer the cell by the column name instead of its index, because the order of columns in DataGridView can be customized.
GetCellreturns a grid cell specified either by row and column indices, or by row index and column name. The row and column indices are zero-based.
Simulating Keyboard Shortcuts
It is possible to navigate through DataGridView using keyboard shortcuts. For example, pressing an arrow key selects the neighbor cell in the direction of the arrow, Home and End select the first and the last cell in the current row, respectively, and so on. To simulate these shortcuts, you can use the
Keys action applied to the grid control, as follows:
You can read more about the supported shortcuts in the following MSDN article: Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control.
You can also select a particular cell in the DataGridView control using the native
CurrentCell property of the DataGridView control. This property lets you get or set the cell focused in the grid.
In order to set the value of this property, first, you need to obtain the object corresponding to the desired cell. To do this, you can use the
GetCell routine from the example in the Simulating Cell Clicks section. The code snippet below shows how you can use the
CurrentCell property in scripts:
By the way, when setting this property to a cell, which is not currently visible, the grid automatically scrolls in order for the cell to become visible. So you don’t have to check whether the cell is visible and write some additional code to scroll the grid to the desired cell.