104

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
 }
}
John Smith
7,4477 gold badges52 silver badges63 bronze badges
asked Mar 11, 2011 at 20:58

11 Answers 11

218

You must create a select element object from the drop down list.

 using OpenQA.Selenium.Support.UI;
 // select the drop down list
 var education = driver.FindElement(By.Name("education"));
 //create select element object 
 var selectElement = new SelectElement(education);
 //select by value
 selectElement.SelectByValue("Jr.High"); 
 // select by text
 selectElement.SelectByText("HighSchool");

More info here

Matthew Lock
13.6k14 gold badges97 silver badges132 bronze badges
answered Mar 14, 2011 at 8:37

5 Comments

There is a bug. var selectElement = new SelectElement(education); Should be: var selectElement = new SelectElement(element);
FYI: To use a Select Element, you need to include the Selenium Webdriver Support package which is a different NuGet package than the Selenium WebDriver. Include the namespace OpenQA.Selenium.Support.UI.
I'm using the firefox driver , selenium version 2.53.1 and support library 2.53 , The SelectByText doesnt seem to be working. Im able to see all the options . Even if i iterate the options and set the correct value, The value is not getting set..Any help would be great
Did you try other drivers or just Firefox? Also, the package's technical name is currently Selenium.Support.
This worked great for me, had to add the Selenium.Support NuGet as well.
18

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.

John Smith
7,4477 gold badges52 silver badges63 bronze badges
answered Feb 21, 2015 at 4:50

Comments

11

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.

Kirk Woll
77.8k23 gold badges188 silver badges200 bronze badges
answered May 25, 2012 at 23:13

1 Comment

I'm not sure this works all the time. Someone did it this way and it didn't work and I ended up having to change to code to the code suggested by Matthew Lock
5

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
answered May 23, 2017 at 13:34

Comments

4

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("");
Matt
15.1k28 gold badges109 silver badges161 bronze badges
answered Apr 27, 2015 at 12:13

1 Comment

The Selenium.Support NuGet Package should be installed to use these solutions, but its working pretty well for me.
3

You just need to pass the value and enter key:

driver.FindElement(By.Name("education")).SendKeys("Jr.High"+Keys.Enter);
Nic Wortel
11.4k7 gold badges62 silver badges79 bronze badges
answered Jul 30, 2014 at 7:21

1 Comment

Will likely fail if dropdown contains multiple options with similar texts.
1

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");
answered Mar 5, 2013 at 22:44

Comments

0

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);
}
Unheilig
16.3k193 gold badges71 silver badges101 bronze badges
answered Dec 1, 2016 at 23:53

Comments

0
 var select = new SelectElement(elementX);
 select.MoveToElement(elementX).Build().Perform();
 var click = (
 from sel in select
 let value = "College"
 select value
 );
Petter Friberg
21.8k10 gold badges67 silver badges116 bronze badges
answered Sep 20, 2017 at 9:06

1 Comment

Please add an explanation to your code: why is it an answer to the question and what makes it different from the earlier given answers?
0
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");
 }
}
Syscall
19.8k10 gold badges44 silver badges60 bronze badges
answered Mar 15, 2018 at 20:01

1 Comment

Works with dropdownlist selections
0

If you don't want to install an extra Nuget package ("Selenium Support") you can just execute JavaScript on the page

((IJavaScriptExecutor)driver)
 .ExecuteScript("document.getElementById('mySelect').value=123;");
answered Mar 9, 2024 at 16:44

Comments

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.