[c#] How to select an option from drop down using Selenium WebDriver C#?

I was trying for my web test selecting an option. An example can be found here: http://www.tizag.com/phpT/examples/formex.php

Everything works great except the selecting an option part. How to selecting an option by value or by label?

My Code:

using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;

class GoogleSuggest
{
    static void Main()
    {
        IWebDriver driver = new FirefoxDriver();

        //Notice navigation is slightly different than the Java version
        //This is because 'get' is a keyword in C#
        driver.Navigate().GoToUrl("http://www.tizag.com/phpT/examples/formex.php");
        IWebElement query = driver.FindElement(By.Name("Fname"));
        query.SendKeys("John");
        driver.FindElement(By.Name("Lname")).SendKeys("Doe");
        driver.FindElement(By.XPath("//input[@name='gender' and @value='Male']")).Click();
        driver.FindElement(By.XPath("//input[@name='food[]' and @value='Chicken']")).Click();
        driver.FindElement(By.Name("quote")).Clear();
        driver.FindElement(By.Name("quote")).SendKeys("Be Present!");
        driver.FindElement(By.Name("education")).SendKeys(Keys.Down + Keys.Enter); // working but that's not what i was looking for
        // driver.FindElement(By.XPath("//option[@value='HighSchool']")).Click(); not working
        //  driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr/td[2]/table/tbody/tr/td/div[5]/form/select/option[2]")).Click(); not working
        // driver.FindElement(By.XPath("id('examp')/x:form/x:select[1]/x:option[2]")).Click(); not working

        }
}

This question is related to c# webdriver selenium-webdriver

The answer is


Other way could be this one:

driver.FindElement(By.XPath(".//*[@id='examp']/form/select[1]/option[3]")).Click();

and you can change the index in option[x] changing x by the number of element that you want to select.

I don't know if it is the best way but I hope that help you.


This is how it works for me (selecting control by ID and option by text):

protected void clickOptionInList(string listControlId, string optionText)
{
     driver.FindElement(By.XPath("//select[@id='"+ listControlId + "']/option[contains(.,'"+ optionText +"')]")).Click();
}

use:

clickOptionInList("ctl00_ContentPlaceHolder_lbxAllRoles", "Tester");

 var select = new SelectElement(elementX);
 select.MoveToElement(elementX).Build().Perform();

  var click = (
       from sel in select
       let value = "College"
       select value
       );

IWebElement element = _browserInstance.Driver.FindElement(By.XPath("//Select"));
IList<IWebElement> AllDropDownList = element.FindElements(By.XPath("//option"));
int DpListCount = AllDropDownList.Count;
for (int i = 0; i < DpListCount; i++)
{
    if (AllDropDownList[i].Text == "nnnnnnnnnnn")
    {
        AllDropDownList[i].Click();
        _browserInstance.ScreenCapture("nnnnnnnnnnnnnnnnnnnnnn");
    }
}

To Select an Option Via Text;

(new SelectElement(driver.FindElement(By.XPath(""))).SelectByText("");

To Select an Option via Value:

 (new SelectElement(driver.FindElement(By.XPath(""))).SelectByValue("");

Adding a point to this- I came across a problem that OpenQA.Selenium.Support.UI namespace was not available after installing Selenium.NET binding into the C# project. Later found out that we can easily install latest version of Selenium WebDriver Support Classes by running the command:

Install-Package Selenium.Support

in NuGet Package Manager Console, or install Selenium.Support from NuGet Manager.


You just need to pass the value and enter key:

driver.FindElement(By.Name("education")).SendKeys("Jr.High"+Keys.Enter);

If you are looking for just any selection from the drop-down box, I also find "select by index" method very useful.

if (IsElementPresent(By.XPath("//select[@id='Q43_0']")))
{
    new SelectElement(driver.FindElement(By.Id("Q43_0")))**.SelectByIndex(1);** // This is selecting first value of the drop-down list
    WaitForAjax();
    Thread.Sleep(3000);
}
else
{
     Console.WriteLine("Your comment here);
}

Selenium WebDriver C# code for selecting item from Drop Down:

IWebElement EducationDropDownElement = driver.FindElement(By.Name("education"));
SelectElement SelectAnEducation = new SelectElement(EducationDropDownElement);

There are 3 ways to select drop down item: i)Select by Text ii) Select by Index iii) Select by Value

Select by Text:

SelectAnEducation.SelectByText("College");//There are 3 items - Jr.High, HighSchool, College

Select by Index:

SelectAnEducation.SelectByIndex(2);//Index starts from 0. so, 0 = Jr.High 1 = HighSchool 2 = College

Select by Value:

SelectAnEducation.SelectByValue("College");//There are 3 values - Jr.High, HighSchool, College

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to webdriver

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? ImportError: No module named 'selenium' how to use List<WebElement> webdriver How to get attribute of element from Selenium? Selenium Finding elements by class name in python Open web in new tab Selenium + Python When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly How can I start InternetExplorerDriver using Selenium WebDriver

Examples related to selenium-webdriver

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Scrolling to element using webdriver? Only local connections are allowed Chrome and Selenium webdriver Check if element is clickable in Selenium Java