-->

How to Click on a Button within a datagrid after f

2019-01-29 02:26发布

问题:

So here is my Code that is able to get the header of the datagrid column and find the matching values from the user inputs. For Example if input is "jdoe" it will look at the Username column in the datagrid and match the [value.Key].Text to the value.Value. Now the problem is that each row has an "Edit" button with the same automation ID. How do I iterate through the datagrid and be able to click on the Edit button with regardless of what row "jdoe" is in: Here is what I have so far:

    public static bool Contains(this ListView listView, ObjectInList  objectInList)
    {
        foreach (ListViewRow row in listView.Rows)
        {

            if (DataMatches(row, objectInList))
                return true;
        }

        return false;
    }


    private static bool DataMatches(ListViewRow row, ObjectInList objectInList)
    {
        foreach (KeyValuePair<string, string> value in objectInList.Values)
        {
            if (row.Cells[value.Key].Text != value.Value)


                return false;


        }
        return true;
    }
}


internal class UserInList : ObjectInList
{



    public UserInList(string username)
    {

        _values["Username"] = username;


    }
}

internal class OrderInList : ObjectInList
{

    public OrderInList(string orderNumber)
    {

        _values["Depot Tag #"] = orderNumber;


    }
}

internal abstract class ObjectInList
{

    protected readonly Dictionary<string, string> _values = new Dictionary<string, string>();

    public IReadOnlyDictionary<string, string> Values
    {

        get { return _values; }
    }

This is a screenshot of the WPF application

回答1:

Here is what I use to iterate through tables:

get your search element = value2

get your table id, xpath or css = myTable

The loop will go through the table and then find value2. From here you have a choice on what you want to do next. Let's say your column looks like this:

|col 1 |col  2  | col   3 |
|link1 | value1 | link2   |
|link1 | value2 | link2   |

In the below it will stop on value2. That becomes tds[i]. To click link 1 I use:

 tds[i - 1].Click(); 

If I want to click on link 2 I use:

 tds[i + 1].Click(); 

Just consider the column number from [i] and count left (minus) or right (plus) the number of columns.

 public void ClickTableLink(String value2)
  {
  var table =  driver.FindElement(By.Id("myTable"));
  foreach (var tr in table.FindElements(By.TagName("tr")))
  {
   var tds = tr.FindElements(By.TagName("td"));
    for (var i = 0; i < tds.Count; i++)
    {
        if (tds[i].Text.Trim().Contains(value2))
        {
            tds[i - 1].Click();
           break;
        }

    }
  }
}


回答2:

A possible solution would be to use an xpath that finds the line that has a cell with your text and from there to select the button.

example:

//tr[.//td[text()='jdoe']]//button