Enroll in Selenium Training

Just like CheckBox & Radio Buttons, DropDown & Multiple Select Operations in C# also works together and almost the same way. To perform any action, the first task is to identify the element group. I am saying it a group, as DropDown / Multiple Select is not a single element. They always have a single name but and they contain one or more than one element in them. I should rather say more than one option in DropDown and Multiple Select. The only difference between these two is deselecting statements & multiple selections are not allowed on DropDown . Let's look at the different operations:

DropDown & Multiple Select Operations

It is just an ordinary operation like selecting any other type of element on a webpage. You can choose it by ID, Name, CSS & Xpath, etc. But to perform any action on this element it is required to import 'using OpenQA.Selenium.Support.UI;' package and to use it we need to create a new Select Object of class Select.

Select Class in Selenium

Models a SELECT tag, providing helper methods to select and deselect options. Select is a class that is provided by Selenium to perform multiple operations on DropDown object and Multiple Select object. This class can be found under the Selenium's Support.UI package. As Select is also an ordinary class, so it's object is also created by a New keyword with regular class creation syntax.

SelectElement oSelect = new SelectElement());

The above code will generate compile time error in Eclipse, as Select() is asking for constructor. Bring the cursor over Select(), Eclipse will populate a suggestion.

DropDown

It clearly says that SelectElement is asking for an element type object for its constructor. The code will be:

	IWebElement element = driver.FindElement(By.Id("Country"));
	SelectElement oSelect = new SelectElement(element);

	//Or it can be also written as

	SelectElement oSelect = new SelectElement(driver.FindElement(By.Id("Country")));

Note: Select class only works for elements with <select> tags.

Now, once you got the oSelect object which is a SELECT object, you can access all the methods resides in side the SELECT class by typing oSelect + dot.

DropDown_1

Different Select Commands

In this chapter, we will learn how to deal with DropDown and Multi Select elements. There will be many interesting operations are available on these elements. But you may be wondering that how a DropDown looks like in the HTML code. Will use the same example for the reference of different select commands.

MultiSelect_3

SelectByText

void SelectElement.SelectByText(string text) – It is very easy to choose or select an option given under any dropdowns and multiple selection boxes with SelectByText method. It takes a parameter of String which is one of the Value of Select element and it returns nothing.

Command - oSelect.SelectByText("text");

Example - Refer the above Screen shot of YEAR Drop Down*

Code - To select the value 2010.

SelectElement oSelect = new SelectElement(driver.FindElement(By.Id("yy_date_8")));

oSelect.selectByText("2010");

SelectByIndex

void SelectElement.SelectByIndex(int index) – It is almost the same as SelectByText but the only difference here is that we provide the index number of the option here rather the option text.It takes a parameter of int which is the index value of Select element and it returns nothing.

Command - oSelect.SelectByIndex(int);

Example - Refer the above Screen shot of YEAR Drop Down*

Code - To select the value 2010 using index.

SelectElement oSelect = new SelectElement(driver.FindElement(By.Id("yy_date_8")));

oSelect.SelectByIndex(4);

Note: Index starts from Zero, so the fifth position value will be at index 4.

SelectByValue

void SelectElement.SelectByValue(string value) –It is again the same what we have discussed earlier, the only difference in this is that it ask for the value of the option rather the option text or index. It takes a parameter of String which is on of the value of Select element and it returns nothing.

Command - oSelect.SelectByValue("text");

Example - Refer the above Screen shot of YEAR Drop Down*

Code - To select the value 2014.

SelectElement oSelect = new SelectElement(driver.FindElement(By.Id("yy_date_8")));

oSelect.SelectByValue("2014");

Note: The value of an option and the text of the option may not be always same and there can be a possibility that the value is not assigned to Select webelement. If the value is given in the Select tag then only you can use the SelectByValue method.

Options

IList<IWebElement> SelectElement.Options { get; } –This gets the list all options belonging to the Select tag.

Command - oSelect.Options;

Sometimes you may like to count the element in the drop down and multiple select box, so that you can use the loop on Select element.

Example- Refer the above Screen shot of YEAR Drop Down*

Code - To get the Count of the total elements inside SELECT.

	SelectElement oSelect = new SelectElement(driver.FindElement(By.Id("yy_date_8")));
	IList<IWebElement> elementCount = oSelect.Options;
	Console.Write(elementCount.Count);

Print all the Options

Code - To get the Count of the total elements inside SELECT and to Print the text value of every element present in the SELECT.

	SelectElement oSelect = new SelectElement(driver.FindElement(By.Id("yy_date_8")));
	IList<IWebElement> elementCount = oSelect.Options;
	int iSize = elementCount.Count;

	for (int i = 0; i > iSize; i++)
	{
		String sValue = elementCount.ElementAt(i).Text;
	   Console.WriteLine(sValue);

All of the above methods work on both Dropdown and Multiple select box.

DeSelect Methods

The way we select different values of DropDown & Multi Select, the same way we can also deselect the values. But the only challenge in these methods are they do not work for DropDown and only work for Multi Select elements.

In case you want to deselect any pre-selected option, that can be done with either DeselectAll(), DeselectByIndex, DeselectByValue and DeselectByText.

DropDown_2

Multi Select element look like this:

MultiSelect_5

void SelectElement.DeselectAll() – Clear all selected entries. This is only valid when the SELECT supports multiple selections.

Command - oSelect.DeselectAll;

void SelectElement.DeselectByIndex(int index) –Deselect the option at the given index.

Command - oSelect.DeselectByIndex;

void SelectElement.DeselectByValue(string value) –Deselect all options that have a value matching the argument.

Command - oSelect.DeselectByValue;

void SelectElement.DeselectByText(string text)– Deselect all options that display text matching the argument.

Command - oSelect.DeselectByText

isMultiple

boolean SelectElement.IsMultiple { get; } – This tells whether the SELECT element support multiple selecting options at the same time or not. This accepts nothing by returns boolean value(true/false).

Command - oSelect.IsMultiple;

This is done by checking the value of the "multiple" attribute.

Example - Refer the above Screen shot of MULTI SELECT for multiple attribute*

Multi Select Methods

This one also just works on Multiple selection boxes and not on regular List boxes or dropdowns. There is no additional logic behind selecting multiple options of Select element. All you need to do is to fire select commands on multiple elements one by one that's it.

	SelectElement oSelect = new SelectElement(driver.FindElement(By.Id(Element_ID)));
	oSelect.SelectByIndex(index);
	oSelect.SelectByIndex(index);

	// Or can be used as
	oSelect.SelectByText(text);
	oSelect.SelectByText(text);

	// Or can be used as
	oSelect.SelectByValue(value);
	oSelect.SelectByValue(value);

Practice Exercise -1 (Drop Down Box/List)

  1. Launch new Browser
  2. Open “http://toolsqa.com/automation-practice-form/
  3. Select 'Continents' Drop down ( Use Id to identify the element )
  4. Select option 'Europe' (Use SelectByIndex)
  5. Select option 'Africa' now (Use SelectByText)
  6. Print all the options for the selected drop down and select one option of your choice
  7. Close the browser

Solution

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ToolsQA.Selenium_Basics
{
    class DropDownAndSelectOperations
    {
        [Test]
        public void Test()
        {

            // Create a new instance of the Firefox driver
            IWebDriver driver = new FirefoxDriver();

            // Put an Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

            // Launch the URL
            driver.Url = "https://toolsqa.com/automation-practice-form";

            // Step 3: Select 'Continents' Drop down ( Use Id to identify the element )
            // Find Select element of "Single selection" using ID locator.
            SelectElement oSelection = new SelectElement(driver.FindElement(By.Id("continents")));

            // Step 4:) Select option 'Europe' (Use selectByIndex)
            oSelection.SelectByText("Europe");

            // Using sleep command so that changes can be notice
            Thread.Sleep(2000);

            // Step 5: Select option 'Africa' now (Use selectByVisibleText)
            oSelection.SelectByIndex(2);
            Thread.Sleep(2000);

            // Step 6: Print all the options for the selected drop down and select one option of your choice
            // Get the size of the Select element
            IList <IWebElement> oSize = oSelection.Options;

            int iListSize = oSize.Count;
            // Setting up the loop to print all the options
            for (int i = 0; i < iListSize; i++)
            {
                // Storing the value of the option	
                String sValue = oSelection.Options.ElementAt(i).Text;
                // Printing the stored value
                Console.WriteLine("Value of the Select item is : " + sValue);

                // Putting a check on each option that if any of the option is equal to 'Africa" then select it 
                if (sValue.Equals("Africa"))
                {
                    oSelection.SelectByIndex(i);
                    break;
                }

            }

            // Kill the browser
            driver.Close();
        }
    }
}

Practice Exercise -2 (Multiple Selection Box/List)

  1. Launch new Browser
  2. Open “http://toolsqa.com/automation-practice-form/
  3. Select 'Selenium Commands' Multiple selection box ( Use Name locator to identify the element )
  4. Select option 'Browser Commands'  and then deselect it (Use SelectByIndex and DeselectByIndex)
  5. Select option 'Navigation Commands'  and then deselect it (Use SelectByText and DeselectByText)
  6. Print and select all the options for the selected Multiple selection list.
  7. Deselect all options
  8. Close the browser

Solution

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ToolsQA.Selenium_Basics
{
    class MultiSelect
    {
        [Test]
        public void Test()
        {
            // Create a new instance of the Firefox driver
            IWebDriver driver = new FirefoxDriver();

            // Put an Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

            // Launch the URL
            driver.Url= "https://toolsqa.com/automation-practice-form";

            // Step 3: Select 'Selenium Commands' Multiple select box ( Use Name locator to identify the element )
            SelectElement oSelection = new SelectElement(driver.FindElement(By.Name("selenium_commands")));

            // Step 4: Select option 'Browser Commands'  and then deselect it (Use selectByIndex and deselectByIndex)
            oSelection.SelectByIndex(0);
            Thread.Sleep(2000);
            oSelection.DeselectByIndex(0);

            // Step 5: Select option 'Navigation Commands'  and then deselect it (Use selectByVisibleText and deselectByVisibleText)
            oSelection.SelectByText("Navigation Commands");
            Thread.Sleep(2000);

            oSelection.DeselectByText("Navigation Commands");

            // Step 6: Print and select all the options for the selected Multiple selection list.
            IList <IWebElement> oSize = oSelection.Options;
            int iListSize = oSize.Count;

            // Setting up the loop to print all the options
            for (int i = 0; i < iListSize; i++)
            {
                // Storing the value of the option	
                String sValue = oSelection.Options.ElementAt(i).Text;
                // Printing the stored value
                Console.WriteLine("Value of the Item is :" + sValue);
                // Selecting all the elements one by one
                oSelection.SelectByIndex(i);

                Thread.Sleep(2000);
            }

            // Step 7: Deselect all
            oSelection.DeselectAll();

            // Kill the browser
            driver.Close();
        }
    }
}

CheckBox & Radio Button Operations in C#
CheckBox & Radio Button Operations in C#
Previous Article
Handle Dynamic WebTables with Selenium in CSharp
Handle Dynamic WebTables with Selenium in CSharp
Next Article
Lakshay Sharma
I’M LAKSHAY SHARMA AND I’M A FULL-STACK TEST AUTOMATION ENGINEER. Have passed 16 years playing with automation in mammoth projects like O2 (UK), Sprint (US), TD Bank (CA), Canadian Tire (CA), NHS (UK) & ASOS(UK). Currently, I am working with RABO Bank as a Chapter Lead QA. I am passionate about designing Automation Frameworks that follow OOPS concepts and Design patterns.
Reviewers
Virender Singh's Photo
Virender Singh

Similar Articles

Feedback