-1

I have already checked many answers but all are using a foreach loop to iterate through rows. I want to use a for loop.

Code:

IWebElement NtTable = driver.FindElement(By.Id("nt-item-table"));
IReadOnlyCollection<IWebElement> TableRows = NtTable.FindElements(By.TagName("tr")).ToList();

for (int i = 0; i <= TableRows.Count; i++)
{
    //driver.FindElement(TableRows[i])....
    //Tablows.get(i)....

}

I tried above commented 2 lines to get text of particular TD from particular TR but seems not getting any property after press (.). Above seems fine if I use Java but not in C#.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Helping Hands
  • 5,292
  • 9
  • 60
  • 127

2 Answers2

2

There are several issues.

  1. You don't need to chain the .FindElement() calls. It's more efficient to just get the TRs in one search, e.g. by CSS selector #nt-item-table tr.

  2. You are calling .ToList() after the .FindElements() call which isn't necessary and won't work. It shows an error in the IDE.

  3. You are iterating to <= TableRows.Count when you only need <. The index starts at 0.

  4. You can't access elements in the IReadOnlyCollection using array notation, e.g. TableRows[i]. You need to use LINQ and ElementAt(i).

  5. You already have found the TR elements, statements like driver.FindElement(TableRows[i]).... make no sense.

  6. Tablows is not a variable name that you have defined. The variable is TableRows.

    IReadOnlyCollection<IWebElement> TableRows = Driver.FindElements(By.CssSelector("#nt-item-table tr"));
    for (int i = 0; i < TableRows.Count; i++)
    {
        // do something with TableRows.ElementAt(i);
    }
    

You really should spend some time reading some Selenium and basic C# programming tutorials, syntax references, etc. It will help you avoid a lot of these issues.

JeffC
  • 22,180
  • 5
  • 32
  • 55
0

I changed the variables to start lowercase (camelcase) and have you tried this. Since you already have a list of tr elements which have child elements (td)

IWebElement ntTable = driver.FindElement(By.Id("nt-item-table"));
IReadOnlyCollection<IWebElement> tableRows = ntTable.FindElements(By.TagName("tr")).ToList();

for (int i = 0; i <= tableRows.Count; i++)
{
    var tdCollection = tableRows[i].FindElements(By.TagName("td"));

    for (int c = 0; c <= tdCollection.Count; c++)
    {
        string column = tdCollection[c].Text;
    }
}

I would prefer foreach though. Because you do not need index int's then.

JP Hellemons
  • 5,977
  • 11
  • 63
  • 128