top of page

Selenium C# Tutorial: Exploring the Radio-Button element (C#)

Updated: Mar 5

A radio button or option button is a graphical control element that allows users to choose only one from a predefined set of options. This article will explore the main properties and methods associated with this element.


To work with the code example below, please use the following HTML code (Save it as . HTML and open it in your browser).

<form>

<input type="radio" name="Color" value="Red" >Red Color<br>

<input type="radio" name="Color" value="Orange"> Orange Color<br>

<input type="radio" name="Color" value="Blue" checked> Blue Color<br>

<input type="radio" name="Color" value="Amber" > Amber Color<br>

<input type="radio" name="Color" value="Black">Black Color<br>

</form>

Example 1: Checking which button is currently checked


class Program

{

public int MyProperty { get; set; }

static void Main(string[] args)

{

string radioButtons = "//input[contains(@name,'Color')]";

IWebDriver firefoxDriver = new FirefoxDriver();

Backlog.TestPreperationGeneralSites(firefoxDriver, "file:///C:/Users/home-pc3/Downloads/new%201.html");

Backlog.WorkingWithRadioButton(firefoxDriver,radioButtons);

}

}


static public class Backlog

{

static IWebElement searchFieldtextBox;

static IWebElement searchFieldButton;

static IWebElement checkBoxToValidate;

internal static void WorkingWithRadioButton(IWebDriver firefoxDriver, string radioButtons)

{

foreach (var item in firefoxDriver.FindElements(By.XPath("//input[contains(@name,'Color')]")))

{

if (item.Selected == true)

{

Console.ForegroundColor = ConsoleColor.Green;

Console.WriteLine("The Current button is: " + item.GetAttribute("value") + " |is it selected? " + item.Selected);

}

else

{

Console.ForegroundColor = ConsoleColor.Red;

Console.WriteLine("The Current button is: " + item.GetAttribute("value") + " |is it selected? " + item.Selected);

}

}

}

}


Result






145 views0 comments