Selecting Options from a Drop Down Menu in C# using Selenium

1.5k Views Asked by At

I am trying to select a specific option in a drop down menu. My current code highlights the selection I want, but moves on and does not keep the value in the field after "selecting" it. I want to grab the value "Medical." Currently I am using:

IWebElement element = driver.FindElement(By.Name("DISPLAY_CoverageType"));
SelectElement selector = new SelectElement(element);
selector.SelectByText("Medical");

The List I am pulling from looks like:

<option value="">Please Select One</option>
<option value="Medical">Medical</option>
<option value="Hospital">Hospital</option>
<option value="Dental">Dental</option>
<option value="Vision">Vision</option>

This highlights my selection in blue, but does not keep it selected when the drop down menu closes. Any advice?

3

There are 3 best solutions below

0
On

Apparently going the repetitive and "easy" route was the correct way the entire time. This code helped me pass my tests:

driver.FindElement(By.Name("DISPLAY_CoverageType")).Click();
driver.FindElement(By.XPath("//td[4]/select/option[3]")).Click();
driver.FindElement(By.XPath("//td[4]/select/option[3]")).Click();

Thanks to @alecxe for the idea of repeating calls.

3
On

You can also use css selector to bypass the SelectElement class and find the option directly.

string option = "Medical";
By css = By.CssSelector("Select>option[value='" + option + "']");
driver.FindElement(css).Click();
1
On

Use below line

 selector.selectByValue("Medical"); 

Instead of

 selector.SelectByText("Medical");

Let me know is it working or not.