areaStart 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 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, using labels Label (from top to bottom) LblInstructions, LblLength (text = 1), LblAreaHeader, LblArea, and LblWidth (text=1).
Add a vertical scroll bar VsbVsbWidth: LargeChange=1, Minimum=1, and Value=1. Add a horizontal scroll bar Hsb HsbLength: LargeChange=1, Minimum=1, and Value=1. Write the code as shown below:

Private Sub Calc() 'a general procedure, not associated with any event
   Dim Area As Integer
   Area = Me.HsbLength.Value * Me.VsbWidth.Value
   Me.LblArea.Text = Area
End Sub 'Calc

Private Sub HsbLength_Scroll(ByVal sender As System.Object, ByVal e As _
     System.Windows.Forms.ScrollEventArgs) Handles HsbLength.Scroll
   Me.LblLength.Text = Me.HsbLength.Value
   Calc()
End Sub 'HsbLength_Scroll

Private Sub VsbWidth_Scroll(ByVal sender As System.Object, ByVal e _
      As System.Windows.Forms.ScrollEventArgs) Handles VsbWidth.Scroll
   Me.LblWidth.Text = Me.VsbWidth.Value
   Calc()
End Sub 'VsbWidth_Scroll

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Calc() 'This is so the area will show correctly at start
End Sub 'Form1_Load

INDEX, General Procedures
Next lesson: Dialogs in Visual Basic

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

General Procedures