Visual Basic 2017 Lesson 22: Working with Radio Buttons

We have learned how to use the checkbox control in the previous lesson. In this lesson, we shall learn how to write code for another control in visual basic 2017, the radio button.Though closely related to the check box control, the radio buttons operate differently from the check boxes. The difference is check boxes work independently and allow the user to select one or more items, radio buttons only allow the user to select one item out of a number of choices. It means radio buttons are mutually exclusive. Examples of the usage of radio buttons are survey questions related to gender, age, income and more of an individual.

Example 22.1

In this example, the user can only choose one T-shirt color. To design the interface, add three radio buttons and name them as RadioRed, RadioGreen and RadioYellow respectively. Besides that, add a button to confirm the chosen color and a label control to display the chosen color. Name the button as BtnConfirm and the label as LblDisplay. We use the If…Then…Else decisions making structure to construct the program. The state of the radio button is indicated by its checked property.

The Runtime Interface

Figure 22.1

Example 22.2

Although the user may only select one item at a time, he may make more than one selection if those items belong to different categories. For example, the user wishes to choose T-shirt size and color, he needs to select one color and one size, which means one selection in each category. In this case, we need to group the radio buttons together according to the categories. This is easily achieved in Visual Basic 2017 using the Groupbox control under the containers categories.

In the Visual Basic 2017 IDE, after inserting the Groupbox from the tool box into the form, you can proceed to insert the radio buttons into the Groupbox. Only the radio buttons inside the Groupbox are mutually exclusive, they are not mutually exclusive with the radio buttons outside the Groupbox. In this example, the user can select one color and one size of the T-shirt. To design the interface, insert two group boxes. In the first group box, add four radio buttons and name them as RadioXL, RadioL, RadioM and Radio S respectively. In the second group box, add three radio buttons and name them RadioRed, RadioBlue and RadioBeige respectively. Besides that, insert two label control to display the chosen size and color, name them LblSize and LblColor respectively. Finally, add a button and name it as BtnConfirm. In the Visual Basic 2017 code, we shall declare two variables, TSize to indicate the T-shirt size and TColor to indicate the T-shirt color.