Saturday, August 6, 2016

WebDriver - Select Multiple Items in a List

WebDriver - Select Multiple Items in a List


This is the MultiSelect Drop-Down ListBox that we are using for all the examples below:


Save the above code in ".html" file and open it in a browser, it looks like below:


Below are few examples of how to select multiple options in the list. In all our examples below, we are using SelectElement class, which is included in OpenQA.Selenium.Support.UI.

Example 1 of Select Multiple Options - SelectByValue

Lets go through the first example line by line. First we are creating a new Firefox driver. Then we are navigating to our file in order to open that multiselect dropdown listbox. Next we are creating an object of SelectElement class and assigning the multiselect list to it by name. At last we are selecting the value in the list by using SelectByValue method of SelectElement class.



Below is the result of example 1. "Australia" is selected here because the value "Third" is for "Australia" (as can be seen in the multiselect list at the top).



Example 2 of Select Multiple Options - SelectByText

This is similar to example 1 except that we are using SelectByText here and as a result Denmark is selected below in the result.





Example 3 of Select Multiple Options - SelectByIndex

In this example we are using SelectByIndex. Index starts from 0. We want to select "India", hence we have given index as 1. 0 is for "Please Select".





Example 4 of Select Multiple Options - AllSelectedOptions

In this example first we have selected two options with SelectByIndex and then we are using AllSelectedOptions property to get count of all the selected options. In our case the result will be 2.



Example 5 of Select Multiple Options - SelectedOption

We are selecting the third item in the list using SelectByIndex(2). Third, because index starts from 0. Then we are using GetAttribute method of SelectedOption property to get the Value of the selected item, America, in our case. So result will be "Second".



Example 6 of Select Multiple Options - SelectedOption

This example prints out the "Text" of the selected option. America in our case.



Example 7 of Select Multiple Options - AllSelectedOptions

Firstly we are selecting two options (America and Finland in our case) using SelectByIndex. We get all selected options in elementCount list. Then we iterate and print the text of all the selected options using elementCount[i].Text.