motto motto - 1 year ago 103
C# Question

How to Using Webdriver Selenium for selecting an option in C#?

I was trying for my web test selecting an option. An example can be found here:

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#
IWebElement query = driver.FindElement(By.Name("Fname"));
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")).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


Answer Source

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
 // select by text

More info here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download