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.

Kate Paulk
31.5k8 gold badges56 silver badges109 bronze badges
asked Sep 14, 2017 at 12:04

2 Answers 2

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");
answered Sep 14, 2017 at 13:33
2
  • 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? Commented Sep 14, 2017 at 14:11
  • Use FindElement instead of FindElements Commented Sep 14, 2017 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.

answered Sep 14, 2017 at 13:21

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.