Home

Button-Based Controls: Radio Buttons

Introduction to Radio Buttons

Description

A radio button, sometimes called an option button, is a circular control that comes in a group with other radio buttons. Each radio button is made of a small empty circle O. From the group, when the user clicks one of them, the radio button that was clicked becomes filled with a big dot 8. When one of the radio buttons in the group is selected and displays its dot, the others display empty circles. To guide the user as to what the radio buttons mean, each is accompanied by a label.

Here is an example of a form with three radio buttons: Small, Medium, and Large

Radio Buttons

Creating Radio Buttons

To create a radio button, on the Toolbox, you can click the RadioButton control Radio Button. To programmatically create a radio button, declare a variable of type RadioButton, use the new operator to allocation memory for it and add it to the Controls collection of its parent. Because radio buttons always come as a group, you should include them in another control that visibly shows that the radio buttons belong together. The most common control used for this purpose is the group box created using the GroupBox control.

Characteristics of Radio Buttons

The Location of a Radio Button

Unlike most of other controls that can be positioned anywhere, a radio button should not be placed directly on a form. Instead, a radio button should be positioned in a container that belongs to a form. The typical container is the group box. When a radio button is added to a group box, the location of the radio button is relative to its parent. This location is easy to specify if you are visually designing the application. If you are programmatically creating it, make sure you specify the location based on the control that will hold the radio button. Here are examples:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form
{
    RadioButton radSmall;
    RadioButton radMedium;
    RadioButton radLarge;
    GroupBox    grpPizzaSize;

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        grpPizzaSize = new GroupBox();
        grpPizzaSize.Size = new Size(160, 120);
        grpPizzaSize.Location = new Point(20, 10);

        radSmall = new RadioButton();
        radSmall.Location = new Point(20, 20);

        radMedium = new RadioButton();
        radMedium.Location = new Point(20, 50);

        radLarge = new RadioButton();
        radLarge.Location = new Point(20, 80);

        grpPizzaSize.Controls.Add(radSmall);
        grpPizzaSize.Controls.Add(radMedium);
        grpPizzaSize.Controls.Add(radLarge);

        Controls.Add(grpPizzaSize);
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

This would produce:

Radio Buttons

The Caption of a Radio Button

To indicate what a radio button represents, it is accompanied by text, also referred to as its caption. To specify the caption of a radio button at a design time, type a string in the Text field of its Properties window. To programmatically specify the caption of a radio button, assign a string to its Text property. Here are examples:

private void InitializeComponent()
{
        grpPizzaSize = new GroupBox();
        grpPizzaSize.Text = "Pizza Size";
        grpPizzaSize.Size = new Size(160, 120);
        grpPizzaSize.Location = new Point(20, 10);

        radSmall = new RadioButton();
        radSmall.Text = "Small";
        radSmall.Location = new Point(20, 20);

        radMedium = new RadioButton();
        radMedium.Text = "Medium";
        radMedium.Location = new Point(20, 50);

        radLarge = new RadioButton();
        radLarge.Text = "Large";
        radLarge.Location = new Point(20, 80);

        grpPizzaSize.Controls.Add(radSmall);
        grpPizzaSize.Controls.Add(radMedium);
        grpPizzaSize.Controls.Add(radLarge);

        Controls.Add(grpPizzaSize);
    }
}

This would produce:

Checking a Radio Button

If you add only one radio button to a container, when the application starts, the lone radio button would appear with an empty round circle. If the user clicks that lone radio button, the radio button's circle becomes filled with a dot and the user cannot remove or change this aspect. If you equip a container with more than one radio button, the user can click the desired one to select it and only one of the radio buttons can be selected at a given time. The radio button that is selected is referred to as checked. To support this description, the RadioButton class is equipped with a property named Checked.

At design time, to select a radio button, in the Properties window, set its Checked property to True. At run time, to programmatically select a radio button, assign a true value to its Checked property. To find out whether a particular radio button is selected, get the value of its Checked property. You can also programmatically check a radio button. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)
{
        radioButton2.Checked = true;
}

If the user clicks a radio button, since this control is primarily a button, the radio button that was clicked in the group fires a Click event. This is the most regularly used event of a radio button. Normally, when the user clicks a button in the group, the round box of that button becomes filled and the Click event is fired. If the user clicks a button that is already checked, nothing changes in the round box of that button but the Click event fires again. In some cases, you may want to execute code only if the checked state of a button has actually changed rather than being interested in whether the button was clicked or not. Fortunately, if you are interested only when the checked stated of a button is changed, you can use the CheckedChanged event. This event is fired whenever the checked state of a button is modified. Here is an example of implementing it:

private void rdoSmall_CheckedChanged(object sender, System.EventArgs e)
{
        txtPizzaPrice.Text = "$8.75";
}

The Alignment of a Radio Button

By default, the round box of a radio button is positioned to the left side of its accompanying label but you have many options. Besides the left position, you can position the round box to the top, the right, or the bottom etc side of its label. The position of the round box with regards to its label is controlled by the CheckAlign property which is a value of type ContentAlignment. To specify it at design time, access the Properties window of the radio button and select the desired value from the CheckAlign field. You can also change this property programmatically. Here are examples:

private void InitializeComponent()
{
        grpPizzaSize = new GroupBox();
        grpPizzaSize.Text = "Pizza Size";
        grpPizzaSize.Size = new Size(160, 120);
        grpPizzaSize.Location = new Point(20, 10);

        radSmall = new RadioButton();
        radSmall.Text = "Small";
        radSmall.CheckAlign = ContentAlignment.TopCenter;
        radSmall.Location = new Point(20, 20);

        radMedium = new RadioButton();
        radMedium.Text = "Medium";
        radMedium.CheckAlign = ContentAlignment.TopCenter;
        radMedium.Location = new Point(20, 50);

        radLarge = new RadioButton();
        radLarge.Text = "Large";
        radLarge.CheckAlign = ContentAlignment.TopCenter;
        radLarge.Location = new Point(20, 80);

        grpPizzaSize.Controls.Add(radSmall);
        grpPizzaSize.Controls.Add(radMedium);
        grpPizzaSize.Controls.Add(radLarge);

        Controls.Add(grpPizzaSize);
}

Besides the alignment of the check box, you can also control the alignment of the text with regards to the bounding rectangle of the control. This characteristic is controlled by the TextAlign property of the RadioButton class. The TextAlign property also is of type ContentAlignment.

The Appearance of a Radio Button

By default, a radio button appears as a rounded box that gets filled with a big dot when the user selects it. Optionally, you can make a radio button appear as a toggle button. Normally, if you make one radio button appear as a button, you should apply the same characteristics on the other radio buttons of the same group. The button would appear as a rectangular object. When the user clicks such a button, it appears down:

Pizza Order

If the user clicks another button, this button becomes up:

Pizza Order

To change the appearance of a radio button, assign the Button or Normal value to its Appearance property. The Appearance property is based on the Appearance enumeration. Here are examples:

private void InitializeComponent()
{
        grpPizzaSize = new GroupBox();
        grpPizzaSize.Text = "Pizza Size";
        grpPizzaSize.Size = new Size(150, 120);
        grpPizzaSize.Location = new Point(20, 10);

        radSmall = new RadioButton();
        radSmall.Appearance = Appearance.Button;
        radSmall.Location = new Point(20, 20);

        radMedium = new RadioButton();
        radMedium.Appearance = Appearance.Button;
        radMedium.Location = new Point(20, 50);

        radLarge = new RadioButton();
        radLarge.Appearance = Appearance.Button;
        radLarge.Location = new Point(20, 80);

        grpPizzaSize.Controls.Add(radSmall);
        grpPizzaSize.Controls.Add(radMedium);
        grpPizzaSize.Controls.Add(radLarge);

        Controls.Add(grpPizzaSize);
}

This would produce:

Appearance of Radio Buttons

As you can see, you can apply the Appearance property to a radio button that does not have a caption. You can also use a caption. If you do, make sure you align the caption to make is good to see. Here are examples:

private void InitializeComponent()
{
        grpPizzaSize = new GroupBox();
        grpPizzaSize.Text = "Pizza Size";
        grpPizzaSize.Size = new Size(150, 120);
        grpPizzaSize.Location = new Point(20, 10);

        radSmall = new RadioButton();
        radSmall.Text = "Small";
        radSmall.Appearance = Appearance.Button;
        radSmall.TextAlign = ContentAlignment.MiddleCenter;
        radSmall.CheckAlign = ContentAlignment.MiddleCenter;
        radSmall.Location = new Point(20, 20);

        radMedium = new RadioButton();
        radMedium.Text = "Medium";
        radMedium.Appearance = Appearance.Button;
        radMedium.TextAlign = ContentAlignment.MiddleCenter;
        radMedium.CheckAlign = ContentAlignment.MiddleCenter;
        radMedium.Location = new Point(20, 50);

        radLarge = new RadioButton();
        radLarge.Text = "Large";
        radLarge.Appearance = Appearance.Button;
        radLarge.TextAlign = ContentAlignment.MiddleCenter;
        radLarge.CheckAlign = ContentAlignment.MiddleCenter;
        radLarge.Location = new Point(20, 80);

        grpPizzaSize.Controls.Add(radSmall);
        grpPizzaSize.Controls.Add(radMedium);
        grpPizzaSize.Controls.Add(radLarge);

        Controls.Add(grpPizzaSize);
}

This would produce:

If you configure your application and give the user the ability to change the appearance of the radio button from a round circle to a rectangular object and vice-versa, and if the user decides to change this appearance, when this is done, the control whose appearance was changed fires an AppearanceChanged event. The AppearanceChanged event is of type EventArgs, meaning that it does not carry any significant information other than to let you know that the appearance of the button was changed.

Radio Buttons and Databases

Data Entry With Radio Buttons

With a group of radio buttons, you can first find out what radio button the user selected, and then pass the caption of that radio button to the column of the table, provided the caption of the radio button holds the exact same text the column is supposed to receive. Here is an example:

String-Based Values

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace StringDataEntry1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnAddEmployee_Click(object sender, EventArgs e)
        {
            string strMaritalStatus = "";

            if (rdoMarried.Checked == true)
                strMaritalStatus = rdoMarried.Text;
            else if (rdoSeparated.Checked == true)
                strMaritalStatus = rdoSeparated.Text;
            else if (rdoDivorced.Checked == true)
                strMaritalStatus = rdoDivorced.Text;
            else if (rdoWidow.Checked == true)
                strMaritalStatus = rdoWidow.Text;
            else
                strMaritalStatus = rdoSingle.Text;

            using (SqlConnection cntExercise =
            new SqlConnection("Data Source='EXPRESSION';" +
                              "Database='Exercise1';" +
                              "Integrated Security=SSPI;"))
            {
                SqlCommand cmdExercise =
                    new SqlCommand("INSERT INTO Personnel.Employees(EmployeeName, " +
                        "MaritalStatus) VALUES(N'" + txtEmployeeName.Text + "', N'" +
                                   strMaritalStatus + "');",
                                   cntExercise);

                cntExercise.Open();
                cmdExercise.ExecuteNonQuery();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
    }

    public class Program
    {
        [STAThread]
        static int Main()
        {
            System.Windows.Forms.Application.Run(new Exercise());
            return 0;
        }
    }
}

As an alternative to a combo box, you use a control that presents two choices as Yes/No or True/False to the user. When the user has made a selection, you can find out what the user selected, give it a value of 1 or 0, and then pass it as a numeric value to the column. In this case, or whenever you pass the value as a number, you can omit the single-quotes. Here is an example:

Boolean Data Entry

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Exercise2
{
    public partial class Employees : Form
    {
        public Employees()
        {
            InitializeComponent();
        }

        private void btnAddEmployee_Click(object sender, EventArgs e)
        {
            int iHasChildren = 0;
            int iMaritalStatus = 0;

            if (rdoMarried.Checked == true)
                iMaritalStatus = 1;
            else if (rdoSeparated.Checked == true)
                iMaritalStatus = 2;
            else if (rdoDivorced.Checked == true)
                iMaritalStatus = 3;
            else if (rdoWidow.Checked == true)
                iMaritalStatus = 4;
            else
                iMaritalStatus = 0;

            if (rdoYes.Checked == true)
                iHasChildren = 1;
            else
                iHasChildren = 0;

            using (SqlConnection cntExercise =
            new SqlConnection("Data Source='EXPRESSION';" +
                              "Database='Exercise1';" +
                              "Integrated Security=SSPI;"))
            {
                SqlCommand cmdExercise =
                    new SqlCommand("INSERT INTO Personnel.Employees " +
                                   "VALUES('" + txtEmployeeName.Text + "', " +
                                   iMaritalStatus + ", " + iHasChildren + ");",
                                   cntExercise);

                cntExercise.Open();
	        cmdExercise.ExecuteNonQuery();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}

Radio Buttons and Data Selection

Radio buttons work as a mutually-exclusive group where the user can select one item at a time. Although the functionality of radio buttons presents various options (for example some implementations treat each value of a radio button as an integer), a radio button primarily holds text. As such, it can follow the same rules as a label. The issue is that radio buttons behave in a group. This means that you must know what radio button in the group you are referring to. To do this, you can use a conditional statement. Here are examples:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Exercise2
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnBinder_Click(object sender, EventArgs e)
        {
            using (SqlConnection cntExercise =
            	new SqlConnection("Data Source=(local);" +
                                  "Database='Exercise1';" +
                                  "Integrated Security=SSPI;"))
            {
                SqlCommand cmdExercise =
                	new SqlCommand("SELECT * FROM Personnel.Employees;",
                        	       cntExercise);

                cntExercise.Open();
                SqlDataReader rdrExercise = cmdExercise.ExecuteReader();

                while(rdrExercise.Read())
                {
                    txtEmployeeName.Text = rdrExercise[3].ToString();
                    
                    if (rdrExercise[5].ToString() == "Full Time")
                        rdoFullTime.Checked = true;
                    else if (rdrExercise[5].ToString() == "Part Time")
                        rdoPartTime.Checked = true;
                    else
                        rdoUnspecified.Checked = true;
                }
            }
        }
    }
}