Home

Windows 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 RadioButton. To programmatically create a radio button, declare a variable of type RadioButton, use the gcnew 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:

#include <windows.h>

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;

public ref class CExercise : public Form
{
private:
    RadioButton ^ radSmall;
    RadioButton ^ radMedium;
    RadioButton ^ radLarge;
    GroupBox    ^ grpPizzaSize;

public:
    CExercise()
    {
	InitializeComponent();
    }

private:
    void InitializeComponent()
    {
        grpPizzaSize = gcnew GroupBox;
        grpPizzaSize->Size = System::Drawing::Size(160, 120);
        grpPizzaSize->Location = Point(20, 10);

        radSmall = gcnew RadioButton;
        radSmall->Location = Point(20, 20);

        radMedium = gcnew RadioButton;
        radMedium->Location = Point(20, 50);

        radLarge = gcnew RadioButton;
        radLarge->Location = Point(20, 80);

        grpPizzaSize->Controls->Add(radSmall);
        grpPizzaSize->Controls->Add(radMedium);
        grpPizzaSize->Controls->Add(radLarge);

        Controls->Add(grpPizzaSize);
    }
};

[STAThread]
int APIENTRY WinMain(HINSTANCE hInstance,
		     HINSTANCE hPrevInstance,
		     LPSTR lpCmdLine,
		     int nCmdShow)
{
    Application::Run(gcnew CExercise);

    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:

void InitializeComponent()
{
        grpPizzaSize = gcnew GroupBox;
        grpPizzaSize->Text = "Pizza Size";
        grpPizzaSize->Size = System::Drawing::Size(160, 120);
        grpPizzaSize->Location = Point(20, 10);

        radSmall = gcnew RadioButton;
        radSmall->Text = "Small";
        radSmall->Location = Point(20, 20);

        radMedium = gcnew RadioButton;
        radMedium->Text = "Medium";
        radMedium->Location = Point(20, 50);

        radLarge = gcnew RadioButton;
        radLarge->Text = "Large";
        radLarge->Location = Point(20, 80);

        grpPizzaSize->Controls->Add(radSmall);
        grpPizzaSize->Controls->Add(radMedium);
        grpPizzaSize->Controls->Add(radLarge);

        Controls->Add(grpPizzaSize);
    }
}

This would produce:

ApplicationPractical Learning: Introducing Radio Buttons

The application we are going to create is used to calculate the amount owed on a loan using the following formula:

Compound Interest Formula P = Principal
r = Annual (Interest) Rate
m = Number of Compounding Periods per Year
n = Total Number of Compounding Periods
A = Amount Earned After n periods
  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New Project
  3. In the middle list, click Windows Forms Application
  4. Change the Name to CompoundInterest1
  5. Design the form as followed:
     
    Compound Interest - Form Design
    Control Name Text Additional Properties
    GroupBox GroupBox   Loan Setup  
    Label Label   Principal:  
    TextBox TextBox txtPrincipal 0.00 TextAlign: Right
    Label Label   Interest Rate:  
    TextBox TextBox txtInterestRate 8.25 TextAlign: Right
    Label Label   %  
    Label Label   Number of Periods:  
    TextBox TextBox txtPeriods 1 TextAlign: Text
    Label Label   years  
    GroupBox GroupBox   Compound Frequency  
    RadioButton RadioButton rdoMonthly Monthly  
    RadioButton RadioButton rdoQuarterly Quarterly  
    RadioButton RadioButton rdoSemiannually Semiannually  
    RadioButton RadioButton rdoAnnually Annually  
    GroupBox GroupBox   Results  
    Label Label   Interest Earned:  
    TextBox TextBox txtInterestEarned 0.00 TextAlign: Right
    ReadOnly: True
    Label Label   Future Value:  
    TextBox TextBox txtFutureValue 0.00 TextAlign: Right
    ReadOnly: True
    Button Button btnCalculate Calculate  
    Button Button btnClose Close  
  6. On the form, double-click the Close button and implement its OnClick() event as follows:
    System::Void btnClose_Click(System::Object^  sender, System::EventArgs^  e)
    {
    	Close();
    }
  7. To test the application, press F5
  8. Close the form and return to your programming environment

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:

void InitializeComponent()
{
        grpPizzaSize = gcnew GroupBox;
        grpPizzaSize->Text = "Pizza Size";
        grpPizzaSize->Size = System::Drawing::Size(160, 120);
        grpPizzaSize->Location = Point(20, 10);

        radSmall = gcnew RadioButton;
        radSmall->Text = "Small";
        radSmall->Location = Point(20, 20);

        radMedium = gcnew RadioButton;
        radMedium->Text = "Medium";
        radMedium->Location = Point(20, 50);

        radLarge = gcnew RadioButton;
        radLarge->Text = "Large";
        radLarge->Location = Point(20, 80);

        grpPizzaSize->Controls->Add(radSmall);
        grpPizzaSize->Controls->Add(radMedium);
        grpPizzaSize->Controls->Add(radLarge);

        Controls->Add(grpPizzaSize);

	radMedium->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:

System::Void rdoSmall_CheckedChanged(Object ^ sender, EventArgs ^ e)
{
        txtPizzaPrice->Text = "$8.75";
}

ApplicationPractical Learning: Using Radio Buttons

  1. Return to the form.
    On the form, click Monthly
  2. In the Properties window, double-click Checked to set its value to True
  3. On the form, double-click the Calculate button and implement its Click() event as follows:
    System::Void btnCalculate_Click(Object ^ sender, EventArgs ^ e)
    {
        double principal = 0.00,
               interestRate = 0.00,
               interestEarned = 0.00;
        double futureValue = 0.00,
               ratePerPeriod = 0.00,
               periods = 0;
        int compoundType = 0;
    
        // Retrieve the value of the principal
        principal = double::Parse(txtPrincipal->Text);
    
        // Retrieve the interest rate
        interestRate = double::Parse(txtInterestRate->Text) / 100;
    
        // Find out what radio button was clicked
        // to apply the compound frequency
        if( rdoMonthly->Checked )
            compoundType = 12;
        else if( rdoQuarterly->Checked )
            compoundType = 4;
        else if( rdoSemiannually->Checked )
            compoundType = 2;
        else
            compoundType = 1;
    
        // Get the number of periods
        periods = double::Parse(txtPeriods->Text);
    
        // These values will make the calculation easier to read
        double i = interestRate / compoundType;
        double n = compoundType * periods;
    
        // Perform the necessary calculations
        ratePerPeriod = interestRate / periods;
        futureValue = principal * Math::Pow(1 + i, n);
        interestEarned = futureValue - principal;
    
        // Display the values in the appropriate text boxes
        txtInterestEarned->Text = interestEarned.ToString("C");
        txtFutureValue->Text = futureValue.ToString("C");
    }
  4. Test the application
     
    Compound Interest - Results
  5. After using it, close the form and return to your programming environment

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:

void InitializeComponent()
{
        grpPizzaSize = gcnew GroupBox;
        grpPizzaSize->Text = "Pizza Size";
        grpPizzaSize->Size = System::Drawing::Size(160, 120);
        grpPizzaSize->Location = Point(20, 10);

        radSmall = gcnew RadioButton;
        radSmall->Text = "Small";
        radSmall->CheckAlign = ContentAlignment::TopCenter;
        radSmall->Location = Point(20, 20);

        radMedium = gcnew RadioButton;
        radMedium->Text = "Medium";
        radMedium->CheckAlign = ContentAlignment::TopCenter;
        radMedium->Location = Point(20, 50);

        radLarge = gcnew RadioButton;
        radLarge->Text = "Large";
        radLarge->CheckAlign = ContentAlignment::TopCenter;
        radLarge->Location = 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:

void InitializeComponent()
{
        grpPizzaSize = gcnew GroupBox;
        grpPizzaSize->Text = "Pizza Size";
        grpPizzaSize->Size = System::Drawing::Size(150, 120);
        grpPizzaSize->Location = Point(20, 10);

        radSmall = gcnew RadioButton;
        radSmall->Appearance = Appearance::Button;
        radSmall->Location = Point(20, 20);

        radMedium = gcnew RadioButton;
        radMedium->Appearance = Appearance::Button;
        radMedium->Location = Point(20, 50);

        radLarge = gcnew RadioButton;
        radLarge->Appearance = Appearance::Button;
        radLarge->Location = 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:

void InitializeComponent()
{
        grpPizzaSize = gcnew GroupBox;
        grpPizzaSize->Text = "Pizza Size";
        grpPizzaSize->Size = System::Drawing::Size(150, 120);
        grpPizzaSize->Location = Point(20, 10);

        radSmall = gcnew RadioButton;
        radSmall->Text = "Small";
        radSmall->Appearance = Appearance::Button;
        radSmall->TextAlign = ContentAlignment::MiddleCenter;
        radSmall->CheckAlign = ContentAlignment::MiddleCenter;
        radSmall->Location = Point(20, 20);

        radMedium = gcnew RadioButton;
        radMedium->Text = "Medium";
        radMedium->Appearance = Appearance::Button;
        radMedium->TextAlign = ContentAlignment::MiddleCenter;
        radMedium->CheckAlign = ContentAlignment::MiddleCenter;
        radMedium->Location = Point(20, 50);

        radLarge = gcnew RadioButton;
        radLarge->Text = "Large";
        radLarge->Appearance = Appearance::Button;
        radLarge->TextAlign = ContentAlignment::MiddleCenter;
        radLarge->CheckAlign = ContentAlignment::MiddleCenter;
        radLarge->Location = 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.

 
 
 

ApplicationPractical Learning: Using the Appearance of a Radio Button

  1. To create a new application, on the main menu, click File -> New Project...
  2. In the middle list, make sure Window Forms Application is selected. Set the Name to ElementaryOperations1
  3. In the Solution Explorer, right-click Form1.h and click Rename
  4. Set the name to ElementaryOperations.h
  5. Design the form as follows:
     
    Elementary Addition
    Control Text Name TextAlign Font Additional Properties
    Label Select Your Level        
    GroupBox          
    RadioButton Level 1 rdoLevel1 MiddleCenter Microsoft Sans Serif, 12pt, style=Bold Appearance: Button
    Checked: TRue
    RadioButton Level 2 rdoLevel2 MiddleCenter Microsoft Sans Serif, 12pt, style=Bold Appearance: Button
    RadioButton Level 3 rdoLevel3 MiddleCenter Microsoft Sans Serif, 12pt, style=Bold Appearance: Button
    RadioButton Level 4 rdoLevel4 MiddleCenter Microsoft Sans Serif, 12pt, style=Bold Appearance: Button
    Label Select the OPeration        
    GroupBox          
    RadioButton Addition rdoAddition MiddleCenter Microsoft Sans Serif, 12pt, style=Bold Appearance: Button
    Checked: TRue
    RadioButton Subtraction rdoSubtraction MiddleCenter Microsoft Sans Serif, 12pt, style=Bold Appearance: Button
    RadioButton Multiplication rdoMultiplication MiddleCenter Microsoft Sans Serif, 12pt, style=Bold Appearance: Button
    RadioButton Division rdoDivision MiddleCenter Microsoft Sans Serif, 12pt, style=Bold Appearance: Button
    Label 000 lblOperand1 MiddleRight Microsoft Sans Serif, 54pt  
    Button New Operation btnNewOperation   Microsoft Sans Serif, 20pt  
    Label + lblOperation MiddleRight Microsoft Sans Serif, 54pt  
    Label 00 lblOperand2 MiddleRight Microsoft Sans Serif, 54pt  
    Panel         Size: 317, 10
    Label =   Center Microsoft Sans Serif, 54pt AutoSize: True
    ForeColor: Green
    TextBox 000 txtResult Right Microsoft Sans Serif, 54pt, style=Bold  
    Button Check Result btnCheckResult      
  6. Double-click the New Operation button and implement its event as follows:
    System::Void btnNewOPeration_Click(Object ^ sender, EventArgs ^ e)
    {
                int Number1 = 0;
                int Number2 = 0;
                Random ^ rndNumber = gcnew Random;
    
                // If the user clicked the Level 1 button,
                // the operation will be performed on numbers from 1 to 9
                if( rdoLevel1->Checked == true)
                {
                    Number1 = rndNumber->Next(1, 10);
                    Number2 = rndNumber->Next(1, 10);
                }
                else if( rdoLevel2->Checked == true)
                {
                    // If the user clicked the Level 2 button,
                    // the operation will be performed on numbers from 10 to 19
                    Number1 = rndNumber->Next(10, 30);
                    Number2 = rndNumber->Next(10, 30);
                }
                else if( rdoLevel3->Checked == true)
                {
                    // If the user clicked the Level 3 button,
                    // the operation will be performed on numbers from 21 to 49
                    Number1 = rndNumber->Next(30, 50);
                    Number2 = rndNumber->Next(30, 50);
                }
                else if( rdoLevel4->Checked == true)
                {
                    // If the user clicked the Level 4 button,
                    // the operation will be performed on numbers from 51 to 99
                    Number1 = rndNumber->Next(50, 101);
                    Number2 = rndNumber->Next(50, 101);
                }
    
                // Display the numbers to the user
                lblOperand1->Text = Number1.ToString();
                lblOperand2->Text = Number2.ToString();
    
                // Just in case, empty the Result text box
                txtResult->Text = "";
                // Give focus to the Result text box
                txtResult->Focus();
    }
  7. Return to the form and click the Level 1 button
  8. Press and hold Shift
  9. On the form, click the Level 2, the Level 3, and the Level 4 buttons
  10. Release Shift
  11. In the Properties window, click Events and double-click Click 
  12. Implement the event as follows:
    System::Void rdoLevel1_Click(Object ^ sender, EventArgs ^ e)
    {
                btnNewOPeration_Click(sender, e);
    }
  13. Return to the form and click the Addition button
  14. In the Events section of the Properties window, double-click Click and implement the event as follows:
    System::Void rdoAddition_Click(Object ^ sender, EventArgs ^ e)
    {
                lblOperation->Text = "+";
    }
  15. Return to the form and click the Subtraction button
  16. In the Events section of the Properties window, double-click Click and implement the event as follows:
    System::Void rdoSubtraction_Click(Object ^ sender, EventArgs ^ e)
    {
                lblOperation->Text = "-";
    }
  17. Return to the form and click the Multiplication button
  18. In the Events section of the Properties window, double-click Click and implement the event as follows:
    System::Void rdoMultiplication_Click(Object ^ sender, EventArgs ^ e)
    {
                lblOperation->Text = "*";
    }
  19. Return to the form and click the Division button
  20. In the Events section of the Properties window, double-click Click and implement the event as follows:
    System::Void rdoDivision_Click(Object ^ sender, EventArgs ^ e)
    {
                lblOperation->Text = "/";
    }
  21. Return to the form and double-click the Check Result button
  22. Implement the event as follows:
    System::Void btnCheckResult_Click(Object ^ sender, EventArgs ^ e)
    {
        double Number1, Number2;
        double UserResult, OurResult;
        Random ^ RandomNumber = gcnew Random;
    
        // It is hard to perform a comparison on a division
        // So we will have to do some gymastic here to get something
        // We will use this variable to format the number 
        // to appear as 0.00
        // That will allow us to perform the comparision
        // on a decimal number with a precision of 2
        string strFixedResult;
        strFixedResult = "";
    
        array<String ^> ^  Congratulations = gcnew array<String ^> ^ { 
                "Right :) - WOW - Good Answer!",
                "Good Answer :) - You are Impressive", 
                "Right Answer :) - What a Good Job!", 
                "Good :) - You Are Greaaaaaaaaaaaat", 
                "Wonderful Answer :) - You Know It" 
                };
        array<String ^> ^  WrongAnswers = { 
                "Uhhhhhhhhhh - Bad Answer", 
                "Wrong - You will do better next time", 
                "Nop", 
                "Common - You can do Better Than That!",
                "No - You are probably getting tired" 
                };
    
        // Make sure the user provides a result
        if( txtResult->Text == "")
        {
            MessageBox::Show("You must provide a result before clicking the button");
            return;
        }
    
        // Use exception handling to get the result
        UserResult = double::Parse(txtResult->Text);
    
        Number1 = double::Parse(lblOperand1->Text);
        Number2 = double::Parse(lblOperand2->Text);
    
        // Get the user's answer
        if( rdoAddition->Checked == true)
        {
            OurResult = Number1 + Number2;
            // Format the result to appear with 2 decimal numbers
            strFixedResult = String::Format("{0:F}", Number1 + Number2);
        }
    
        if( rdoSubtraction->Checked == true)
        {
            OurResult = Number1 - Number2;
            strFixedResult = String::Format("{0:F}", Number1 - Number2);
        }
    
        if( rdoMultiplication->Checked == true)
        {
            OurResult = Number1 * Number2;
            strFixedResult = String::Format("{0:F}", Number1 * Number2);
        }
    
        if( rdoDivision->Checked == true)
        {
            OurResult = Number1 / Number2;
            strFixedResult = String::Format("{0:F}", Number1 / Number2);
        }
    
        // Check if the user's answer is the right one
        // Because of the division, we will format the result as 0.00
        // then perform the comparison
        if( strFixedResult == double::Parse(txtResult->Text).ToString("F"))
            MessageBox::Show(Congratulations[RandomNumber.Next(0, 4)],
                            "Elementary Operations",
                            MessageBoxButtons::OK, MessageBoxIcon::Question);
        else
        {
            MessageBox::Show(WrongAnswers[RandomNumber.Next(0, 4)],
                            "Elementary Operations",
                            MessageBoxButtons::OK, MessageBoxIcon.Information);
        }
    
        // After checking the user's answer, generate a new operation
        btnNewOPeration_Click(sender, e);
    }
  23. Execute the application and test it
     
  24. Close the form and return to your programming environment
 
 
   
 

Home Copyright © 2011 FunctionX, Inc. Home