How To Select Dropdown In Selenium C#
Tags: testing, tutorial, webdev, programming
Published: 2022-11-21 13:49:57

Dropdowns and multi-selects are extremely common in today’s web pages. Dropdowns can be a great option to allow your users to choose from several options without having to scroll through a whole page. In HTML, these web elements are defined by the tag < select >, with multiple < option > child tags representing the available options to choose from.

In this [Selenium C# tutorial](https://www.lambdatest.com/blog/category/selenium-c/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog), I’ll show you how to select dropdown in Selenium C# and multiple select menus. Here, I will be running tests with different test data and demonstrate how to run them in parallel on the [cloud Selenium Grid](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog).

So, let’s get started!

***Upload your app for testing within seconds using the LambdaTest cloud and perform mobile app testing right away. Find bugs early on, improve performance, quality, user experience and make the most of [Mobile App Testing](https://www.lambdatest.com/mobile-app-testing?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=webpage) on LambdaTest.***

## How to get started with a Selenium project?

We first need to set up a new [Selenium project](https://www.lambdatest.com/blog/build-and-execute-selenium-projects/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog) in Visual Studio (or Visual Studio Code). For this Selenium C# tutorial, I will be using NUnit as a test framework. However, there are other frameworks available, such as XUnit or MSTest.

![](https://cdn-images-1.medium.com/max/2532/1*QhPnIYb66iMT7_xeGFJdTA.png)

**Step 1**: Add the Selenium packages we will use in the project. To do this, right-click on the project name in the Solution Explorer pane, and select *Manage NuGet packages*:

![](https://cdn-images-1.medium.com/max/2000/1*aQ3n4-gAb9xFMLkCV_sq8g.png)

**Step 2**: Search for and install:

* **Selenium.WebDriver**: we need it to interact with the WebElements on the page.

* **Selenium.Support**: it’s the package that enables us to work with dropdowns in Selenium.

* **Selenium.WebDriver.ChromeDriver (or a different driver if you want to test on another browser)**: allows the interaction with the browser.

You will then have them in the list of installed packages:

![](https://cdn-images-1.medium.com/max/2000/1*MqdjS0LvERzxPR6suySNXA.png)

{% youtube https://youtu.be/UdsGfnBUYSI?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog  %}

In the next section of this article on how to select dropdown in Selenium C#, we will learn about the SelectElement Class in Selenium.

## The SelectElement Class in Selenium C#

The **SelectElement** class in Selenium C# is part of the Selenium.Support NuGet package. It allows us to interact with the dropdown and multiple select menus on web pages.

It also allows you to select and deselect options from the dropdown, validate if it allows multiple selections, see all the available options, and see what options are currently selected.

To understand how to select dropdown in Selenium C#, let me show how a dropdown looks in the Inspector from Developer Tools:

![](https://cdn-images-1.medium.com/max/2000/1*b7b-1l70FkWdNZhz5wX8oQ.png)

This is a simple dropdown that allows you to choose a day of the week.

Methods in the SelectElement class:

* **SelectByValue()**: will select the option based on the value from the HTML.

* **SelectByText()**: used to select the dropdown option based on the displayed text.

* **SelectByIndex()**: selects the option based on index. The index starts from 0, not 1!

* **SelectedOption()**: returns the selected WebElement.

* **AllSelectedOptions()**: returns a list of the selected WebElements. It should be used only on multiple selections.

* **IsMultiple()**: a boolean attribute with the value True if the selection allows multiple selections and False if it doesn’t.

* **DeelectByValue()**: will deselect the option based on its value.

* **DeselectByText()**: used to deselect the dropdown option based on the text.

* **DeselectByIndex()**: deselects the option based on index.

* **DeselectAll()**: will deselect all previously selected options.

These are the main things you need to know while you are learning how to select dropdown in Selenium C#. Now let’s see it in action.

## How to select dropdown in Selenium C# with an example?

I’m going to demonstrate how to select dropdown in Selenium C# with a simple scenario.

**Test Scenario**

* Navigate to the [LambdaTest Playground Dropdown Demo](https://www.lambdatest.com/selenium-playground/select-dropdown-demo?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog) page.

* Select Wednesday from the dropdown.

* Validate that the text displays the selected day of the week.

**Implementation**

Before you get started, make sure you create a new NUnit test project in Visual Studio or Visual Code, and add the following NuGet packages:

* **Selenium.WebDriver** — I’m using version 3.141.0 in this tutorial.

* **Selenium.Support** — should have the same version as Selenium.WebDriver.

* **Selenium.Support.ChromeDriver, Selenium.WebDriver.IEDriver, Selenium.Firefox.WebDriver, etc.**— depending on the browser you want to use in your test. Going forward, I will use Google Chrome for my tests, but feel free to choose your favorite browser.

Then, in a new class, we need to write the following Selenium C# code to perform the dropdown test:

    using NUnit.Framework;
    using OpenQA.Selenium;
    using OpenQA.Selenium.Support.UI;
    using System;
    using OpenQA.Selenium.Remote;
     
    namespace SeleniumTutorial
    {
        public class DropDown
        {
            private static IWebDriver driver;
            public static string gridURL = "@hub.lambdatest.com/wd/hub";
            public static string LT_USERNAME = "LT_USERNAME";
            public static string LT_ACCESS_KEY = "LT_ACCESS_KEY";
     
            [SetUp]
            public void Setup()
            {
                var desiredCapabilities = new DesiredCapabilities();
                desiredCapabilities.SetCapability("browserName", "Chrome");
                desiredCapabilities.SetCapability("platform", "Windows 11");
                desiredCapabilities.SetCapability("version", "101.0");
                desiredCapabilities.SetCapability("screenResolution", "1280x800");
                desiredCapabilities.SetCapability("user", LT_USERNAME);
                desiredCapabilities.SetCapability("accessKey", LT_ACCESS_KEY);
                desiredCapabilities.SetCapability("build", "Selenium C-Sharp");
                desiredCapabilities.SetCapability("name", "Selenium Test");
                driver = new RemoteWebDriver(new Uri($"https://{LT_USERNAME}:{LT_ACCESS_KEY}{gridURL}"), desiredCapabilities, TimeSpan.FromSeconds(600));
            }
     
            [Test]
            public void ValidateDropDownSelection()
            {
                string dayOfTheWeek = "Wednesday";
                driver.Navigate().GoToUrl("https://www.lambdatest.com/selenium-playground/select-dropdown-demo");
                SelectElement dropDown = new SelectElement(driver.FindElement(By.Id("select-demo")));
                dropDown.SelectByValue(dayOfTheWeek);
                string actualText = driver.FindElement(By.CssSelector(".selected-value.text-size-14")).Text;
                Assert.True(actualText.Contains(dayOfTheWeek), $"The expected day of the week {dayOfTheWeek} was not selected. The actual text was: {actualText}.");
            }
     
            [TearDown]
            public void TearDown()
            {
                driver.Quit();
            }
        }
    }

**Code Walkthrough**

Now let me guide you through the lines of code to get a clear picture of how to select dropdown in Selenium C#.

    using NUnit.Framework;
    using OpenQA.Selenium;
    using OpenQA.Selenium.Support.UI;
    using System;
    using OpenQA.Selenium.Remote;

This part contains the packages used in the class.

    private static IWebDriver driver;
    public static string gridURL = "@hub.lambdatest.com/wd/hub";
    public static string LT_USERNAME = "LT_USERNAME";
    public static string LT_ACCESS_KEY = "LT_ACCESS_KEY";

The first line, above, is where I declare the WebDriver, and the next variables are related to my LambdaTest account.

LambdaTest is a cloud-based [cross browser testing](https://www.lambdatest.com/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog) platform that allows you to perform [Selenium C# automation testing](https://www.lambdatest.com/c-sharp-automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog) at scale over an [online browser farm](https://www.lambdatest.com/online-browser-farm?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog) of 3000+ browsers and operating systems. With LambdaTest, you can run your automated C# test scripts faster and more efficiently by running them in parallel on the fastest cloud-based infrastructure. Therefore, you can test more in less time and ship quality products faster.

{% youtube https://youtu.be/WZlsHlReRww?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog  %}

You can also Subscribe to the [LambdaTest YouTube Channel](https://www.youtube.com/channel/UCCymWVaTozpEng_ep0mdUyw?sub_confirmation=1?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog) and stay updated with the latest tutorials around [automated browser testing](https://www.lambdatest.com/automated-browser-testing?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog), [Selenium testing](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog), CI/CD, and more.

Replace LT_USERNAME and LT_ACCESS_KEY with your own credentials, i.e., username and the access key from your [LambdaTest Profile Section](https://accounts.lambdatest.com/login?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog).

   
    [SetUp]
    public void Setup()
    {
          var desiredCapabilities = new DesiredCapabilities();
          desiredCapabilities.SetCapability("browserName", "Chrome");
          desiredCapabilities.SetCapability("platform", "Windows 11");
          desiredCapabilities.SetCapability("version", "101.0");
          desiredCapabilities.SetCapability("screenResolution", "1280x800");
          desiredCapabilities.SetCapability("user", LT_USERNAME);
          desiredCapabilities.SetCapability("accessKey", LT_ACCESS_KEY);
          desiredCapabilities.SetCapability("build", "Selenium C-Sharp");
          desiredCapabilities.SetCapability("name", "Selenium Test");
          driver = new RemoteWebDriver(new Uri($"https://{LT_USERNAME}:{LT_ACCESS_KEY}{gridURL}"), desiredCapabilities, TimeSpan.FromSeconds(600));
    }

Using the [SetUp] [annotation in NUnit](https://www.lambdatest.com/blog/nunit-annotations-for-selenium-automation/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog), I let my code know that this method needs to be run before each of my tests. Then, inside it, I set the driver’s capabilities based on the browser type, version, OS, and screen resolution I want to use in my tests.

I use the [Capabilities Generator](https://www.lambdatest.com/capabilities-generator/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog) from LambdaTest, so I don’t have to enter them by hand:

![](https://cdn-images-1.medium.com/max/3772/1*xrEsaXTKal_YwofL4XlMmw.png)

This way, I just select my configuration, select the C# language, and simply copy them into my code.

Then, in the new driver instance, I use the capabilities I copied before and the URL created by combining my username, access key, and the LambdaTest Selenium Grid URL. I like using string interpolation because it reads much easier than concatenation.

Moving on to the test, let me break it down a bit more:

The [Test] annotation marks the method beneath it as a test method. After the project is built, I can see this test in the Test Explorer and run it from there:

![](https://cdn-images-1.medium.com/max/2000/1*r3MqT3wZG0C9-6PgfUnM9A.png)

    string dayOfTheWeek = "Wednesday";

This one is pretty straightforward. I created a string variable to store the value I want to test because I am using it in more than one place, and I don’t want to update it in multiple places if the value changes.

    driver.Navigate().GoToUrl("https://www.lambdatest.com/selenium-playground/select-dropdown-demo");

The Navigate() method in Selenium C# instructs the browser to navigate to a specific location, in my case, to the given URL (using the GoToUrl() method).

The next part is the actual dropdown selection, which shows how to select dropdown in Selenium C#.

    SelectElement dropDown = new SelectElement(driver.FindElement(By.Id("select-demo")));
    dropDown.SelectByValue(dayOfTheWeek);

The dropdown web element in Selenium C# has the type SelectElement and has to be declared as a new instance of the SelectElement class. The dropdown web element has an Id value, so I will use the Id locator.

You can use the browser’s Developer Tools to inspect an element (right-click on the element and select Inspect, and you will see its HTML attributes):

![](https://cdn-images-1.medium.com/max/3822/1*JqBdrZ5ntf9pL_VqpiTv_g.png)

If you’re not familiar with Selenium C# element interaction, you can check out my previous tutorial on [automation testing with Selenium C#](https://www.lambdatest.com/blog/selenium-c-sharp/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog).

I prefer to use SelectByValue() or SelectByText() for selecting the dropdown value, which in this particular case would accept the same parameter. Using SelectByIndex() also works, but then I would need to know the exact order of the options and ensure that the order doesn’t change. For a day of the week dropdown, that’s fine, but in most cases, the available options might change.

The last part is the validation, where I verify that the app works as expected:

    string actualText = driver.FindElement(By.CssSelector(".selected-value.text-size-14")).Text;
    Assert.True(actualText.Contains(dayOfTheWeek), $"The expected day of the week {dayOfTheWeek} was not selected. The actual text was: {actualText}.");

I identified the text displayed based on its [CSS Selector](https://www.lambdatest.com/blog/selenium-c-sharp/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog), then used the Assert class from NUnit to check that it contains the day of the week I previously selected. In case the [NUnit assertion](https://www.lambdatest.com/blog/asserts-in-nunit/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog) fails, the test will display a message — I am using string interpolation to insert the string variables in the text.

The final method is executed after each test, and what it does is close all driver instances:

    [TearDown]
    public void TearDown()
    {
        driver.Quit();
    }

***Try an online [Selenium Testing](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=webpage) Grid to run your browser automation testing scripts. Our cloud infrastructure has 3000+ desktop & mobile environments. Try for free!***

## How to select dropdown in Selenium C# and run the test in parallel?

In this section of this article on how to select dropdown in Selenium C#, I will show you how you can run the same test with different data. The steps will remain the same, so we want to use the same method with different parameters.

With NUnit, this is achieved with the TestCase attribute. And since we will have more tests now, it’s a good idea to perform [parallel testing](https://www.lambdatest.com/blog/what-is-parallel-testing-and-why-to-adopt-it/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog), so they don’t take so long to execute. For this, we have the Parallelizable attribute. However, [NUnit parallelization](https://www.lambdatest.com/blog/parallel-execution-with-specflow-nunit-and-selenium/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog) is not thread-safe, so the tests in a class share the same instance of the driver which might result in unexpected failures.

So the test method now should look like this:

    [Test]
    [TestCase("Monday")]
    [TestCase("Tuesday")]
    [TestCase("Wednesday")]
    [TestCase("Thursday")]
    [TestCase("Friday")]
    [TestCase("Saturday")]
    [TestCase("Sunday")]
    [Parallelizable(ParallelScope.All)]
    public void ValidateDropDownSelection(string dayOfTheWeek)
    {    driver.Navigate().GoToUrl("https://www.lambdatest.com/selenium-playground/select-dropdown-demo");
        SelectElement dropDown = new SelectElement(driver.FindElement(By.Id("select-demo")));
        dropDown.SelectByValue(dayOfTheWeek);
        string actualText = driver.FindElement(By.CssSelector(".selected-value.text-size-14")).Text;
        Assert.True(actualText.Contains(dayOfTheWeek), $"The expected day of the week {dayOfTheWeek} was not selected. The actual text was: {actualText}.");
    }

**Code Walkthrough**

    [Test]
    [TestCase("Monday")]
    [TestCase("Tuesday")]
    [TestCase("Wednesday")]
    [TestCase("Thursday")]
    [TestCase("Friday")]
    [TestCase("Saturday")]
    [TestCase("Sunday")]
    [Parallelizable(ParallelScope.All)]

With these lines of code, we instruct the test to run once for each day of the week string value.

The [Parallelizable(ParallelScope.All)] line means that the test can be run in parallel with other tests at the same level — in our case, the method level.

There are other scopes of parallelization in NUnit:

![](https://cdn-images-1.medium.com/max/2000/1*qNPmBnI4olxk5b6Fpb1RJg.png)

* **All**: the test and its children can run in parallel with others at the same level.

* **Children**: the scope is defined at the class or assembly level, and child tests of the class or assembly can run in parallel.

* **Fixtures**: fixtures can run in parallel.

* **Self**: the test itself can run in parallel with other tests.

    public void ValidateDropDownSelection(string dayOfTheWeek)

The test method also takes a parameter now. You can see I removed the line:

    string dayOfTheWeek = "Wednesday";

This is because the value of the dayOfTheWeek variable now comes from the TestCase attribute.

Everything else stays the same. Now you will see seven tests available in the Test Explorer. When you run them on the [Selenium Grid](https://www.lambdatest.com/blog/selenium-grid-setup-tutorial/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog), they will also run in parallel:

![](https://cdn-images-1.medium.com/max/2000/1*LmBBvh2ZpO5sbnK5belypw.png)

You can see the tests in LamdaTest in real-time while they are running and also see the video recordings afterwards:

![](https://cdn-images-1.medium.com/max/3810/1*tvUoEUcd0fsaDBhyiefiGg.png)

On the left-hand side, there is the recording, and the right side displays the test steps, the step duration, and the result. If you click on the timestamp of a step, the video will jump to that point so you can see the action in the recording.

You can analyze your test performance through the [LambdaTest Analytics Dashboard](https://analytics.lambdatest.com/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog). The Test Summary section shows all test results, their status, and the total number of tests passed or failed. The Test Overview section shows snapshots of recently executed test runs.

![](https://cdn-images-1.medium.com/max/2000/1*D-mwRfy-PJpjcBqAubAXGg.gif)

LambdaTest also provides some advanced features like [HyperExecute](https://www.lambdatest.com/hyperexecute?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog), which helps in achieving up to 70% faster execution of your Selenium NUnit test cases. HyperExecute is a blazing fast test end-to-end test orchestration cloud that allows you to group and distribute tests intelligently across runner environments.

So far, we have seen how to select dropdown in Selenium C#. In the next section, we will learn to handle multiple select menus.

{% youtube https://youtu.be/5Q0yxvErcCw?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog  %}

## How to handle multiple select in Selenium C#?

In this section of this article on how to select dropdown in Selenium C#, I want to show you how to work with a multi select dropdown using Selenium C#. We’ve already discussed the available methods, so let’s jump in.

**Test Scenario**

* Navigate to the [LambdaTest Playground Dropdown Demo](https://www.lambdatest.com/selenium-playground/select-dropdown-demo?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog) page.

* Verify that the Multi-Select List Demo allows multiple selections — if not, display a message.

* If it does allow multiple selections, select Florida, New York, and Texas

* Deselect all values.

**Implementation**

The SetUp and TearDown methods are the same as before, so I will just show you the test method code:

    [Test]
    public void ValidateMultipleSelection()
    {
        driver.Navigate().GoToUrl("https://www.lambdatest.com/selenium-playground/select-dropdown-demo");
        string[] selectedStates = { "Florida", "New York", "Texas" };
        var multiSelect = new SelectElement(driver.FindElement(By.Id("multi-select")));
        Assert.IsTrue(multiSelect.IsMultiple, "The Select does not allow multiple selection.");
        foreach (var state in selectedStates)
        {
            multiSelect.SelectByText(state);
        }
        multiSelect.DeselectAll();
    }

**Code Walkthrough**

The first few lines don’t have anything new. We need to navigate to the web page (the same as before), create an array of strings with the values we want to select, and declare the multiSelect dropdown using the [FindElement() method in Selenium](https://www.lambdatest.com/blog/findelement-and-findelements-in-selenium/?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog).

    driver.Navigate().GoToUrl("https://www.lambdatest.com/selenium-playground/select-dropdown-demo");
        string[] selectedStates = { "Florida", "New York", "Texas" };
        var multiSelect = new SelectElement(driver.FindElement(By.Id("multi-select")));

In Developer Tools, you can see that the select element has an ID, which I used above:

![](https://cdn-images-1.medium.com/max/2046/1*5upb8SFToyx73mJbmExDvw.png)

Next, I want to validate that the SelectElement allows multiple selections. As I previously mentioned, the IsMultiple attribute will let me know if I can select multiple options or not.

    Assert.IsTrue(multiSelect.IsMultiple, "The Select does not allow multiple selection.");

If this assertion fails, the test will simply fail and stop executing the following steps. Of course, I expect it to pass, and if multiple selections is allowed, I want to perform the next actions:

    foreach (var state in selectedStates)
    {
        multiSelect.SelectByText(state);
    }

This is a simple loop that goes through each value of the selectedStates array, and then selects the value, using the text this time — once again, the text and the value of the options are the same.

The last step deselects all the previously selected values:

    multiSelect.DeselectAll();

Are you a tester looking to hone your craft? Prove your worth by earning the Selenium C# 101 certification from LambdaTest:

Here’s a short glimpse of the Selenium C# 101 certification from LambdaTest:

{% youtube https://youtu.be/ZU85Mjwgv54?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=blog  %}

***Test on [Selenium Automation](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=nov21_pk&utm_term=pk&utm_content=webpage) Grid Cloud of 3000+ Desktop & Mobile Browsers.***

## Conclusion

If you followed this tutorial blog on how to select dropdown in Selenium C#, you should now know how to select or deselect a dropdown value using Selenium C#, how to work with multiple selects, and also how to run the same test with different test data in NUnit.

And as a bonus, you could also see how to parallelize the tests and run them on the remote Selenium grid to save the test execution time.