Casra515
Casra515

Reputation: 29

Select a row of datagrid using UI Automation

I'm writing a UI automation software. I need to select a row in the datagrid and then click on the run button. I tried most of the example codes in the internet and they didn't work for me. For example for selecting a gridview row:

When I write the following code:

AutomationElement dataGrid =  this.mainWindow.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "2885"));

if (dataGrid != null)
{
    GridPattern pattern = GetGridPattern(dataGrid);
    AutomationElement tempElement = pattern.GetItem(1, 1);
    tempElement.SetFocus();
}

I receive the error: "Target element cannot receive focus." which is related to the last line.

I also tried the code:

AutomationElement mainGrid = // find the grid in the window
var columnCount = (int)mainGrid.GetCurrentPropertyValue(GridPattern.ColumnCountProperty);

var mainGridPattern = (GridPattern)mainGrid.GetCurrentPattern(GridPattern.Pattern);

var rowToSelect = 2;

// select just the first cell
var item = mainGridPattern.GetItem(rowToSelect, 0);

var itemPattern = (SelectionItemPattern)item.GetCurrentPattern(SelectionItemPattern.Pattern);

itemPattern.Select();

but I and I received the error :"Unsupported Pattern".

I should mention that I'm using UI Spy for retrieving the elements properties.

Could you explain me what's wrong and how should I select a row? ![UI Spy][1]

Upvotes: 2

Views: 7696

Answers (1)

Simon Mourier
Simon Mourier

Reputation: 139216

Here is how you can do it:

        // get to ROW X (here it's row #1 name is always "Row X")
        AutomationElement row1 = dataGrid.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Row 1"));

        // get row header
        AutomationElement row1Header = row1.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Header));

        // invoke it (select the whole line)
        ((InvokePattern)row1Header.GetCurrentPattern(InvokePattern.Pattern)).Invoke();

To find these operations, you can use UISpy and try the different items in the tree, look at the pattern each item implements and try them out using the UISpy contextual "Control Patterns" menu.

Upvotes: 3

Related Questions