Assignment Statements

To store a value in a variable or to change the setting of a property we will use an assignment statement.

Format of assignment statement:

variable/property = Variable or
Property or
Constant or
Expression

For example

frmMain.Text = strFileName

lblOutput.Text = txtInput.Text

decOverTimeFactor = 1.5

decGrossPay = sngPayRate * sngHours


The equal signs in these examples are assignment operators, not equality operators.

Whatever is on the right of the assignment operator is evaluated and the result is placed in whatever is on the left. What is on the left is made equal to what is on the right. Only a variable, object or property can be to left of equal sign in an assignment statement.

 

You can only assign numeric data to numeric variables/properties and string data to string variables/properties. If you attempt to assign a nonnumeric value to a numeric variable or numeric property a run-time error will occur

 

Invalid cast error message


All numeric data types can be assigned to each other. When you assign a floating-point number to an Integer type variable Visual Basic rounds rather than truncates the fractional part.

 

Examples of assigning constants to variables and properties of controls:

To clear the Text property of a Label

lblOutput.Text= “”

Quotes with nothing, not even a space between them are called a zero-length string or empty string.

To initialize a numeric variable to zero. To initialize a variable means to give a beginning value to a variable

intCount = 0

 

To assign a value to a string variable

strName = “Parkland College”

 

To assign a value to a Boolean variable

blnSalaried = True


NOTE: Variables can be assigned a value at the time they are declared.


Dim intNum As Integer = 7