1

I need to create a simple loop that iterates through a list of options in a list container and searches for a specific option. When the text is found it should scroll down to that option so it's visible and then click on it. I came up with something like this:

public static IWebElement FindListItem(IWebElement listContainer, string itemText)
    {
        List<IWebElement> allOptions = listContainer.FindElements(By.XPath(""));
        for (WebElement we: allOptions)
        {
            dropDown.sendKeys(Keys.DOWN); 
            sleep(250);
            if (we.getText().contains(text)) select.selectByVisibleText("Value1");
        }
    }

I need this in C#. Can anyone help me with that since my C# skills are just developing.

1

For working with options, please use the SelectElement class which will redure your effort to about two lines of code. Example:

 using OpenQA.Selenium.Support.UI;

 var selectElement = new SelectElement(driver.FindElement(By.Name("dropdown"));

 selectElement.SelectByText("thisWillBeSelected");
  • On this line: var SelectElement = new SelectElement(listContainer.FindElements(By.XPath(""))); listContainer.FindElements(ByXpath(""))); is underlined with the message that it cannot convert System.Collections.ObjectModel.ReadOlnyCollection<OpenQA.Selenium.IWebElement> to OpenQA.Selenium.IWebElement How do i fix this? – Adam Gencel Sep 14 '17 at 14:11
  • Use FindElement instead of FindElements – FDM Sep 14 '17 at 14:55
0

There's a simpler way to find your elements:

List<IWebElement> allOptions = listContainer.FindElements(By.TagName("option"));

I suggest you learn Linq query syntax, because that will make the find and select part easy (the exact code is not guaranteed to be correct since I'm doing this from memory):

allOptions.Where(opt -> opt.text.equals(itemText)).First().Scroll();

At this point you can select and click the element.

I'd recommend doing some of the excellent tutorials around for C# so you can improve your general programming skills in the language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.