- Oct 25, 2018
- admin
- 0
CheckBox & Radio Button Operations in selenium C#
CheckBox & Radio Button Operations in selenium C# are easy to perform and most of the times the simple ID attributes work fine for both of these. But selection and d-selection is not the only thing we want with Check Boxes and Radio Buttons. We might like to check that if the Check Box is already checked or if the Radio Button is selected by default or anything. Check Boxes and Radio Button deals exactly the same way and you can perform below mentioned operations on either of them.
Different Selection Method
By ID
If ID is given for the Radio Button/CheckBox and you just want to click on it irrespective of it’s value, then the command will be like this:
1
2
3
|
IWebElement radioBtn = driver.FindElement(By.Id(“ttradio”));
radioBtn.Click();
|
With Selected
If your choice is based on the pre-selection of the Radio Button/Check Box and you just need to select the deselected Radio Button/Check Box. Assume there are two Radio Buttons/Check Boxes, one is selected by default and you want to select the other one for your test. With IsSelected statement, you can get to know that the element is selected or not.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
// Store all the elements of same category in the list of WebLements
IList<IWebElement> oRadioButton = driver.FindElements(By.Name(“ttRadio”));
// Create a boolean variable which will hold the value (True/False)
bool bValue = false;
// This statement will return True, in case of first Radio button is selected
bValue = oRadioButton.ElementAt(0).Selected;
// This will check that if the bValue is True means if the first radio button is selected
if (bValue == true)
{
// This will select Second radio button, if the first radio button is selected by default
oRadioButton.ElementAt(1).Click();
}
else
{
// If the first radio button is not selected by default, the first will be selected
oRadioButton.ElementAt(0).Click();
}
|
Note: Name is always same for the same group of Radio Buttons/Check Boxes but their Values are different. So if you find the element with the name attribute then it means that it may contain more than one element, hence we need to use FindElements method and store the list of WebElements.
With Value
You can even select Radio Buttons/Check Boxes with their Values.
// Find the checkbox or radio button element by Name IList <IWebElement> oCheckBox = driver.FindElements(By.Name("ttCheck")); // This will tell you the number of checkboxes are present int Size = oCheckBox.Count; // Start the loop from first checkbox to last checkboxe for (int i = 0; i < Size; i++) { // Store the checkbox name to the string variable, using 'Value' attribute String Value = oCheckBox.ElementAt(i).GetAttribute("value"); // Select the checkbox it the value of the checkbox is same what you are looking for if (Value.Equals("techtutorialz")) { oCheckBox.ElementAt(i).Click(); // This will take the execution out of for loop break; } }