Sorting Data in Microsoft DataGridView

Applies to TestComplete 15.63, last modified on April 23, 2024

The DataGridView control lets the end users sort the displayed data. This topic describes various approaches that can be used to sort the grid data from test scripts.

To perform these actions, TestComplete should have access to internal objects, properties and methods of the DataGridView control. For this purpose, the .NET Application Support and Microsoft Control Support plugins must be installed and enabled.

When testing Microsoft DataGridView controls, use specific methods and properties of the corresponding MicrosoftDataGridView object. You can call these methods and properties from your keyword tests, as well as from scripts. This topic describes how to work with an object’s properties and methods from your scripts. However, when testing a DataGridView control from your keyword test, you can use the same methods and properties calling them from keyword test operations. For more information, see Keyword Tests Basic Operations.

Simulating Column Headers Clicks

It is possible to sort the data displayed in the DataGridView control by clicking on the header of the column that you want to sort. The next click on the same header switches the sort direction (from ascending to descending, and vice versa). Note, that this functionality is only enabled if the grid’s SelectionMode property is set to anything other than ColumnHeaderSelect or FullColumnSelect. Otherwise, clicking the column header selects the entire column and it is impossible to sort grid data using column header clicks. Also, the column headers in the grid are only displayed if the ColumnsHeadersVisible property of the grid object is True. Otherwise, if this property is False, the grid headers are hidden and it is impossible to simulate clicks on them. In this case, you can use the grid’s internal properties and methods to implement sorting.

With TestComplete, you can simulate clicks on the grid column headers using the ClickColumnHeader action of the MicrosoftDataGridView object. The following example demonstrates how to use this action for sorting data displayed in the DataGridView control:

JavaScript, JScript

function Main ()
{
  var p, Grid;

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

  // Click the column header once to sort ascending by that column
  Grid.ClickColumnHeader ("Customer Name");

  aqUtils.Delay (1000);

  // Click the column header twice to sort descending by that column
  Grid.ClickColumnHeader ("Product");
  Grid.ClickColumnHeader ("Product");
}

Python

def Main ():

  # Obtain the grid object
  p = Sys.Process ("DataGridViewSample")
  Grid = p.WinFormsObject("Form1").WinFormsObject("dataGridView1")

  # Click the column header once to sort ascending by that column
  Grid.ClickColumnHeader ("Customer Name")

  aqUtils.Delay (1000)

  # Click the column header twice to sort descending by that column
  Grid.ClickColumnHeader ("Product")
  Grid.ClickColumnHeader ("Product")

VBScript

Sub Main
  Dim p, Grid

  ' Obtain the grid object
  Set p = Sys.Process ("DataGridViewSample")
  Set Grid = p.WinFormsObject("Form1").WinFormsObject("dataGridView1")

  ' Click the column header once to sort ascending by that column
  Grid.ClickColumnHeader "Customer Name"

  aqUtils.Delay 1000

  ' Click the column header twice to sort descending by that column
  Grid.ClickColumnHeader "Product"
  Grid.ClickColumnHeader "Product"
End Sub

DelphiScript

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

  // Click the column header once to sort ascending by that column
  Grid.ClickColumnHeader ('Customer Name');

  aqUtils.Delay (1000);

  // Click the column header twice to sort descending by that column
  Grid.ClickColumnHeader ('Product');
  Grid.ClickColumnHeader ('Product');
end;

C++Script, C#Script

function Main ()
{
  var p, Grid;

  // Obtain the grid object
  p = Sys["Process"]("DataGridViewSample");
  Grid = p["WinFormsObject"]("Form1")["WinFormsObject"]("dataGridView1");

  // Click the column header once to sort ascending by that column
  Grid["ClickColumnHeader"]("Customer Name");

  aqUtils.Delay (1000);

  // Click the column header twice to sort descending by that column
  Grid["ClickColumnHeader"]("Product");
  Grid["ClickColumnHeader"]("Product");
}

Using the DataGridView.Sort Method

It is possible to sort grid data using its internal properties and methods. The DataGridView control has a special Sort method that can be used to sort data in the grid. The method declaration is as follows:

GridObj.Sort (ColumnObj, Direction)

The ColumnObj parameter specifies the grid column by which the grid contents will be sorted. The sort direction is specified by the Direction parameter. 0 or “Ascending” means the ascending direction; 1 or “Descending” is the descending direction.

Below is an example that demonstrates how to use the DataGridView.Sort method to sort the grid data:

Example

View description

JavaScript

function Main ()
{
  var p, Grid;

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

  // Sort the grid data by the "Customer Name" column
  Sort (Grid, "Customer Name", "Ascending");

  aqUtils.Delay (1000);

  // Sort the grid data by the "Product" column
  Sort (Grid, "Product", "Descending");
}

// Sorts the grid by the specified column
function Sort (Grid, ColumnId, SortOrder)
{
  // Get the column object
  var Column = GetColumn (Grid, ColumnId);
  // Sort the grid data by that column
  Grid.Sort (Column, SortOrder);
}

// Returns the column object by its caption or index
function GetColumn (Grid, ColumnId)
{
  // Check if the column is specified by caption or index
  if (equal(aqObject.GetVarType(ColumnId), varOleStr))
  {
    // Search for the column by its caption
    for (let i=0; i<Grid.wColumnCount; i++)
      if (equal(Grid.wColumn(i), ColumnId))
        return Grid.Columns.Item(i); // Column is found

    return null; // Column is not found
  }
  else
    // Get the column by index
    return Grid.Columns.Item(ColumnId);
}

JScript

function Main ()
{
  var p, Grid;

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

  // Sort the grid data by the "Customer Name" column
  Sort (Grid, "Customer Name", "Ascending");

  aqUtils.Delay (1000);

  // Sort the grid data by the "Product" column
  Sort (Grid, "Product", "Descending");
}

// Sorts the grid by the specified column
function Sort (Grid, ColumnId, SortOrder)
{
  // Get the column object
  var Column = GetColumn (Grid, ColumnId);
  // Sort the grid data by that column
  Grid.Sort (Column, SortOrder);
}

// Returns the column object by its caption or index
function GetColumn (Grid, ColumnId)
{
  // Check if the column is specified by caption or index
  if (aqObject.GetVarType(ColumnId) == varOleStr)
  {
    // Search for the column by its caption
    for (i=0; i<Grid.wColumnCount; i++)
      if (Grid.wColumn(i) == ColumnId)
        return Grid.Columns.Item(i); // Column is found

    return null; // Column is not found
  }
  else
    // Get the column by index
    return Grid.Columns.Item(ColumnId);
}

Python

def Main ():

  # Obtain the grid object
  p = Sys.Process ("DataGridViewSample")
  Grid = p.WinFormsObject("Form1").WinFormsObject("dataGridView1")

  # Sort the grid data by the "Customer Name" column
  Sort (Grid, "Customer Name", "Ascending")

  aqUtils.Delay (1000)

  # Sort the grid data by the "Product" column
  Sort (Grid, "Product", "Descending")

# Sorts the grid by the specified column
def Sort (Grid, ColumnId, SortOrder):
  # Get the column object
  Column = GetColumn (Grid, ColumnId)
  # Sort the grid data by that column
  Grid.Sort (Column, SortOrder)

# Returns the column object by its caption or index
def GetColumn (Grid, ColumnId):
  # Check if the column is specified by caption or index
  if (aqObject.GetVarType(ColumnId) == varOleStr):
    # Search for the column by its caption
    for i in range(0, Grid.wColumnCount-1):
      if (Grid.wColumn[i] == ColumnId):
        return Grid.Columns.Item[i] # Column is found

    return null # Column is not found
  else:
    # Get the column by index
    return Grid.Columns.Item(ColumnId)

VBScript

Sub Main
  Dim p, Grid

  ' Obtain the grid object
  Set p = Sys.Process ("DataGridViewSample")
  Set Grid = p.WinFormsObject("Form1").WinFormsObject("dataGridView1")

  ' Sort the grid data by the "Customer Name" column
  Call Sort (Grid, "Customer Name", "Ascending")

  aqUtils.Delay (1000)

  ' Sort the grid data by the "Product" column
  Call Sort (Grid, "Product", "Descending")
End Sub

' Sorts the grid by the specified column
Sub Sort (Grid, ColumnId, SortOrder)
  Dim Column
  ' Get the column object
  Set Column = GetColumn (Grid, ColumnId)
  ' Sort the grid data by that column
  Call Grid.Sort (Column, SortOrder)
End Sub

' Returns the column object by its caption or index
Function GetColumn (Grid, ColumnId)
  ' Check if the column is specified by caption or index
  If aqObject.GetVarType(ColumnId) = varOleStr Then
    ' Search for the column by its caption
    For i = 0 To Grid.wColumnCount
      If Grid.wColumn(i) = ColumnId Then
        Set GetColumn = Grid.Columns.Item(i) ' Column is found
        Exit Function
      End If
    Next

    Set GetColumn = Nothing ' Column is not found
  Else
    ' Get the column by index
    Set GetColumn = Grid.Columns.Item(ColumnId)
  End If
End Function

DelphiScript

procedure Sort (Grid, ColumnId, SortOrder); forward;
function GetColumn (Grid, ColumnId); forward;

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

  // Sort the grid data by the 'Customer Name' column
  Sort (Grid, 'Customer Name', 'Ascending');

  aqUtils.Delay (1000);

  // Sort the grid data by the 'Product' column
  Sort (Grid, 'Product', 'Descending');
end;

// Sorts the grid by the specified column
procedure Sort (Grid, ColumnId, SortOrder);
var Column : OleVariant;
begin
  // Get the column object
  Column := GetColumn (Grid, ColumnId);
  // Sort the grid data by that column
  Grid.Sort (Column, SortOrder);
end;

// Returns the column object by its caption or index
function GetColumn (Grid, ColumnId);
var i : OleVariant;
begin
  // Check if the column is specified by caption or index
  if aqObject.GetVarType(ColumnId) = varOleStr then
  begin
    // Search for the column by its caption
    for i := 0 To Grid.wColumnCount do
      if Grid.wColumn[i] = ColumnId then
      begin
        Result := Grid.Columns.Item[i]; // Column is found
        Exit;
      End;

    Result := nil; // Column is not found
  end
  else
    // Get the column by index
    Result := Grid.Columns.Item[ColumnId];
end;

C++Script, C#Script

function Main ()
{
  var p, Grid;

  // Obtain the grid object
  p = Sys["Process"]("DataGridViewSample");
  Grid = p["WinFormsObject"]("Form1")["WinFormsObject"]("dataGridView1");

  // Sort the grid data by the "Customer Name" column
  Sort (Grid, "Customer Name", "Ascending");

  aqUtils["Delay"] (1000);

  // Sort the grid data by the "Product" column
  Sort (Grid, "Product", "Descending");
}

// Sorts the grid by the specified column
function Sort (Grid, ColumnId, SortOrder)
{
  // Get the column object
  var Column = GetColumn (Grid, ColumnId);
  // Sort the grid data by that column
  Grid["Sort"](Column, SortOrder);
}

// Returns the column object by its caption or index
function GetColumn (Grid, ColumnId)
{
  // Check if the column is specified by caption or index
  if (aqObject["GetVarType"](ColumnId) == varOleStr)
  {
    // Search for the column by its caption
    for (i=0; i<Grid["wColumnCount"]; i++)
      if (Grid["wColumn"](i) == ColumnId)
        return Grid["Columns"]["Item"](i); // Column is found

    return null; // Column is not found
  }
  else
    // Get the column by index
    return Grid["Columns"]["Item"](ColumnId);
}

However, this approach may not be admissible in some cases. For example, if the application under test implements a custom sort algorithm or allows sorting data by several columns, changing its internal data directly may produce inaccurate results. You should ask the developers whether you can use this approach to test the sort functionality.

See Also

Working With Microsoft DataGridView
ClickColumnHeader Action (Grid Controls)
Selecting Cells in Microsoft DataGridView
Obtaining and Setting Cell Values in Microsoft DataGridView

Highlight search results