Programming & Scripting Tutorials

Visual Basic: Radio Buttons and Checkboxes





Radio Buttons



Radio buttons are useful in all kinds of situations were the user needs to select one of a number of things.
Also like a lot of basics in visual basic its extremely easy to use, for example the following program gets the user to select a type of pizza, and then displays the selection:

    Dim Topping As String 'Global Variable "Topping"

    Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
        Topping = "Margarita"
    End Sub

    Private Sub RadioButton2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton2.CheckedChanged
        Topping = "Prosciutto"
    End Sub

    Private Sub RadioButton3_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton3.CheckedChanged
        Topping = "Hawaiian"
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Label2.Text = Topping
    End Sub

As you may have guessed this form has three radio buttons, a button and two labels.


Checkboxes



Checkboxes are a lot like radio buttons, however with checkboxes you can choose more than one option. They are used a lot like radio buttons in visual basic. Here is a program which simulates a very small simple shop checkout program:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        Const Laptop As Integer = 100
        Const Desktop As Integer = 500
        Const Speakers As Integer = 50
        Const USBStick As Integer = 5
        Const Monitor As Integer = 200
        Const Microphone As Integer = 150
        Dim sum As Integer

        If CheckBox1.Checked = True Then
            sum += Laptop
        End If

        If CheckBox2.Checked = True Then
            sum += Desktop
        End If

        If CheckBox3.Checked = True Then
            sum += USBStick
        End If
        If CheckBox4.Checked = True Then
            sum += Speakers
        End If

        If CheckBox5.Checked = True Then
            sum += Microphone
        End If

        If CheckBox6.Checked = True Then
            sum += Monitor
        End If
        Label8.Text = sum.ToString("c") 'The "c" makes it into money (currency)
    End Sub

This has eight labels (one for each product, one for the "Your order comes to:", and one for the total), six checkboxes, and one button.
Checkboxes are very powerful and are used in many applications for many different reasons.

This Visual Basic tutorial was written by


Back to Visual Basic

Advertisement: