color2Global Variables: Counter

A global variable is one that is not declared inside a procedure or function. A global variable can be accessed, changed, or modified anywhere in the program. Variables that are declared inside a procedure or function are local: they can only be used inside the procedure or function where they are declared. We are going to modify the color program by adding a counter. The counter will be declared outside of the procedures, making it global. Write the code as shown below:

Public Class Form1
    Dim Number As Integer = 0 'number is global
    Private Sub Form1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
           Handles Me.MouseClick
        Dim Red, Green, Blue As Integer ' red, green and blue are local  to form1_MouseClick
        Number = Number + 1
        Red = Rnd() * 255
        Green = Rnd() * 255
        Blue = Rnd() * 255
        Me.BackColor = Color.FromArgb(Red, Green, Blue)
        Me.Text = "Color " & Number & " is " & Hex(Red) & Hex(Green) & Hex(Blue) 'shows the hex value of the color
    End Sub 'Form1_MouseClick
End Class

INDEX, Introduction to Variables, Assigning Values to a Variable, Short Cut Notations, Global variables
Next lesson: Boolean Expressions in Visual Basic

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Global variables