RadioButton Control in C#

May 30, 2020
Tutorials
radio button in c#

The RadioButton component allows you to force a user to select a single choice from a set of options. This component will be used in a group of at least two RadioButton instances. Only one member per group can be selected at any given time. Now, we will create a RadioButtons that when chose the background color changes.

Let’s start this tutorial!

1. Create a Windows Form Application in C# for this tutorial by following steps in Microsoft Visual Studio 2019: Go to File, click New Project, and choose Windows Application.

2. Then, add three RadioButton named RadioButton1 labeled “Yellow“, RadioButton2 labeled “Blue“, and RadioButton3 labeled “Red“. Next add a Button named Button1. You must design your interface like this:

design

3. Put this code in Button1_Click. This will display the result of changing the color of our form when choosing the preferred color in Radio Buttons.

private void Button1_Click(System.Object sender, System.EventArgs e)
{
    if (RadioButton1.Checked == true)
    {
        this.BackColor = Color.Yellow;
        return;
    }
    else if (RadioButton2.Checked == true)
    {
        this.BackColor = Color.Blue;
        return;
    }
    else
    {
        this.BackColor = Color.Red;
    }
}

We use the code statement of If-else Decision statement to choose from the three different choices. RadioButton1 labeled “Yellow“, RadioButton2 labeled “Blue“, and RadioButton3 labeled “Red“. The checked = true is our event for our RadioButton as it toggles on and off. When we check RadioButton1, it will have a background color of Yellow (this.BackColor = Color.Yellow). The “this” here indicates that we are referring to Form1. Next, When we check RadioButton2, it will have a background color of Blue (this.BackColor = Color.Blue). So on and so  forth.

Output:

output

output

output

Facebook Comments

Leave a Reply

Your email address will not be published.