Pages

Showing posts with label Visual Basic. Show all posts
Showing posts with label Visual Basic. Show all posts

Saturday, May 7, 2016

VB.Net Chapter 8 - Select Case Control Structure

VB.Net Chapter 8 -  Select Case Control Structure 



In This Chaper
• Understanding The Select Case ….End Select Structure

In the previous Chapter, we have learned how to control the program flow using the If...ElseIf control structure. In this chapter, you will learn another way to control the program flow, that is, the Select Case control structure. However, the Select Case control structure is slightly different from the If...ElseIf control structure. The difference is that the Select Case control structure basically only make decision on one expression or dimension (for example the examination grade) while the If...ElseIf statement control structure may evaluate only one expression, each If...ElseIf statement may also compute entirely different dimensions. Select Case is preferred when there exist many different conditions because using If...Then...ElseIf statements might become too messy.

The Select Case ...End Select control structure is shown below:

Select Case test expression  
   Case expression list 1 
        Block of one or more VB statements  
   Case expression list 2 
        Block of one or more VB Statements  
   Case expression list 3 
        Block of one or more VB statements  
   Case expression list 4  
               Block of one or more VB statements  
   Case Else  
        Block of one or more VB Statements  
End Select


Example 8.1

Based on Example 7.4, you can rewrite the code using Select Case...End Select, as shown below.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
'Examination Marks  
Dim mark As Single  
mark = mrk.Text    
Select Case mark  
Case 0 to 49  
   Label1.Text = "Need to work harder"  
Case 50 to 59  
   Label2.Text = "Average"  
Case 60 to 69  
   Label3.Text= "Above Average"  
 Case 70 to 84  
   Label4.Text = "Good"  
Case Else  
   Label5.Text= "Excellence"  
End Select  
End Sub


Example 8.2

In this example, you can use the keyword Is together with the comparison operators.

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click  
'Examination Marks
Dim mark As Single
mark = mrk.Text
Select Case mark
Case Is >= 85
     Label1.Text= "Excellence"
Case Is >= 70
     Label2.Text= "Good"
Case Is >= 60
     Label3.Text = "Above Average"
Case Is >= 50
     Label4.Text= "Average"
Case Else
     Label5.Text = "Need to work harder"
End Select
End Sub


Example 8.3 

You also can rewrite Example 8.2 by omitting the keyword IS, as shown here:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click  
'Examination Marks
Dim mark As Single 
mark = mrk.Text
Select Case mark
Case 0 to 49
    Label1.Text = "Need to work harder"
Case 50 to 59
    Label2.Text = "Average"
Case 60 to 69
    Label3.Text= "Above Average"
Case 70 to 84
    Label4.Text = "Good"
Case Else
    Label5.Text= "Excellence"
End Select
End Sub


Summary
In this chapter, you learned how to control program flow using the Select Case control structure. You also learned how to write code for the practical usage of the Select Case control structure, such as the program that processed examination marks. 

Monday, May 2, 2016

VB.Net Chapter 7 - Controlling Program Flow

Chapter 7 - Controlling Program Flow


In This Chapter
• Understanding Conditional and Logical Operators
• Using the If control structure with the Comparison Operators

In the previous Chapters, we have learned how to write code that accepts input from the user and displays the output without controlling the program flow. In this chapter, you will learn how to write VB2010 code that can make decision when it processes input from the user, and controls the program flow in the process. Decision making process is an important part of programming because it will help solve practical problems intelligently so that it can provide useful output or feedback to the user. For example, we can write a VB2010 program that can ask the computer to perform certain task until a certain condition is met, or a program that will reject non-numeric data. In order to control the program flow and to make decisions, we need to use the conditional operators and the logical operators together with the If control structure. 

7.1 Conditional Operators 

 The conditional operators are powerful tools that can compare values and then decide what actions to take, whether to execute a program or terminate the program and more. They are also known as numerical comparison operators. Normally we use them to compare two values to see whether they are equal or one value is greater or less than the other value. The comparison will return true or false result. These operators are shown in Table 7.1


Table 7.1: Conditional Operators 


7.2 Logical Operators 

Sometimes we might need to make more than one comparison before a decision can be made and an action taken. In this case, using numerical comparison operators alone is not sufficient, we need to use additional operators, and they are the logical operators. The logical operators are shown in Table 7.2.

Table 7.2: Logical Operators 


* Normally the above operators are use to compare numerical data. However, you can also compare strings with the above operators. In making strings comparison, there are certain rules to follows: Upper case letters are less than lowercase letters, "A"<"B"<"C"<"D"...<"Z" and number are less than letters. 

7.3 Using the If control structure with the Comparison Operators 

To effectively control the VB program flow, we shall use the If control structured together with the conditional operators and logical operators. There are three types of If control structure, namely If...Then statement, If...Then... Else statement and If...Then...ElseIf statement. 

7.3(a) If...Then Statement 

This is the simplest control structure which ask the computer to perform a certain action specified by the VB expression if the condition is true. However, when the condition is false, no action will be performed. The general format for the if...then... statement is 

If condition Then  
VB expression 
End If


Example 7.1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
Dim myNumber As Integer
myNumber = TextBox1.Text
If myNumber > 100 Then
Label2.Text = " You win a lucky prize"
End If 
End Sub

When you run the program and enter a number that is greater than 100, you will see the "You win a lucky prize" statement. On the other hand, if the number entered is less than or equal to 100, you do not see any display. 

7.3(b) If...Then...Else Statement 

Using just If...Then statement is not very useful in programming and it does not provides choices for the users. In order to provide a choice, we can use the If...Then...Else Statement. This control structure will ask the computer to perform a certain action specified by the VB expression if the condition is true. When the condition is false, an alternative action will be executed. The general format for if...then... Else statement is

If condition Then  
VB expression 
Else 
VB expression 
End If

Example 7.2 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
Dim myNumber As Integer
myNumber = TextBox1.Text
If myNumber > 100 Then
Label2.Text = "Congratulation! You win a lucky prize!"
Else
Label2.Text = "Sorry, You did not win any prize"
End If 
End Sub


When you run the program and enter a number that is greater than 100, it displays a message “Congratulation! You win a lucky prize!”  On the other hand, if the number entered is less than or equal to 100, you will see the "Sorry, You did not win any prize" message.

Example 7.3 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
Dim myNumber, MyAge As Integer
myNumber = TextBox1.Text
MyAge = TextBox2.Text  

If myNumber > 100 And myAge > 60 Then
Label2.Text = " Congratulation! You win a lucky prize"
Else
Label2.Text = " Sorry, You did not win any prize"
End If 
End Sub

This program use the logical And operator beside the conditional operators. This means that for the statement to be true, both conditions must be fulfilled in order; otherwise, the second block of code will be executed. In this example, the number entered must be more than 100 and the age must be more than 60 in order to win a lucky prize, any one of the above conditions not fulfilled will disqualify the user from winning a prize. 

7.3(c) If...Then...ElseIf Statement 

If there are more than two alternatives, using just If...Then...Else statement will not be enough. In order to provide more choices, we can use the If...Then...ElseIf Statement. The general format for the if...then... Else statement is

If condition Then 
VB expression
ElseIf condition Then 
VB expression
ElseIf condition Then 
VB expression
Else
VB expression
End If 


Example 7.4 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Mark As Integer
Dim Grade as String
Mark = TextBox1.Text
If myNumber >=80 Then
Grade="A"
ElseIf Mark>=60 and Mark<80 then
Grade="B"
ElseIf Mark>=40 and Mark<60 then
Grade="C"
Else
Grade="D"
End If
End Sub



Summary

In this chapter, you learned how to use the If control structure together with the comparison operators to control program flow. 

• In section 7.1, you learned how to use the conditional operators in VB2010 such as =, <,>, >=, <= and <>. 

• In section 7.2, you learned how to use the logical operators And, Or, Xor and Not. 

• In section 7.3, you learned three types of If control structure, i.e. If...Then, If...Then...Else and If...Then...ElseIf. Besides, you also learned how to write code involving the use of the If control structure. 

Visual Basic .Net Random Number Generator

Visual Basic .Net Random Number Generator


Video:


Download Project:
Download

Password: ucx

Source Code:

Public Class Form1

    Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
        txt_RandomNumber.Clear()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        txt_RandomNumber.Clear()

        Dim RNG As New Random
        txt_RandomNumber.Text = RNG.Next(txt_Min.Text, txt_Max.Text)
    End Sub
End Class

Wednesday, April 27, 2016

VB.Net Chapter 6 - String Manipulation

Chapter 6 - String Manipulation



In This Chapter
• Learn how to manipulate Strings

String manipulation is an important part of programming because it helps to process data that come in the form of non-numeric types such as name, address, city, book title and etc.

6.1 String Manipulation Using + and & signs. 

Strings can be manipulated using the  & sign and the + sign, both perform the string concatenation which means combining two or more smaller strings into a larger string. For example, we can join "Visual" and "Basic" into "Visual Basic" using "Visual"&"Basic" or "Visual "+"Basic", as shown in the example below

Example 6.1


Public Class Form1 
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As 
System.EventArgs) Handles Button1.Click 
Dim text1, text2, text3 As String 
text1 = "Visual" 
text2 = "Basic" 
text3 = text1 + text2 
Label1.Text = text3 
End Sub 
End Class


The line text3=text1+ text2 can be replaced by text3=text1 & text2 and produced the same output. However, if one of the variables is declared as numeric data type, you cannot use the + sign, you can only use the  & sign.

Example 6.2 


Dim text1, text3 as string 
Dim Text2 As Integer 
text1 = "Visual" 
text2=22 
text3=text1+text2 
Label1.Text = text3


This code will produce an error because of data mismatch. However, using & instead of + will be all right.

Example 6.3 


Dim text1, text3 as string 
Dim Text2 As Integer 
text1 = "Visual" 
text2=22 
text3=text1 & text2 
Label1.Text = text3

You can combine more than two strings to form a larger string, like the following example:

Example 6.4 


Public Class Form1  
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim text1, text2, text3, text4, text5, text6 As String 
text1 = "Welcome"
text2 = "to"
text3 = "Visual"
text4 = "Basic"
text5 = "2008"
text6 = text1 + text2 + text3
Label1.Text = text4  
End Sub End Class

Running the above program will produce the following screen shot.


Figure 6.1: The Screen Shot 



6.2 String Manipulation Using VB2010 Built-in Functions 

A function is similar to a normal procedure but the main purpose of the function is to accept a certain input and return a value, which is passed on to the main program to finish the execution. VB2010 has numerous built-in string manipulation functions but we will only discuss a few here. You will learn more about these functions in later Chapters.

6.2 (a) the Len Function 

The length function returns an integer value that is the length of a phrase or a sentence, including the empty spaces. The format is

Len ("Phrase") 

For example,

Len (Visual Basic) = 12 and  
Len (welcome to VB tutorial) = 22 


Example 6.5 


Public Class Form1  
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
Label1.Text = Len(TextBox1.Text)  
End Sub
End Class

The output:


Figure 6.2 



6.2(b) the Right  Function 

The Right function extracts the right portion of a phrase. The format for Visual Basic 6 is

Right ("Phrase", n)

Where n is the starting position from the right of the phase where the portion of the phrase is going to be extracted.  For example,

Right("Visual Basic", 4) = asic 

However, this format is not applicable in VB2010. In VB2010, we need to use the following format

Microsoft.VisualBasic.Right("Phrase",n) 

Example 6.6 


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim text1 As String  
text1 = TextBox1.Text  
Label1.Text = Microsoft.VisualBasic.Right(text1, 4) 
End Sub

The above program will return four right most characters of the phrase entered into the textbox, as shown in Figure 6.3

Figure 6.3 



*The reason of using the full reference is because many objects have the Right properties so using Right on its own will make it ambiguous to VB2010.

6.2(c) the Left Function 

The Left function extract the left portion of a phrase. The format is

Microsoft.VisualBasic.Left("Phrase",n) 

Where n is the starting position from the left of the phase where the portion of the phrase is going to be extracted.  For example,

Microsoft.VisualBasic.Left (“Visual Basic”, 4) = Visu

We will learn more about string manipulation function in Chapter 11.

Summary 
• In section 6.1, you learned how to manipulate strings using + and & signs. The + and & signs are used to join up two strings. 
• In section 6.2, you learned how to use string manipulation functions. Among the functions are Len, Right and  Left, 

Sunday, April 24, 2016

VB.Net Chapter 5 - Performing Mathematical Operations

Chapter 5 - Performing Mathematical Operations

In This Chapter
• Learn how to use Mathematical operators. 

Computers can perform mathematical calculations much faster than human beings. However, the computer itself will not be able to perform any mathematical calculations without receiving instructions from the programmer. In VB2010, we can write code to instruct the computer to perform mathematical calculations such as addition, subtraction, multiplication, division and other kinds of arithmetic operations. In order for VB2010 to carry out arithmetic calculations, we need to write code that involves the use of various arithmetic operators. The VB2010 arithmetic operators are very similar to the normal arithmetic operators, only with slight variations. The plus and minus operators are the same while the multiplication operator use the * symbol and the division operator use the / symbol. The list of VB2010 arithmetic operators are shown in table 5.1 below: 

Table 5.1: Arithmetic Operators


Example 5.1 

In this program, you need to insert two Textboxes, four labels and one button. Click the button and enter the code as shown below. When you run the program, it will perform the four basic arithmetic operations and display the results on the four labels. 


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As 
System.EventArgs) Handles Button1.Click 
Dim num1, num2, difference, product, quotient As Single 
num1 = TextBox1.Text 
num2 = TextBox2.Text 
sum=num1+num2 
difference=num1-num2 
product = num1 * num2 
quotient=num1/num2 
Label1.Text=sum 
Label2.Text=difference 
Label3.Text = product 
Label4.Text = quotient 
End Sub


Example 5.2 

The program can use Pythagoras Theorem to calculate the length of hypotenuse  c given the length of the adjacent side a and the opposite side b. In case you have forgotten the formula for the Pythagoras Theorem, We are showing it below: 

 c2=a2+b2

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As 
System.EventArgs) Handles Button1.Click 
Dim a, b, c As Single 
a = TextBox1.Text 
b = TextBox2.Text 
c=(a^2+b^2)^(1/2) 
Label3.Text=c 
End Sub

Example 5.3: BMI Calculator 

Many people are obese now and it could affect their health seriously. Obesity has proven by the medical experts to be a one of the main factors that brings many adverse medical problems, including the heart disease.   If your BMI is more than 30, you are considered obese. You can refer to the following range of BMI values for your weight status:  

Underweight = <18.5
Normal weight = 18.5-24.9 
Overweight = 25-29.9 
Obesity = BMI of 30 or greater 

In order to calculate your BMI, you do not have to consult your doctor, you could just use a calculator or a homemade computer program, and this is exactly what I am showing you here. The BMI calculator is a Visual Basic program that can calculate the body mass index, or BMI of a person based on the body weight in kilogram and the body height in meter. BMI is calculated based on the formula    weight/ (height) 2, where weight is measured in kg and height in meter. If you only know your weight and height in lb and feet, then you need to convert them to the metric system (you could indeed write a VB program for the conversion).

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As 
System.EventArgs) Handles Button1.Click 
Dim height, weight, bmi As Single 
height = TextBox1.Text 
weight = TextBox2.Text 
bmi = (weight) / (height ^ 2) 
Label4.Text = bmi 
End Sub

The output is shown in the Figure 7-1 below. In this example, your height is 1.80m (about 5 foot 11), your weight is 78 kg( about 170 Ib), and your BMI is about 23.5. The reading suggests that you are healthy. (Note; 1 foot=0.3048, 1 lb=.45359237 kilogram) 

Figure 5.1: BMI Calculator



Summary 
In this chapter, you learned how to use various mathematical operators in Visual Basic 2010 in writing code for mathematical calculations. You also learned how to create some programs to solve mathematical problems like Pythagoras Theorem. Besides, you learned how to create the BMI calculator. 

VB.Net Chapter 4 - Managing VB2010 Data

Chapter 4 - Managing VB2010 Data

In This Chapter
• Getting to know various data types in Visual Basic 2010 
• Assigning values to the variables 
• Getting to know various arithmetic operators in Visual Basic 2010 


In our daily life we come across many types of data. For example, we need to handle data such as names, addresses, money, dates, stock quotes, statistics and more everyday. Similarly, in Visual Basic 2010, we have to deal with all sorts of data; some are numeric in natrure while some are in the form of text or other forms. VB2010 divides data into different types so that it is easier to manage when we need to write the code involving those data.

4.1 Visual Basic 2010 Data Types 

Visual Basic classifies the information mentioned above into two major data types; namely the numeric data types and the non-numeric data types.

4.1.1 Numeric Data Types 

Numeric data types are types of data that consist of numbers, which you can compute them mathematically with various standard operators such as add, minus, multiply, divide and so on. Examples of numeric data types are your examination marks, your height and your weight, the number of students in a class, share values, price of goods, monthly bills, fees and more. In Visual Basic 2010, we divide numeric data into seven types, depending on the range of values they can store. Calculations that only involve round figures or data that do not need precision can use Integer or Long integer in the computation. Programs that require high precision calculation need to use Single and Double decision data types, we also call them floating-point numbers. For currency calculation, you can use the currency data types. Lastly, if even more precision is requires which involve many decimal points, we can use the decimal data types. We summarized the data types in Table 4.1

Table 4.1 Numeric Data Types



4.1.2 Non-numeric Data Types 

Nonnumeric data types are data that cannot be manipulated mathematically using standard arithmetic operators. The non-numeric data comprises text or string data types, the Date data types, the Boolean data types that store only two values (true or false), Object data type and Variant data type .We summarized them in Table 6.2

Table 4.2: Non-numeric Data Types 




4.1.3 Suffixes for Literals  

Literals are values that you assign to a data. In some cases, we need to add a suffix behind a literal so that VB2010 can handle the calculation more accurately. For example, we can use num=1.3089# for a Double type data. Some of the suffixes are displayed in Table 4.3.

Table 4.3



In addition, we need to enclose string literals within two quotations and date and time literals within two # sign. Strings can contain any characters, including numbers. The following are few examples:


memberName="Turban, John." 
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#

4.2 Managing Variables 
Variables are like mail boxes in the post office. The contents of the variables changes every now and then, just like the mail boxes. In term of VB2010, variables are areas allocated by the computer memory to hold data. Like the mail boxes, each variable must be given a name. To name a variable in Visual Basic 2010, you have to follow a set of rules.

4.2.1 Variable Names 
The following are the rules when naming the variables in Visual Basic 2010
 25 It must be less than 255 characters
No spacing is allowed
It must not begin with a number
Period is not permitted
Examples of valid and invalid variable names are displayed in Table 4.4

Table 4.4: Valid and invalid Names



4.2.2 Declaring Variables 

In Visual Basic 2010, one needs to declare the variables before using them by assigning names and data types. If you fail to do so, the program will show an error. They are normally declared in the general section of the codes' windows using the Dim statement.

The format is as follows:

Dim Variable Name As Data Type 

Example 4.1 

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As 
System.EventArgs) Handles MyBase.Load 
Dim password As String  
Dim yourName As String  
Dim firstnum As Integer  
Dim secondnum As Integer  
Dim total As Integer  
Dim doDate As Date  
End Sub

You may also combine them in one line, separating each variable with a comma, as follows:

Dim password As String, yourName As String, firstnum As Integer,.............

For string declaration, there are two possible formats, one for the variable-length string and another for the fixed-length string. For the variable-length string, just use the same format as example 4.1 above. However, for the fixed-length string, you have to use the format as shown below:

Dim VariableName as String * n

where n defines the number of characters the string can hold.

Example 4.2: 

Dim yourName as String * 10

yourName can holds no more than 10 Characters.

4.2.3 Assigning Values to Variables 

After declaring various variables using the Dim statements, we can assign values to those variables. The general format of an assignment is

 Variable=Expression 


The variable can be a declared variable or a control property value. The expression could be a mathematical expression, a number, a string, a Boolean value (true or false) and more. The following are some examples:


firstNumber=100  
secondNumber=firstNumber-99  
userName="John Lyan"  
userpass.Text = password  
Label1.Visible = True  
Command1.Visible = false  
Label4.Caption = textbox1.Text  
ThirdNumber = Val(usernum1.Text)  
total = firstNumber + secondNumber+ThirdNumber

4.3 Constants 

Constants are different from variables in the sense that their values do not change during the running of the program.

4.3.1 Declaring a Constant 

The format to declare a constant is

    Const Constant Name As Data Type = Value 

Example 4.3


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
Const Pi As Single=3.142 
Const Temp As Single=37 
Const Score As Single=100 
End Sub

Summary 
• In section 4.1, you learned that we could categorize data types into numeric and non-numeric data types.
• In section 4.2, you learned about the rules to name variables in Visual Basic 2010. Besides, you also learned how to declare variables using the Dim keyword and assign values to them. 
• In section 4.3, you learned about constants and the way to declare them.   

VB.Net Chapter 3 - Writing the Code

Chapter 3 - Writing the Code


In This Chapter
• Learning how to write Visual Basic 2010 Code 


In the previous chapter, you have learned to design an interface, adding controls and setting control properties. You have also learned how to write some simple code without understanding the concepts behind.  In this chapter, you will learn some basic concepts about VB2010 programming and the techniques in writing code .I will keep the theories short so that it would not be too taxing for beginners.

3.1 Understanding Event Driven Programming 

VB2010 is an object oriented and event driven programming language. In fact, all windows applications are event driven. Event driven means the user decides what to do with the program, whether he or she wants to click the command button, enter text in a text box, or close the application and more. An event is related to an object, it is an incident that happens to the object due to the action of the user, such as a click or pressing a key on the keyboard. A class contains events as it creates instant of a class or an object. When we start a windows application in VB2010 in previous chapters, we will see a default form with the Form1 appears in the IDE. Form1 is the Form1 Class that inherits from the Form class System.Windows.Forms.Form, as shown in Figure 3.1

Figure 3.1: The Form1 Class


The other events associated with the Form1 class are  click, DoubleClick, DragDrop, Enter and more, as shown in Figure 3.2  below (It appears when you click on the upper right pane of the code window)

Figure 3.2


3.2 Understanding the Code Structure of an Event Procedure 

Now you are ready to write the code for the event procedure so that it will do something more than loading a blank form.  The structure of the code takes the following form:

Private Sub... 
   Statements 
End Sub

You have to enter the code between Private Sub and End Sub.

Private Sub 
    Enter your code here 
End Sub

There are variations of the structure such as

1)
Private Sub 
    Enter your code here 
End Sub

2)
Sub 
    Enter your code here 
End Sub

3)
Function 
    Enter your code here 
End Sub

Let us enter the following code:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
Me.Text="My First VB2010 Program"
Me.ForeColor = Color.Yellow
Me.BackColor = Color.Blue 
End Sub

When you press F5 to run the program, the output is shown in Figure 3.3 below:

Figure 3.3: The Output Window


The first line of the code will change the title of the form to “My First VB2010 Program” , the second line will change the foreground object to yellow( in this case, it is a label that you insert into the form and change its name to Foreground) and the last line changes the background to blue color. The equal sign in the code is to assign something to the object, like assigning yellow color to the foreground of the Form1 object (or an instance of Form1). Me is the name given to the Form1 class. We can also call those lines as Statements. Therefore, the actions of the program will depend on the statements entered by the programmer. Here is another example.

Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
Dim name1, name2, name3 As String
name1 = "John"
name2 = "Chan"
name3 = "Ali"
MsgBox(" The names are " & name1 & " , " & name2 & " and " & name3) 
End Sub

In this example, you insert one command button into the form and rename its caption as Show Hidden Names. The keyword Dim is to declare variables name1, name2 and name3 as string, which means they can only handle text. The function MsgBox is to display the names in a message box that are joined together by the "&" signs. The output is shown in Figure 3.4 below:

Figure 3.4: The Output Window For Displaying Names



3.3 Writing a Simple Multiplication Program 

In this program, you insert two text boxes, three labels and one button. The text boxes are for the user to enter numbers, the label is to display the multiplication operator and the other label is to display the equal sign. The last label is to display the answer. The run time interface is shown in Figure 3.5

Figure 3.5: The Multiplication Program



The Code 


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
Dim num1, num2, product As Single
num1 = TextBox1.Text
num2 = TextBox2.Text
product = num1 * num2
Label3.Text = product 
End Sub

3.4 Writing a Program that Add Items to a List Box

This program will add one item at a time to a list box as the user enters an item into the text box and click the Add button. In this program, you insert a TextBox and a ListBox into the Form. The function of the TextBox is to let the user enter an item one at a time and add it to the Listbox. The method to add an item to the ListBox is Add. The output interface is shown in Figure 3.6.

The Code 


Class Frm1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
Dim item As String
item = TextBox1.Text 
'To add items to a listbox
ListBox1.Items.Add(item) 
End Sub End Class


Figure 3.6: The Add Items Program



Summary 
• In section 3.1, you learned the concept of event driven programming. 
• In section 3.2, you learned how to write a simple code for an event procedure, including the usage of MsgBox().
• In section 3.3, you learned how to create a multiplication program. 
• In section 3.4, you learned how to write a program to add some items to a list box.