Home

Button-Based Controls

 

Introduction to Command Buttons

 

Description

On a typical application, a button is an object that the user clicks to perform an action. To make this obvious, a button is a control surrounded by thick borders. Here is an example of a button on a form:

Button

Although a control is usually positioned on a form, there various other control containers that can hold a button. These include the toolbar or the status bar, and the other containers we have used so far.

To indicate what it is used for, a button displays some text as its caption. A button can also display a picture instead. Another button can display both a string and a picture. When you create a button, you will decide what it should display and how it should behave.

Practical LearningPractical Learning: Introducing Buttons

  1. Start Microsoft Visual Basic and create a Windows Application named Algebra1
  2. In the Solution Explorer, right-click Form1.vb and click Rename
  3. Type Exercise.vb and press Enter
  4. Click the body of the form to make sure it is selected.
    In the Properties window, change the following characteristics
    FormBorderStyle: FixedDialog
    Text: Factorial, Permutation, and Combination
    Size: 304, 235
    StartPosition: CenterScreen
    MaximizeBox: False
    MinimizeBox: False
  5. In the Containers section of the Toolbox, click TabControl and click the form
  6. On the form, right-click the right side of tabPage2 and click Add Page
  7. Based on what we learned in Lesson 19, design the form as follows:
     
    Control Text Name Additional Properties
    TabControl   tclAlgebra HotTrack: True
    Location: 12, 12
    Size: 304, 235
    TabPage Factorial tabFactorial  
    Label Number:   Location: 22, 21
    TextBox   txtNumber TextAlign: Right
    Location: 88, 18
    Size: 50, 20
    Label Result:   Location: 22, 56
    TextBox   txtFactorial TextAlign: Right
    Location: 88, 54
    Size: 140, 20
    Control Text Name Location Size
    TabPage Permutation tabPermutation    
    Label n:   22, 21  
    TextBox   txtPermutationN 88, 18 50, 20
    Label r:   22, 56  
    TextBox   txtPermutationR 88, 54 50, 20
    Label P(n, r):   22, 92  
    TextBox   txtPermutation 88, 90 140, 20
    Control Text Name Location Size
    TabPage Combination tabCombination    
    Label n:   22, 21  
    TextBox   txtCombinationN 88, 18 50, 20
    Label r:   22, 56  
    TextBox   txtCombinationR 88, 54 50, 20
    Label C(n, r):   22, 92  
    TextBox   txtCombination 88, 90 140, 20
  8. Right-click the form and click View Code
  9. Create the following functions:
     
    Public Class Exercise
        Private Function Factorial(ByVal x As Long) As Long
            If x <= 1 Then
                Return 1
            Else
                Factorial = x * Factorial(x - 1)
            End If
        End Function
    
        Private Function Permutation(ByVal n As Long, ByVal r As Long) As Long
            If r = 0 Then Permutation = 0
            If n = 0 Then Permutation = 0
            If (r >= 0) And (r <= n) Then
                Permutation = Factorial(n) / Factorial(n - r)
            Else
                Permutation = 0
            End If
        End Function
    
        Private Function Combinatorial(ByVal a As Long, ByVal b As Long) As Long
            If a <= 1 Then Combinatorial = 1
    
            Combinatorial = Factorial(a) / (Factorial(b) * Factorial(a - b))
        End Function
    End Class
  10. Click the Exercise.vb [Design] tab

Creating a Button

To support the buttons of an application, the .NET Framework provides an abstract class named ButtonBase. The regular button of Microsoft Windows is implemented by the Button class. At design time, to add a button to your project, from the Common Controls section of the Toolbox, you can click the Button and click the form or another container.

To programmatically create a button, you can declare a variable of type Button and use the new operator to allocate memory for it. Here is an example:

Imports System.Drawing
Imports System.Windows.Forms

Module Exercise

    Public Class Starter
        Inherits Form

        Private btnResume As Button


        Dim components As System.ComponentModel.Container

        Public Sub New()
            InitializeComponent()
        End Sub

        Public Sub InitializeComponent()

            btnResume = New Button()

            Controls.Add(btnResume)

        End Sub

    End Class

    Function Main() As Integer

        Dim frmStart As Starter = New Starter

        Application.Run(frmStart)

        Return 0
    End Function

End Module

Practical Learning Practical Learning: Creating Buttons

  1. In the combo box on top of the Properties window, select tabFactorial
  2. From the Common Controls section of the Toolbox, click Button and click on the right side of the top text box

The Characteristics of a Button

 

The Caption of a Button

For a user, the most important aspects of a button are the message it displays and the action it performs. The text the button displays allows the user to know what the button is used for. This is represented by the Text property. The most popular strings that the buttons display are OK and Cancel. The OK caption is set for a form or a dialog box that informs the user of an error, an intermediary situation, or an acknowledgement of an action that was performed on the dialog that hosts the button. The Cancel caption is useful on a button whose main parent (the form or the dialog box) would ask a question or request a follow-up action from the user. Whenever a dialog box allows the user to dismiss it without continuing the action, you should provide a button with a Cancel caption.

After adding a button to a form (by design or with code), you can change its caption with code by assigning the desired string to the Text property. For example, you can change the caption of a button as follows:

button1.Text = "Let it Go!";

After specifying the Text of a button, by default, it's positioned in the middle center of the button:

Button

The position of the text of a button is controlled through the TextAlign property which is a value of the ContentAlignment enumerator. The possible values are:

TopLeft TopCenter TopRight
TopLeft TopCenter TopRight
MiddleLeft MiddleCenter MiddleRight
MiddleLeft MiddleCenter MiddleRight
BottomLeft BottomCenter BottomRight
BottomLeft BottomCenter BottomRight

Here is an example:

Public Sub InitializeComponent()

            btnResume = New Button()
            btnResume.Text = "Resume"
            btnResume.Location = New Point(32, 20)
            btnResume.Size = New System.Drawing.Size(120, 48)

            btnResume.TextAlign = ContentAlignment.BottomCenter

            Controls.Add(btnResume)

End Sub

Button

Practical Learning Practical Learning: Using the Buttons

  1. Access each tab page and add a button to it
  2. Add a button to the form under the tab control
  3. Complete the design of the form as follows:
     
    Control Text Name
    Button Calculate btnCalcFactorial
    Button Close btnClose
    Control Text Name
    Button Calculate btnCalcPermutation
    Control Text Name
    Button Calculate btnCalcCombination
  4. Right-click the form and click View Code
  5. In the Class Name combo box, select btnCalcFactorial
  6. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnCalcFactorial_Click(ByVal sender As Object, _
                                           ByVal e As System.EventArgs) _
                                           Handles btnCalcFactorial.Click
            Dim number As Long
            Dim Result As Long
    
            Try
                number = CLng(txtFactNumber.Text)
                Result = Factorial(number)
                txtFactorial.Text = Result.ToString()
            Catch ex As Exception
                MsgBox("Invalid Number")
            End Try
    End Sub
  7. In the Class Name combo box, select btnCalcPermutation
  8. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnCalcPermutation_Click(ByVal sender As Object, _
                                             ByVal e As System.EventArgs) _
                                             Handles btnCalcPermutation.Click
            Dim n As Long
            Dim r As Long
            Dim Result As Long
    
            Try
                n = CLng(txtPermutationN.Text)
            Catch ex As Exception
                MsgBox("Invalid Number")
            End Try
    
            Try
                r = CLng(txtPermutationR.Text)
                Result = Permutation(n, r)
                txtPermutation.Text = Result.ToString()
            Catch ex As Exception
                MsgBox("Invalid Number")
            End Try
    End Sub
  9. In the Class Name combo box, select btnCalcCombination
  10. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnCalcCombination_Click(ByVal sender As Object, _
                                             ByVal e As System.EventArgs) _
                                             Handles btnCalcCombination.Click
            Dim n As Long
            Dim r As Long
            Dim Result As Long
    
            Try
                n = CLng(txtCombinationN.Text)
            Catch ex As Exception
                MsgBox("Invalid Number")
            End Try
    
            Try
                r = CLng(txtCombinationR.Text)
                Result = Combinatorial(n, r)
                txtCombination.Text = Result.ToString()
            Catch ex As Exception
                MsgBox("Invalid Number")
            End Try
    End Sub
  11. In the Class Name combo box, select btnClose
  12. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            End
    End Sub
  13. Execute the application to test the calculations
     
    Factorial
    Permutation
    Combinatorial
  14. Close the form and return to your programming environment

The Image on a Button

Besides, or instead, of a caption, a button can display a picture on top. If you want a button to display a bitmap, you should first create, design, or have a picture. Then, in the Properties window, use the Image field to select a bitmap or an icon. You can also programmatically assign an Image object to the Image property. Here is an example:

Public Sub InitializeComponent()

            btnResume = New Button()
            btnResume.Text = "Resume"
            btnResume.Location = New Point(32, 20)
            btnResume.Size = New System.Drawing.Size(120, 48)

            btnResume.Image = Image.FromFile("E:\Programs\neutral.gif")

            Controls.Add(btnResume)

End Sub

This would produce:

By default, both the caption and the image display ion the middle-center of the button. To make them distinct and allow the user to see both, you can design a bitmap that has both and assign that bitmap as the image of the button. Alternatively, you can use a separate string and a separate picture. Fortunately, each can have its own alignment. We already saw how to control the alignment of the caption.

Besides displaying an image, the Button class is equipped with the ImageAlign property that allows you to specify the alignment of the image. The ImageAlign property is inherited from the ButtonBase class. The ButtonBase.ImageAlign property is based on the ContentAlignment enumeration that we are already familiar with. Here is an example:

Public Sub InitializeComponent()

            btnResume = New Button()
            btnResume.Text = "Resume"
            btnResume.Location = New Point(32, 20)
            btnResume.Size = New System.Drawing.Size(120, 48)

            btnResume.TextAlign = ContentAlignment.BottomCenter
            btnResume.Image = Image.FromFile("E:\Programs\neutral.gif")
            btnResume.ImageAlign = ContentAlignment.TopCenter

            Controls.Add(btnResume)

End Sub

This would produce:

Instead of using the Image property, you can first create an image list and add some pictures to it. Then, using the ImageList property, assign it to the button. Use the ImageIndex property to specify what picture would be displayed on the button.

Practical Learning Practical Learning: Using a Picture on a Button

  1. To start a new application, on the main menu, click File -> New -> Project
  2. In the Templates list, click Windows Application and change the Name to SimpleInterest1
  3. Click OK
  4. On the main menu, click Project -> Add New Item...
  5. In the Templates list, click Icon File
  6. Change the Name to Calculator and click OK
  7. Right-click a white area in the icon designer -> Delete Image Type
  8. Right-click the icon designer again -> Current Icon Image Types -> 16x16, 16 colors
  9. Design the icon as follows:
     
    Calculator
  10. On the main menu, click Project -> Add New Item...
  11. In the Templates list, click Icon File and change the Name to exit
  12. Click Add
  13. Right-click a white area in the icon designer -> Delete Image Type
  14. Right-click the icon designer again -> Current Icon Image Types -> 16x16, 16 colors
  15. Design the icon as follows:
     
    Exit
  16. Save and close the icon window
  17. In the Solution Explorer, right-click Form1.vb and click Rename
  18. Type SimpleInterest.vb and press Enter twice
  19. Design the form as follows:
     
    Control Text Name TextAlign
    GroupBox Loan Preparation    
    Label Principal    
    TextBox 0.00 txtPrincipal Right
    Label Interest Rate:    
    TextBox 0.00 txtInterestRate Right
    Label %    
    Label Periods:    
    TextBox 1 txtPeriods Right
    Label Months    
    Button Calculate btnCalculate  
    Button Close btnClose  
    GroupBox Results    
    Label Interest Earned:    
    TextBox 0.00 txtInterestEarned Right
    Label Future Value    
    TextBox 0.00 txtFutureValue Right
  20. On the form, click the Calculate button
  21. In the Properties window, click Image and click its ellipsis button
  22. In the Select Resource dialog box, click Import
  23. In the Files of Type box, select All Files
  24. Locate the folder of the current project, select Calculator.ico and click Open
  25. On the Select Resource dialog box, click OK
  26. Change the following properties of the Calculate button:
    ImageAlign: TopCenter
    TextAlign: BottomCenter
  27. On the form, click the Calculate button
  28. In the Properties window, click Image and click its ellipsis button
  29. In the Select Resource dialog box, click Import
  30. In the Files of Type box, select All Files
  31. Locate the folder of the current project, select exit.ico and click Open
  32. On the Select Resource dialog box, click OK
  33. Change the following properties of the Close button:
    ImageAlign: TopCenter
    TextAlign: BottomCenter
     
    Simple Interest
  34. On the form, double-click the Calculate button and implement its Click event as follows:
     
    Private Sub btnCalculate_Click(ByVal sender As System.Object, _
                                       ByVal e As System.EventArgs) _
                                       Handles btnCalculate.Click
            Dim Principal As Double
            Dim InterestRate As Double
            Dim InterestEarned As Double
            Dim FutureValue As Double
            Dim Periods As Double
            Dim I As Double
            Dim p As Double
    
            Try
                Principal = CDbl(txtPrincipal.Text)
            Catch ex As Exception
                MsgBox("The value you entered for the " & _
                                                "principal is not valid")
            End Try
    
            Try
                InterestRate = CDbl(txtInterestRate.Text)
            Catch ex As Exception
                MsgBox("Wrong Value: The interest rate must " & _
                                                "be a value between 0 and 100")
            End Try
    
            Try
                Periods = CDbl(txtPeriods.Text)
            Catch ex As Exception
                MsgBox("You entered an invalid value for the periods")
            End Try
    
            i = InterestRate / 100
            p = Periods / 12
            InterestEarned = Principal * i * p
            FutureValue = Principal + InterestEarned
    
            txtInterestEarned.Text = InterestEarned.ToString("C")
            txtFutureValue.Text = FutureValue.ToString("C")
    End Sub
  35. In the Class Name combo box, select btnClose
  36. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            End
    End Sub
  37. Execute the application and test the calculation
     
    Interest Rate
  38. Close the form and return to your programming environment

The Flat Style of a Button

A regular button displays with raised borders as originally set by the operating system. To give your button a fancy look and behavior, you can use the FlatStyle property. The FlatStyle property is based on an enumeration of the same name. It provides 4 values that are:

  • Flat: The button appears flat. When the mouse is over it, it becomes highlighted

  • Popup: The button appears flat. When the mouse is over it, the borders of the button are raised

  • Standard: The button appears and behave like all regular buttons you have seen

  • System: The appearance of the button depends on the operating system

Obviously the most important and the most intuitive event of a button occurs when clicked. This event is of type EventArgs, which indicates that it doesn't provide nor does it need any formal details about what is going on. To launch this event, you can double-click the button on the form. To create this event programmatically, first implement the method that would carry its assignment, then increment-add (with the += operator) it to the Click property of the button by assigning it the EventHandler constructor.

The Result of a Dialog Box

After the user has used a form or dialog box, to close it, the user would click a button. When the user does this, you must find out what button was clicked. Although there are various ways you can get this information, to assist you, the .NET Framework provides a convenient mechanism through an enumeration named DialogResult.

When creating a form or a dialog box, after adding a button, in the Properties window, click DialogResult and select on the values:

Except for None, by default, it does not matter what value you select but, you should follow Windows standard to select the right value.

After specifying the returned value of a button, access the properties of the form or dialog box:

  • If you had selected OK as the DialogResult value of a button, you should select the name of that button for the AcceptButton property of the form
  • If you had selected Cancel as the DialogResult value of a button, you should select the name of that button for the CancelButton property of the form

After configuring the DialogResult of the button(s), when the user clicks one of the buttons to close the form or dialog box, you can get the value of the Form.ShowDialog() method which returns one of the values of the DialogResult enumeration.

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

Imports System.Drawing
Imports System.Windows.Forms

Module Exercise

    Public Class Starter
        Inherits Form

        Private radSmall As RadioButton
        Private radMedium As RadioButton
        Private radLarge As RadioButton
        Private grpPizzaSize As GroupBox

        Dim components As System.ComponentModel.Container

        Public Sub New()
            InitializeComponent()
        End Sub

        Public Sub 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)

        End Sub

    End Class

    Function Main() As Integer

        Dim frmStart As Starter = New Starter

        Application.Run(frmStart)

        Return 0
    End Function

End Module

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:

Public Sub InitializeComponent()

            grpPizzaSize = New GroupBox()
            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)

        End Sub

This would produce:

Practical Learning Practical 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 a new Windows Application named CompoundInterest1
  2. In the Solution Explorer, right-click Form1.vb and click Rename
  3. Type CompoundInterest.vb and press Enter
  4. 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    
    RadioButton RadioButton rdoQuarterly    
    RadioButton RadioButton rdoSemiannually    
    RadioButton RadioButton rdoAnnually    
    GroupBox GroupBox   Results  
    Label Label   Interest Earned:  
    TextBox TextBox txtInterestEarned 0.00 TextAlign: Right
    ReadOnly: True
    Label Label   Amount Earned:  
    TextBox TextBox txtFutureValue 0.00 TextAlign: Right
    ReadOnly: True
    Button Button btnCalculate Calculate  
    Button Button btnClose Close  
  5. On the form, double-click the Close button and implement the event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            End
    End Sub
  6. Return to the form

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:

Public Sub InitializeComponent()

            grpPizzaSize = New GroupBox()
            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)

            radMedium.Checked = True
End Sub

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.

Practical Learning Practical Learning: Using Radio Buttons

  1. 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:
     
    Private Sub btnCalculate_Click(ByVal sender As System.Object, _
                                       ByVal e As System.EventArgs) _
                                       Handles btnCalculate.Click
            Dim Principal As Double
            Dim InterestRate As Double
            Dim InterestEarned As Double
            Dim FutureValue As Double
            Dim RatePerPeriod As Double
            Dim Periods As Double
            Dim CompoundType As Integer
    
            ' Retrieve the value of the principal
            Try
                Principal = CDbl(txtPrincipal.Text)
            Catch ex As Exception
                MsgBox("The value you entered for the principal " & _
                       "is not valid" & vbCrLf & "Please try again")
            End Try
    
            ' Retrieve the interest rate
            Try
                InterestRate = CDbl(txtInterestRate.Text) / 100
            Catch ex As Exception
                MsgBox("The value you entered for the interest rate " & _
                       "is not valid" & vbCrLf & "Please try again")
            End Try
    
            ' Find out what radio button was clicked to apply the compound frequency
            If rdoMonthly.Checked Then
                CompoundType = 12
            ElseIf rdoQuarterly.Checked Then
                CompoundType = 4
            ElseIf rdoSemiannually.Checked Then
                CompoundType = 2
            Else
                CompoundType = 1
            End If
    
            ' Get the number of periods
            Try
                Periods = CDbl(txtPeriods.Text)
            Catch ex As Exception
                MsgBox("The value you entered for the number of periods " & _
                       "is not valid" & vbCrLf & "Please try again")
            End Try
    
            ' These values will make the calculation easier to read
            Dim i As Double = InterestRate / CompoundType
            Dim n As Double = 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 = FormatCurrency(InterestEarned)
            txtFutureValue.Text = FormatCurrency(FutureValue)
    End Sub
  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:

Public Sub InitializeComponent()

            grpPizzaSize = New GroupBox()
            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)

End Sub

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:

Public Sub 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)

End Sub

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:

Public Sub 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)

End Sub

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.

Practical LearningPractical Learning: Using the Appearance of a Radio Button

  1. Create a new Window Application named ElementaryOperations1
  2. In the Solution Explorer, right-click Form1.vb and click Rename
  3. Set the name to Exercise.vb
  4. 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      
  5. Double-click the New Operation button and implement its event as follows:
     
    Private Sub btnNewOPeration_Click(ByVal sender As System.Object, _
                                          ByVal e As System.EventArgs) _
                                          Handles btnNewOPeration.Click
            Dim Number1 As Integer
            Dim Number2 As Integer
            Dim rndNumber As Random
    
            rndNumber = New Random
    
            ' If the user clicked the Level 1 button,
            ' the operation will be performed on numbers from 1 to 9
            If rdoLevel1.Checked = True Then
                Number1 = rndNumber.Next(1, 10)
                Number2 = rndNumber.Next(1, 10)
            ElseIf rdoLevel2.Checked = True Then
                ' 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)
            ElseIf rdoLevel3.Checked = True Then
                ' 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)
            ElseIf rdoLevel4.Checked = True Then
                ' 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)
            End If
    
            ' Display the numbers to the user
            lblOperand1.Text = CStr(Number1)
            lblOperand2.Text = CStr(Number2)
    
            ' Just in case, empty the Result text box
            txtResult.Text = ""
            ' Give focus to the Result text box
            txtResult.Focus()
    End Sub
  6. In the Class Name combo box, select rdoLevel1
  7. In the Method Name combo box, select Click and implement its event as follows:
     
    Private Sub rdoLevel1_Click(ByVal sender As Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles rdoLevel1.Click
            ' When the user clicks the Level 1 button,
            ' behave as if the user had click the New Operation button
            ' That is, behave as if the user wants a new operation
            btnNewOPeration_Click(sender, e)
    End Sub
  8. In the Class Name combo box, select rdoLevel2
  9. In the Method Name combo box, select Click and implement its event as follows:
     
    Private Sub rdoLevel2_Click(ByVal sender As Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles rdoLevel1.Click
            btnNewOPeration_Click(sender, e)
    End Sub
  10. In the Class Name combo box, select rdoLevel3
  11. In the Method Name combo box, select Click and implement its event as follows:
     
    Private Sub rdoLevel3_Click(ByVal sender As Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles rdoLevel1.Click
            btnNewOPeration_Click(sender, e)
    End Sub
  12. In the Class Name combo box, select rdoLevel4
  13. In the Method Name combo box, select Click and implement its event as follows:
     
    Private Sub rdoLevel4_Click(ByVal sender As Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles rdoLevel1.Click
            btnNewOPeration_Click(sender, e)
    End Sub
  14. In the Class Name combo box, select rdoAddition
  15. In the Method Name combo box, select Click and implement its event as follows:
     
    Private Sub rdoAddition_Click(ByVal sender As Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles rdoAddition.Click
            lblOperation.Text = "+"
    End Sub
  16. In the Class Name combo box, select rdoSubtraction
  17. In the Method Name combo box, select Click and implement its event as follows:
     
    Private Sub rdoSubtraction_Click(ByVal sender As Object, _
                                         ByVal e As System.EventArgs) _
                                         Handles rdoSubtraction.Click
            lblOperation.Text = "-"
    End Sub
  18. In the Class Name combo box, select rdoMultiplication
  19. In the Method Name combo box, select Click and implement its event as follows:
     
    Private Sub rdoMultiplication_Click(ByVal sender As Object, _
                                            ByVal e As System.EventArgs) _
                                            Handles rdoMultiplication.Click
            lblOperation.Text = "*"
    End Sub
  20. In the Class Name combo box, select rdoDivision
  21. In the Method Name combo box, select Click and implement its event as follows:
     
    Private Sub rdoDivision_Click(ByVal sender As Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles rdoDivision.Click
            lblOperation.Text = "/"
    End Sub
  22. In the Class Name combo box, select btnCheckResult
  23. In the Method Name combo box, select Click and implement its event as follows:
     
    Private Sub btnCheckResult_Click(ByVal sender As Object, _
                                         ByVal e As System.EventArgs) _
                                         Handles btnCheckResult.Click
            Dim Number1 As Double
            Dim Number2 As Double
            Dim UserResult As Double
            Dim OurResult As Double
            Dim RandomNumber As Random = New 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
            Dim strFixedResult As String
            strFixedResult = ""
    
            Dim Congratulations As 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" _
                }
            Dim WrongAnswers As String() = { _
                "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 = "" Then
                MsgBox("You must provide a result before clicking the button")
                Exit Sub
            End If
    
            ' Use exception handling to get the result
            Try
                UserResult = CDbl(txtResult.Text)
    
                Number1 = CDbl(lblOperand1.Text)
                Number2 = CDbl(lblOperand2.Text)
    
                ' Get the user's answer
                If rdoAddition.Checked = True Then
                    OurResult = Number1 + Number2
                    ' Format the result to appear with 2 decimal numbers
                    strFixedResult = String.Format("{0:F}", Number1 + Number2)
                End If
    
                If rdoSubtraction.Checked = True Then
                    OurResult = Number1 - Number2
                    strFixedResult = String.Format("{0:F}", Number1 - Number2)
                End If
    
                If rdoMultiplication.Checked = True Then
                    OurResult = Number1 * Number2
                    strFixedResult = String.Format("{0:F}", Number1 * Number2)
                End If
    
                If rdoDivision.Checked = True Then
                    OurResult = Number1 / Number2
                    strFixedResult = String.Format("{0:F}", Number1 / Number2)
                End If
    
                ' 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 = CDbl(txtResult.Text).ToString("F") Then
                    MsgBox(Congratulations(RandomNumber.Next(0, 4)), _
                            MsgBoxStyle.OkOnly Or MsgBoxStyle.Question, _
                            "Elementary Operations")
                Else
                    MsgBox(WrongAnswers(RandomNumber.Next(0, 4)), _
                            MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _
                            "Elementary Operations")
                End If
    
                ' After checking the user's answer, generate a new operation
                btnNewOPeration_Click(sender, e)
            Catch ex As Exception
                MsgBox("Invalid Numeric Value.")
            End Try
    End Sub
  24. Execute the application and test it
     
  25. Close the form and return to your programming environment

 

 

Previous Copyright 2008-2009, yevol.com Next