microsoft visual basic 2012 · chapter 1 introduction to visual basic 2012 1.1 a brief description...

40
1 Microsoft Visual Basic 2012 Chapter One University of Baghdad College of Education for Pure Science Dep.of Computer Science Third Stage M.Sc. Lubab Ahmed 2019-2020

Upload: others

Post on 27-Jun-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

1

Microsoft

Visual Basic

2012

Chapter One

University of Baghdad

College of Education for Pure

Science

Dep.of Computer Science

Third Stage

M.Sc. Lubab Ahmed

2019-2020

Page 2: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

2

Chapter 1

Introduction to Visual Basic 2012

1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming (OOP) Language, so it has caught up with other OOP languages such as C++, Java, C# and others. However, you don't have to know OOP to learn Visual Basic 2012. In fact, if you are familiar with Visual Basic 6, you can learn Visual Basic 2012 effortlessly because the syntax and interface are almost similar. 1.2 The reasons for of implementing Visual Basic program are listed as follows:

1- It uses integrated development environment (IDE) which is easier for the user to minimize

code writing.

2- All visual programs follow the same concepts, therefore the user will become more familiar

with visual approach for other visual languages.

3- It provides Input box and Output box as an interactive windows with user.

4- It is able to connect to Internet, and to call Explorer.

1.3 Visual Studio 2012 Integrated Development Environment When you launch Visual Studio 2012 Express, you will be presented with the start page, as shown in Figure 1.1

1.2

f-

Figure 1.1: Visual Studio Express 2012 Start Page

The Visual Studio 2012 start page comprises three sections, the start page, the output section and the solution explorer. In the start page, you can start a new project, open a project or

Page 3: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

3

open a recent project. You can also check for the latest news in Visual Studio 2012 Express for Windows Desktop. The start page also consists of a menu bar and a tool bar where you can perform various tasks by clicking the menu items. 1.3 Creating a New Project in Visual Studio 2012 To start a new Visual Studio Express 2012 project, click on New Project under the Start section to launch the Visual Studio 2012 New Project page as shown in Figure 1.2. You can also choose to open a recent project:

Figure 1.2: Visual Studio 2012 Express New Project Page

The New Project Page comprises three templates, Visual Basic, Visual C# and Visual C++. Since we are going to learn Visual Basic 2012, we shall select Visual Basic. Visual Basic 2012 offers you four types of projects that you can create; they are Windows Forms Application, WPF Application, Console Application and Class Library. Since we are going to learn how to create windows desktop applications, we shall select Windows Forms Application. At the bottom of this dialog box, you can change the default project name WindowsApplication1 to some other name you like, for example, ‘ My First VB2012 Program’. After renaming the project, click OK to launch the Visual Basic Express 2012 IDE, as shown in Figure 1.3. Visual Basic Express 2012 IDE comprises a few windows, the Form window, the Solution Explorer window and the Properties window. It also consists of a toolbox which contains many useful controls that allows a programmer to develop his or her Visual Basic 2012 programs.

Page 4: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

4

Figure 1.3: The Visual Basic 2012 Express IDE

ToolBox: it contains a collection of tools that are needed for project design. Form Designer: it is a window for each form to customize the designed interface of the application. Using the form designer, the user can add controls, graphics, and text to create the desired form appearance. Properties Window: it is a List of properties settings for a selected form or a control. These properties are characteristics (such as size, visible, or color) of the selected object it provides an easy way to set properties. Project Explorer Window: it is a list of the forms and modules for the current projects. lt is a hierarchical tree- branch structure, where the project at top of tree and other parts like forms ,modules) descend from this tree.

Note: The Toolbox is not shown until you click on the Toolbox tab. When you click on the Toolbox tab or use the shortcut keys Ctrl+w+x, the common controls Toolbox will appear.

Page 5: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

5

1.4 Working with Controls

▪ When you create a new project , you see an empty dialog box, which is known as a form, and also a Toolbox with a lot of controls.

▪ You can add controls by dragging the controls into the form. When you finish, press F5 (the function button at the top of the keyboard) to run the program.

▪ In Visual Basic, users interact with the program using the controls in the form. Each control has its own use. Here are the types of controls we learn in this chapter:

Forms The form is the most important visible object, without it no control can be displayed. It is a window that can be designed and modified to fit user applications. When user starts visual Basic program a form is automatically displayed in Designer window. The designer can add any number of forms to the project of his application by pressing: add windows form from project menu.

Figure 1.4: The Visual Basic 2012 (Windows Form)

Page 6: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

6

Figure 1.5: The Visual Basic 2012 (Windows Application)

Forms properties The most important properties of the form are listed in the following table:

Property Name

Objective Code Stage of changing

Text String appear in title of form Me.Text = "any text" Design and run

Backcolor Background color for form. Me.BackColor = Color.anycolor Design and run

Forecolor Color of text written on form. anycolor.Color.ForeColor = Me Design and run

Font Font style, type and size.

Hide To hide the form Me.Hide() Run

Show To show the form ().Showno.Form Run

Window State Change the size of form Normal Minimized Maximized

Design

Close Close a form

Me.Close()

Design

Examples: 1- Design a form such that: in event load, when project runs, the form backcolor property changed (choose any color) and the name of form changed into "Visual Basic" sol: code: Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Me.BackColor = Color.Blue()

Page 7: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

7

Me.Text = "Visual Basic" End Sub

: 1Exercise

Design a form such that: in event click , when project runs, the form backcolor property changed (choose any color) and the name of form changed into "Computer Science" 1.5 The structure of an event procedure You can look at the following example for the structure of an event procedure. Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click [Add your code here] End Sub

Now the code is explained part by part:

Part Meaning Private Sub Declare a procedure

Button1_Click The name of the procedure. The default is the name of the event, with “.” changed to “_”. You can change this name by yourself.

(sender As System.Object, e As System.EventArgs)

Currently unimportant. Usually abbreviated as (…) in this book

Handles Button1.Click

The event or events to handle. Change this to something like “Handles Button1.Click, Button2.Click, Button3.Click” to handle multiple events in the same procedure

End Sub Marks the end of the event procedure

Page 8: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

8

1.6 Events When the user does some action in the form (e.g. click a button), an event is raised or triggered. You can write a procedure in your Visual Basic program to handle the event, and that procedure will be executed every time the user does the same action.

Names and types of events The most commonly used events of are Load and Click. Here is a shortlist of events we use in this course:

Name of event When the event is raised

Load Before a form is displayed the first time. In most cases, this is when the program starts running.

Click When the user clicks a form or control (e.g. Button). DoubleClick* When the user double clicks certain kinds of controls (e.g. Form, Label,

TextBox). Note: A Button does not raise the DoubleClick event. TextChanged† When the content of the Text property is changed (either by user input or

by Visual Basic.net code.) MouseEnter When the mouse enter a form or control

In Visual Basic, users interact with the program using the controls in the form. Each control has its own use. Here are the types of controls we learn in this chapter:

Page 9: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

9

Controls Properties Forms and controls have properties, events, and methods. Together they make the forms and controls useful for programmers. You can change the appearance of the controls (and form) by setting their properties in the properties window (see the figure). Here is a shortlist of the properties we use in the course:

Property Name

Objective Code Stage of changing

Text String appear in title of control

Text1.Text = "any text" Label1.Text ="any text"

Button1.Text = "any text"

Design and Run

MultiLine To enter more than one line in TextBox1 only

True or False Design

Backcolor Background color for control. Text1.BackColor = Color.anycolor Label1.BackColor = Color.anycolor

Button1.BackColor = Color.anycolor

Design and Run

Forecolor Color of text written on control.

anycolor.Color.ForeColor = Text1 anycolor.ColorLabel1.ForeColor = anycolor.Color Button1.ForeColor =

Design and Run

Font The font used by the text in the control.

Font style, type and size. From Properties

Design

TextAlign The horizontal and vertical alignment of the text inside the control.

Left/Right/Center From properties

Design

Left Top

Horizontal/vertical position of the control, counted by the number of pixels relative to the left/top side of its parent.

TextBox1.Left = no, TextBox1.Top = no Label1.Left= no, label1.Top = no

Button1.Left= no , Button1.Top = no

Run

Width Height

The width or height of the control, counted by the number of pixels.

TextBox1.Width = no, TextBox1.Hight = no Label1.Width= no, label1.Hight= no

Button1.Width= no , Button1.Hight = no

Run

Hide To hide the control TextBox1.Hide() Label1.Hide()

Button1.Hide()

Run

Visible The control appear or disappear

Text1 .Visible = True or False Label1. Visible = True or False

Button1.Visible = True or False

Design and Run

Enabled The control enable or disable TextBox1.Enabled = True or False Label1. Enabled= True or False

Button1. Enabled= True or False

Design and Run

Page 10: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

10

Properties of controls can be changed using the properties window (during design time) or by

Visual Basic code (during runtime).

Using the Text Box,Label,Button Next, we will show you how to create a simple calculator that adds two numbers using the TextBox control. In this program, you insert two text boxes, three labels, and one button. The two text boxes are for the users to enter two numbers, one label is to display the addition operator and the other label is to display the equal sign. The last label is to display the answer. Now change the label on the button to Calculate, then click on this button and enter the following code:

Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button2.Click Dim num1, num2, product As Single num1 = TextBox1.Text num2 = TextBox2.Text product = num1 + num2 Label1.Text = product End Sub

When you run the program and enter two numbers, pressing the calculate button adds the two

numbers.

Page 11: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

11

Here is an example program that changes some properties of the form and the controls. To

enter the code into Visual Basic IDE, you can double click Button1 in design view. Can you

guess what will happen after Button1 is clicked?

Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click Me.Text = "Button1 Pressed!" Me.BackColor = Color.Pink Label1.Text = "Name" Label1.BackColor = Color.Green Label1.ForeColor = Color.Yellow Label1.Top = 80 TextBox1.Text = "Sarah" TextBox1.BackColor = Color.Red TextBox1.Enabled = False TextBox1.Left = 20 Button1.Visible = False End Sub

Before After

Page 12: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

12

AppendText and Paste methods Control Method Meaning Example

TextBox AppendText Add some text to the end of the current text in the text box.

TextBox1.AppendText("Hello")

TextBox Paste Paste some text to the cursor/selection of the text box.

TextBox1.Paste("Hello")

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click TextBox2.AppendText(TextBox1.Text) End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click TextBox2.Paste(TextBox1.Text) End Sub Multiple forms (try the buttons and text box yourself) Form1.vb Public Class Form1 Private Sub ButtonShow_Click(...) Handles ButtonShow.Click Form2.Show() End Sub Private Sub ButtonShowDialog_Click(...) Handles ButtonShowDialog.Click Form2.ShowDialog() End Sub End Clas Form2.vb Public Class Form2 Private Sub ButtonClose_Click(...) Handles ButtonClose.Click Me.Close() End Sub End Class

Page 13: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

13

Exercise 2:

1. Write a program with two controls: Button1 and TextBox1. When Button1 is clicked, the following things should happen: (a) TextBox1 is disabled,

(b) The background color of TextBox1 becomes yellow,

(c) Button1 becomes visible, and

(d) The form’s background color becomes white. 2. Identify the mistakes in the following source code. There is one mistake in each line. (Note: There are no mistakes with the words Me, Label1, Button1 and TextBox1.) Me.Title = "Title of the form" Label1.BackColor = Colour.Green Button1.Visible = Ture TextBox1.Enable = False TextBox1.Text = Very good

CheckBox and RadioButton

The checkbox is a control that allows the user to select multiple items. For example, in the

Font dialog box of Microsoft Words, there are many checkboxes under the Effects

section, such as that shown in the Figure below. The user can choose to format the text with

an underline, subscript, small caps, superscript, blink and more.

Example

In this example, the user can enter text into a text box and format the font using the three

checkboxes that represent bold, italic and underline.

Page 14: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

14

Public Class Form1 Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged If CheckBox1.Checked Then TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Bold) Else TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not FontStyle.Bold) End If End Sub Private Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox2.CheckedChanged If CheckBox2.Checked Then TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Italic) Else TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not FontStyle.Italic) End If End Sub Private Sub CheckBox3_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox3.CheckedChanged If CheckBox2.Checked Then TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Underline) Else TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not FontStyle.Underline) End If End Sub End Class The above program uses the CheckedChanged event to respond to the user selection by checking a particular checkbox, it is similar to the click event. The statement

TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style Or FontStyle.Italic)

Page 15: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

15

will retain the original font type but change it to italic font style.

TextBox1.Font = New Font(TextBox1.Font, TextBox1.Font.Style And Not FontStyle.Italic)

RadioButton The radio button is another control in Visual Basic 2012 that allows selection of choices. However, it operates differently from the check box. While the check boxes allow the user to select one or more items, radio buttons are mutually exclusive, which means the user can only choose one item only out of a number of choices. Here is an example which allows the user to select one color only. Example Dim strColor As String Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged strColor = "Red" End Sub Private Sub RadioButton2_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton2.CheckedChanged strColor = "Green" End Sub

Page 16: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

16

Private Sub RadioButton3_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton3.CheckedChanged strColor = "Green" End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Label1.Text = strColor End Sub Exercise3: Timer The timer is used to manage events that are time-related. For example, you can use the timer to create a clock, a stopwatch and more.

Example : Creating a Clock

To create a clock, you need to use the Timer control that comes with Visual Basic 2012. The Timer control is a control object that is only used by the developer, it is invisible during runtime and it does not allow the user to interact with it. Now add the Timer control to the form by dragging it from the control tool Box. Next, insert a label control into the form. Change the Font size of the label to 14 or any size you wish, and set the Font alignment to be the middle center. Lastly, you shall also set the Interval property of the Timer control to 1000, which reflects a one-second interval(1 unit is 1 millisecond).

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Label1.Text = TimeOfDay End Sub

Page 17: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

17

Example : Creating a simple stopwatch

We can create a simple stopwatch using the Timer control. Start a new project and name it stopwatch. Change the Form1 caption to Stopwatch. Insert the Timer control into the form and set its interval to 1000 which is equal to one second. Besides, set the timer Enabled property to False so that it will not start ticking when the program is started. Insert three command buttons and change their names to StartBtn, StopBtn and ResetBtn respectively. Change their text to “Start”, “Stop” and “Reset” accordingly. Now, key in the code as follows:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick 'To increase one unit per second Label1.Text = Val(Label1.Text) + 1 End Sub Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click 'To stop the Timer Timer1.Enabled = False End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'To start the Timer Timer1.Enabled = True End Sub Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click 'To reset the Timer to 0 Label1.Text = 0 End Sub

The Interface of the Stopwatch is as shown below:

Page 18: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

18

Example : Creating a Digital Dice

To create a dice, you need to generate random numbers using the Rnd function. Rnd generates numbers between 0 and 1.

Generates integers from 1 to 6 randomly.

In the code, we introduce the variable m to control the length of time of the rolling process. If m is more than 1000, then the rolling process will stop by setting the timer enabled property to False.

Dim n, m As Integer Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick m = m + 10 If m < 1000 Then n = Int(1 + Rnd() * 6) Label1.Text = n Else Timer1.Enabled = False m = 0 End If End Sub

Page 19: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

19

Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click Timer1.Enabled = True End Sub

Running the program produces a dice with fast changing numbers which stop at a certain number. The interface is shown below:

Exercise4 : Design a program that’s contents Lable1, Button1 and Timer1 , when press the Button1 the

lable1 will be a countdown , The timer stop when the Label1 equal zero and show message

"The Time is Over".

Introduction to InputBox and MsgBox Besides using labels and textboxes, we can use InputBox and MsgBox to handle input and

output. In this part, we only deal with the simplest way to handle input and output. The

details will be discussed in the second term.

InputBox

To use an InputBox to input a string, we use the following statement:

variablename = InputBox("message")

Page 20: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

20

If you want to input a number, you should use the Val function to convert the string into a

number, i.e.

Here is an example asking for your name using InputBox:*

s = InputBox("What is your name?")

MsgBox To use MsgBox to display a message, we use the following statement:

Here is an example using MsgBox:

MsgBox("This is a wonderful message!")

Multiline MsgBox

variablename = Val(InputBox("message"))

MsgBox("message")

Page 21: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

21

If you want to display a message with more than one line, see the example below. The “&”

character join strings together, and vbCrLf is similar to the “Enter” key in the text editor.

(Note: the example below should be typed in a single line.)

MsgBox("You Won!!!" & vbCrLf & vbCrLf & "You rolled a 6" & vbCrLf & "and the computer

rolled a 5!")

Example : Calculate the product of two numbers

Private Sub Button1_Click(sender As Object, e As EventArgs)

Dim x, y, product As Double

x = Val(InputBox("Input the first number."))

y = Val(InputBox("Input the second number."))

product = x * y

MsgBox("Their product is: " & product)

End Sub

Exercise 5:

1. Rewrite previous Example into a program that uses text boxes and labels but not InputBox and MsgBox.

2. Write a program that uses InputBox to input two numbers when the form is loaded. The numbers are stored into two variables. Now the user can press one of the four buttons, that each of the buttons does a basic arithmetic operation (i.e. +, –, × or ÷)* on the two numbers, and then display the results using an MsgBox. Note: Do not use any text boxes or labels in this question.

Page 22: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

1

Microsoft

Visual Basic

2012

Chapter Two

University of Baghdad

College of Education for Pure

Science

Dep.of Computer Science

Third Stage

M.Sc. Lubab Ahmed

2019-2020

Page 23: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

2

Chapter 2

Variables

In Visual Basic, you use variables to store values. Variables have a name and a data

type.

Declaring variables with Dim statement

Dim variablename [As type]

The data type of the variable can be one of the following:

Data Type Description

Integer Integer (between -2,147,483,648 through 2,147,483,647) Single Single-precision floating-point (about 7 significant figures). Double Double-precision floating-point (about 16 significant figures). Boolean True or False String Text (holds your name, ID card number, etc…)

Example : Dim score As Integer Dim weight As Double Dim finished As Boolean Dim name As String

Declaring several variables in a single line

We can declare several variables in a single Dim statement. However, in Visual Basic, we cannot

assign a value to these variables at the same time.

Example:

Dim a, b, c As Single, x, y As Double, i As Integer

' a, b, and c are all Single; x and y are both Double

Scope of variables

The variable can be declared inside the Class or inside a Sub procedure. The variable is only

effective inside the Class or Sub structure. Once the given structure finishes execution, the

variable is deleted and its value is forgotten. Here is an example:

Page 24: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

3

Example: The following is a program with label Label1 and buttons Button1, Button2 and

Button3.

Public Class Form1 Dim x As Integer = 5 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim x As Integer x = 8 Label1.Text = x End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Label1.Text = x End Sub

Page 25: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

4

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click x = 12 Label1.Text = x End Sub End Class

Now the program is run and the buttons is pressed step by step as follows. Determine the

value of Label1.Text after each step:

Value of Label1.Text Action Step Run the program. 1

Click Button1. 2

Click Button2. 3

Click Button3. 4

Click Button1. 5

Click Button2. 6

Operators and Expressions

Arithmetic Operators

Here is a list of the arithmetic operators in Visual Basic 2012. You should get yourself familiar

with the operators “\” and “Mod” before examinations.

Page 26: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

5

Relational Operators

Relational operators (or comparison operators) are the equality signs and inequality signs in

Mathematics. If the equality or the inequality is satisfied, then the result is True, otherwise the

result is False. Here is the list of the relational operators:

Logical Operators Sometimes we might need to make more than one comparisons before a decision can be made. In this case, using numerical comparison operators alone is not sufficient; we need to use the logical operators.

Operator Description

And Both sides must be true

Or One side or other must be true

Xor One side or other must be true but not both

Not Negates true

Page 27: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

6

Constants

It is a space in memory filled with fixed value that will not be changed.

Constant may be declared as:

Const constant name = value

Example: Declare x as a constant (P), then compute the area of a circle. Put suitable design. Sol: Public Class Form1 Const p = 3.14159 Dim a, r As Single Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click r = Val(TextBox1.Text) a = r ^ 2 * p MsgBox("area=" & a) TextBox1.Text = " " End Sub End Class Inputting variables There are methods to input variable x as stated in the following:

Method of Input For all type of variable In textbox tool X=textbox1.text

In label tool X=label1.text

In input box X=inputbox("prompt","title") Note: To enter many variables we usually use the third method with loop. Outputting variables There are methods to output variable x as stated in the following:

Method of output For all type of variable to textbox tool Textbox1.text =X

to label tool Label1.text=x

By message box msgbox (x)

Or msgbox ("remark"& x)

Page 28: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

7

Functions for variables The numeric and string variables are the most common used variables in programming, therefore V.B provides the user with many functions to be used with a variable to perform certain operations or type convention. The most common functions for numerical variable x

The Mid Function The Mid function is used to retrieve a part of the text from a given phrase. The syntax of the Mid Function is

Mid(phrase, position,n)

*phrase is the string from which a part of the text is to be retrieved *position is the starting position of the phrase from which the retrieving process begins.

number of characters to retrieve. *n is the Example: Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim myPhrase As String myPhrase = InputBox("Enter your phrase") Label1.Text = Mid(myPhrase, 2, 6)

Sub End * This program will extract text starting from position 2 of the phrase and the number of characters extracted is 6.

The figures are shown below:

Page 29: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

8

The Right Function The Right function extracts the right portion of a phrase. The format is

Microsoft.Visualbasic.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: Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim myword As String myword = TextBox1.Text Label1.Text = Microsoft.VisualBasic.Right(myword, 4) End Sub

The Left Function

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

Microsoft.Visualbasic.left ("Phrase", n)

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

The Trim Function

The Trim function trims the empty spaces on both sides of the phrase. The format is

Trim("Phrase")

Page 30: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

9

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim myPhrase As String myPhrase = Microsoft.VisualBasic.InputBox("Enter your phrase") Label1.Text = Trim(myPhrase) End Sub

The Ltrim Function

The Ltrim function trims the empty spaces of the left portion of the phrase. The format is

Ltrim("Phrase")

For example,

Ltrim (" Visual Basic 2012")= Visual basic 2012

The Rtrim Function

The Rtrim function trims the empty spaces of the right portion of the phrase. The format is

Rtrim("Phrase")

For example:

Rtrim ("Visual Basic 2012 ") = Visual Basic 2012

Page 31: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

10

The Ucase and the Lcase Functions

The Ucase function converts all the characters of a string to capital letters. On the other hand, the Lcase function converts all the characters of a string to small letters. The syntax is

Microsoft.VisualBasic.UCase(Phrase)

Microsoft.VisualBasic.LCase(Phrase)

For example,

Microsoft.VisualBasic.Ucase("Visual Basic") =VISUAL BASIC

Microsoft.VisualBasic.Lcase("Visual Basic") =visual basic

The Abs function The Abs function returns the absolute value of a given number. The syntax is

Math. Abs (number)

Example:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim x, y As Integer x = TextBox1.Text y = Math.Abs(x) Label1.Text = y End Sub

The Int Function The Int is a function that converts a number into an integer by truncating its decimal part and the resulting integer is the largest integer that is smaller than he number. For example Int(2.4)=2, Int(6.9)=6 , Int(-5.7)=-6, Int(-99.8)=-100 Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim x, y As String x = TextBox1.Text y = Int(x) Label1.Text = y End sub

Page 32: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

11

The Len Function

Number of character of variable x Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim x, y As String x = TextBox1.Text y = Len(x) Label1.Text = y

End Sub

Using the If control structure with the Comparison Operators To effectively control the Visual Basic 2012 program flow, we shall use the If control structure together with the conditional operators and logical operators. There are basically three types of If control structures, namely If….Then statement, If….Then…Else statement and If….Then….ElseIf statement.

(A) If….Then statement

If condition Then Statement1 Statement2 ... End If

Example1 :

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

Page 33: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

12

If myNumber > 100 Then Label1.Text = " You win a lucky prize" End If End Sub

(B) If...Then...Else Statement If condition Then Statement1 Statement2 ... Else Statement3 Statement4 ... End If Example2: write a program to enter a mark of a student then print (pass) if he successful.

Sol: Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim marks As Integer Dim result As String marks = Val(InputBox("Enter the marks:")) If marks >= 50 Then result = "Pass" Else result = "Fail" End If MsgBox(result) End Sub (C) If...Then...ElseIf Statement If condition1 Then Statement1 ... ElseIf condition2 Then Statement2 ... (more ElseIf conditionals if applicable) Else Statement3

Page 34: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

13

End If Exercise1: This program use the logical operator And besides the conditional operators. This means that both the conditions must be fulfilled in order for the conditions to be true, otherwise, the second block of code will be executed. In this exercise, 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.

Example3: write a program to give the evaluation for different marks as follows:

Mark Evaluation

>=80 A

>=70 B

>=50 C

<50 D

Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim marks As Integer Dim grade As String marks = Val(InputBox("Enter the marks:")) If marks >= 80 Then grade = "A" ElseIf marks >= 70 Then grade = "B" ElseIf marks >= 50 Then grade = "C" Else grade = "D" End If MsgBox("Your grade is: " & grade) End Sub End Class

Exercise2: Write a program to classify any entered number according to its sign and display the phrase (negative number) when the number is negative and the phrase (positive number) when the number is positive, otherwise display the phrase (neither positive nor negative).

Page 35: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

14

Select statement Used for applying many statements depending on one variable. The general form is:

Select case variable

Case value1

statements

Case value2

Statements

...

Case value n

Statements

Case else

Statements

End select

Example4: write a program to print the days of the week when we enter its number

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim x As Integer x = (TextBox1.Text) Select x Case 1 MsgBox("Sunday") Case 2 MsgBox("Monday") Case 3 MsgBox("Tuesday") Case 4 MsgBox("Thursday") Case 5 MsgBox("Wednesday") Case 6 MsgBox("Friday") Case 7 MsgBox("Saturday") End Select End Sub

Example5: write a program to give the evaluation for different marks as follows:

Page 36: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

15

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles

Button2.Click

'Examination Marks Dim mark As Single mark = TextBox1.Text Select Case mark Case 0 To 49 Label1.Text = "E" Case 50 To 59 Label1.Text = "D" Case 60 To 69 Label1.Text = "C" Case 70 To 79 Label1.Text = "B" Case 80 To 100 Label1.Text = "A" Case Else Label1.Text = "Error, please reenter the mark" End Select End Sub

Page 37: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

16

Loop statement: Visual basic supports statement to perform loops. The loops statements could have different structures as follows: 1- Counter loop. 2- Conditional loop. 1- Counter loop: Loops apply programming statements for fixed number of times using counter (for… next) statement. The general form is: For variable = start value to end value step step value Statements Next variable Example6: Write a program to print (hello) five times. Sol: Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click For i = 1 To 5 ListBox1.Items.Add("hello") Next i End Sub

Page 38: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

17

Example7: Write a program to print even numbers from 1 to 10. Sol:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click For i = 2 To 10 Step 2 ListBox1.Items.Add(i) Next i End Sub

Exercise4

Write a program to print odd numbers from 1 to 10.

Conditional loop Loops repeat programming statements according to specific condition. There are two types of conditional loop: 1- Do while 2- Do until 1-Do while loop: In this loop the statements will be implemented and repeated when ever the condition satisfied. The general form is: Do while condition Statements Loop

Page 39: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

18

Example8: Write a program to print (hello) five times with its numbering using do while loop. Sol:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim i As Integer i = 1 Do While i <= 5 ListBox1.Items.Add("hello") i = i + 1 Loop End Sub

Example9: Write a program to print even numbers from 1 to 10.

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim i As Integer i = 2 Do While i <= 10 ListBox1.Items.Add(i) i = i + 2 Loop End Sub

Do until loop: In this loop the statements will be implemented and repeated when ever the condition not satisfied, (i.e) the loop will be stopped when the condition satisfied. The general form is: Do until condition Statements Loop

Example10: Write a program to print (hello) five times with its numbering using do until loop.

Sol:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim i As Integer i = 1 Do Until i > 5 ListBox1.Items.Add("hello") i = i + 1 Loop End Sub

Example11: Write a program to find the summation of undetermined number of positive numbers

such that the program will be stopped when we enter negative number.

Sol:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim sum, x As Integer

Page 40: Microsoft Visual Basic 2012 · Chapter 1 Introduction to Visual Basic 2012 1.1 A brief description of Visual Basic 2012 Visual Basic 2012 is a full-fledged Object-Oriented Programming

19

sum = 0 x = Val(InputBox("enter x", "summation")) Do While x >= 0 sum = sum + x x = Val(InputBox("enter x", "summation ")) ListBox1.Items.Add(sum) Loop End Sub

Example12: Write a program to find the summation of the numbers from 5 to 15. Sol:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim sum As Integer sum = 0 For i = 5 To 15 sum = sum + i Next i Label1.Text = "sum =" & CStr(sum) End Sub

Exercise5

Q1 : Write a program to find the summation of 10 numbers. For example if we entered the

numbers:

1, 5, -1, 3, 2, 0, -1, 3, 0, -4

Q2: Write a program to find the average of n numbers.