Zebra0.com

visual-basic procedures

Previously, we wrote a program to show a cat or dog.

The code for the pets program is shown below:

'Programmer: Janet Joy
'Show picture of dog or cat
Public Class Form1
    Private Sub BtnDog_Click(sender As Object, e As EventArgs) Handles BtnDog.Click
        'Hide the cat, show the dog
        Me.PicCat.Visible = False
        Me.PicDog.Visible = True
    End Sub

    Private Sub BtnCat_Click(sender As Object, e As EventArgs) Handles BtnCat.Click
        'show the cat, hide the dog
        Me.PicCat.Visible = True
        Me.PicDog.Visible = False
    End Sub
End Class

The code could also be written as shown below:

'Programmer: Janet Joy
'Show picture of dog or cat
Public Class Form1
    Private Sub BtnDog_Click(sender As Object, e As EventArgs) Handles BtnDog.Click
        hidepets() 'call the sub that hides all of the pets
        Me.PicDog.Visible = True
    End Sub

    Private Sub BtnCat_Click(sender As Object, e As EventArgs) Handles BtnCat.Click
        hidepets() 'call the sub that hides all of the pets
        Me.PicCat.Visible = True
    End Sub

    Private Sub hidepets()
        'Hide all of the animals
        Me.PicCat.Visible = False
        Me.PicDog.Visible = False
    End Sub
End Class

Compare these two programms. Now thing about what would happen if we added a couple more pets. The second solution will be much easier to add more animals to.

NEXT: Adding a pet