Procedures in Visual Basic


Start a new application and name it Area. We are going to use scroll bars to select the width and length of a room. When a scroll bar changes, we will display the value in a label, then calculate the area from the values of the two scroll bars and display it. Later, we may want to add another scroll bar to select the cost of carpeting and calculate the cost to carpet the room.

Instead of writing all of the calculations for each scroll bar, we will use a general procedure all it from each of the scroll bar scroll events. One important reason to not repeat code is because it can lead to errors when the code needs to be updated.

Build the form as shown in the illustration,

Add labels Label LblInstructions (text="Select the length and Width:", LblWidth (text = Width: 1)

Add a horizontal scroll bar Hsb HsbWidth: LargeChange=1, Minimum=1, and Value=1.

Copy LblWidth and HsbWidth (Drag to select both, then Ctrl+C) and paste (Ctrl+V)

Drag into place, then change the names to LblLength and HsbLength.
Copy and paste one of the labels, then change name to LblArea and drag into position.

Write the code as shown below:

'Programmer: Janet Joy
'Calculate area when either width or length changes
Public Class Form1
    Private Sub HsbWidth_Scroll(sender As Object, e As ScrollEventArgs) Handles HsbWidth.Scroll
        'Show width and calculate area
        LblWidth.Text = "Width: " & HsbWidth.Value
        CalculateArea()
    End Sub

    Private Sub HsbLength_Scroll(sender As Object, e As ScrollEventArgs) Handles HsbLength.Scroll
        'Show length and calculate area
        LblLength.Text = "Width: " & HsbLength.Value
        CalculateArea()
    End Sub
    Private Sub CalculateArea()
        Dim area As Integer = HsbWidth.Value * HsbLength.Value
        LblArea.Text = "Area: " & area
    End Sub
End Class

NEXT: functions