aga private institute for computer...
TRANSCRIPT
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 0
Aga Private Institute for computer Science
3rd Stage
Visual Basic.Net
2015-2016
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 1
Visual Basic (Chapter 1)
*What is computer programming Language?
Programming means designing a set of instruction to ask the computer to carry out certain
jobs that are very much faster and more efficient than human beings can do.
*The microchips of a CPU can only understand a combination of 0 and 1 code to
communicate with computer , a language that is called machine language .
* Interpreters and Compilers that can translate human language into machine language.
*Level of programing Language:- with Example ?
1-Low-Level Programming Language (LLL) ( Like: Machine Language)
2-High Level Programming Language (HLL) (Like:C,C++,VB,Java,….)
*What are the compiler and interpreter?
Compiler and interpreter both carry out the same purpose ,Convert a high level language
Like (C,C++,VB, Java…..) Instruction into binary form (Machine Language ) which is
understandable by computer hardware .
Compiler Interpreter
A compiler is a piece of that translate the
high level language into machine language.
1-Compiler takes Entire program as input
2-Speed of compiler is very fast .
3-Memory Requirement is more .
4-Errors are displayed after Entire
program is checked.
5-Example : C Compiler.
It converts the code into intermediate code
before converting it into machine code.
1-Interpreter single instruction as input
2-Speed is very slow .
3-Memory Requirement is less .
4-Errors are displayed for every instruction
interpreted .
5-Example : Basic .
* Integrated Development Environment (IDE)
* Microsoft Intermediate Language (MSIL)
* Common Language Runtime (CLR)
* Graphical User Interface (GUI)
* The Basic versions of visual basic :
1-Visual Basic 1.0 2-Visual Basic 1.0 for DOS
3-Visual basic 2.0 4-Visual Basic 3.0
5- Visual basic 4.0 6- Visual basic 5.0
7-Visual Basic 6.0 8-Visual basic.net
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 2
*Visual Basic is a high level programming language (HLL) fast and easy way to create
programs for Microsoft Windows.
“Visual” refers to the to the method used to create what the user sees-the graphical user
interface(GUI). “Basic” refers to the BASIC (Beginners All-Purpose Symbolic Instruction
Code) programming language .
*Microsoft Visual Basic.Net : is a programming environment used to create graphical use
interface (GUI) applications for the Microsoft Windows family of Operating systems.
VB.NET is the next generation of Visual Basic.
*What is integrated Development Environment (IDE):
The IDE is also commonly referred to as the design environment , or the program that assists
computer programmers to develop software or create our applications.
An IDE normally consists of source code editor, build automation tools and a debugger.
Chapter 2
1-Stracture of visual basic Application (Layout) Visual basic consists a number of
components :
*Menu Bar
*Tool Bar
*Project explorer
*Properties window
*Tool Box
*Form designer
-The Visual Basic Startup dialog box
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 3
-To start a new Visual Studio Express 2012 project, simply click on New Project to
launched The Visual Studio New Project page as shown below:
-Visual Basic Layout:
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 4
-The code window appear
A-Form :
Forms are the foundation for creating the interface of an application .You can use form to
add windows ,items and dialog boxes to your applications.
B-Toolbox Controls
The Toolbox contains
a set of controls /tools
that are needed for project design .
Control Description
Pointer Provides a way to move and resize the controls form
Picture Box Displays icons/bitmaps and meta files . Draws a box to display graphics
Text Box Used to display massage and enter text .
Frame Serves as visual and functional container for controls
Button Used to carry out the specified action when the user chooses it.
Cheek Box Display a true/false or yes/no option
Radio Button Option Button control which is a part of an option group allows the user to
select only one option even it displays multiple choices .
List Box Display a list of items from which a user can select one
Combo Box Contains a textbox and a list box. This allows the user to select an item
from the dropdown list box or to type in a selection in the text box
Timer Executes the timer events at specified intervals of time
Label Displays a text that the user cannot modify or interact with
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 5
-ln order to work with VB, we need to understand terminology as defined in below:
C- Properties Windows
The Properties Window exposes the various characteristics of selected objects. Each and
every form in an application is considered an object. Now, each object in Visual Basic has
characteristics such as color and size. All these characteristics of an object are called its
properties. Thus, a form has properties and any controls placed on it will have properties too.
All of these properties are displayed in the Properties Window.
D- Windows Forms Methods
The following are some of the commonly used methods of the Form class. You can refer to
Microsoft
documentation for a complete list of methods associated with forms control:
Terminology Definition
Object A thing - like a noun in English. Examples include forms and controls you
place on form such as buttons, text boxes, and icons.
Property Objects have properties - like adjectives in English. Properties describe
object behaviors. Examples of properties include Text,Name, BackColor,
Font, and Size. Refer
to a property by the notation Object Name.PropertyName (use the .dot
notation) —example: Total Due TextBox.Text or AccountLabe|.ForeCoIor.
Method Like a verb in English - these are the actions that objects exhibit. Examples
include methods to Show and Hide forms and methods to Print and Close
forms. Refer to a method with the notation ObjectName.MethodName -
example Me.Close will close the current form.
Event Events are actions usually triggered by the system user such as clicking a
button; however ,events can also be triggered by the actions of objects. For
example, closing a form can trigger an event.
Class It is a sort of template for an object. For example, all forms belong to the
Form class of object. All buttons belong to the Button class of object.
Classes include definitions for object properties, methods, and associated
events. Each class is assigned an identifying namespace within the .NET
Framework Class Library. Each new object you create is defined based on
its class -the new object is called a class instance.
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 6
#Method Name & Description
1-Activate :Activates the form and gives it focus.
2-BringToFront : Brings the control to the front of the Z-order.
3-Close : Closes the form.
4-Focus : Sets input focus to the control.
5-SendToBack : Sends the control to the back of the Z-order.
6-SetDesktopBounds : Sets the bounds of the form in desktop coordinates.
7-SetDesktopLocation :Sets the location of the form in desktop coordinates.
8-SetDisplayRectLocation : Positions the display window to the specified value.
9-Show : Displays the control to the user.
10-ShowDialog :Shows the form as a modal dialog box.
11-lsinputChar : Determines if a character is an input character that the control recognizes.
12-IsInputChar : Determines whether the specified key is a regular input key or a special
key that requires preprocessing.
E- Solution Explorer
Docked on the right side of the screen, just under the toolbar, is the Solution Explorer
window. All of the object that makes up the application are packed in a project. A simple
project will typically contain one form, which is a window that is designed as part of a
program ‘s interface. It is possible to develop any number of forms for use in a program,
although a program may consist of a single form. In addition to forms, the Solution Explorer
window also lists code modules and classes.
F- Windows Forms Events
The form and controls support events (generation, interaction with mouse and keyboard).
Examples of events are clicking a Button, entering text into Textbox, selecting an item in a
List box etc...
-The most important events in Visual basic are described in the following table:
Event Action taken when lt provide the following
integers
Click Single click on object
Double Click Double click on object
Mouse move Mouse pointer move on object Button, shift, X,Y
Key press Pressing a key of the keyboard Like:
TAB, ENTER, ESC, and Arrow keys
Key ASCII
Key Up Occurs when a key is released
while the control has focus.
Key ASCII
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 7
Key Down Occurs when a key is pressed
while the control has focus.
Key ASCII
Drag Drop Move object to another place Source, X,Y
Click Event Example:
Private Sub Button2 Click(sender As System.Object, e As System.Even1Args) Handles
Button2.Click
Close()
End Sub
Double Click Event Examgle:
Private Sub Form1 DoubleClick(sender As Object, e As System.EventArgs) Handles
Me.DoubleClick
Form2.Show()
End Sub
Mouse Move Event Example:
Private Sub Button2 MouseMove(sender As Object, e As
System.Windows.Forms.MouseEvenlArgs) Handles
Bulton2.MouseMove :
Button2.BackColor = Color.Pink
End Sub
Key Press Example :
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles
TextBox1.KeyPress
If e.KeyChar = Convert.ToChar(97) Then
MsgBox("You pressed a")
ElseIf e.KeyChar = Convert.ToChar(65) Then
MsgBox("You pressed A")
End If
End Sub
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 8
2- Steps of Development Application in Visual Basic?
There are three primary steps involved in building a visual basic application.
1- Draw user interface
2- Assign properties to control
3- Attach code to control
Example:
Design a form with one textbox and two Buttons. Write a code so when run project and click
on Button1 (OK) the word (Welcome) display in textbox1, and when click on Button2 (Exit)
close the program and return back to the form interface, and the Font Size is 12 Bold for all
elements/objects.
Solution:
a- Creating the interface:
Create the form then draw the following objects on the form.
1- Adding one Textbox to the form1.
2- Adding two Buttons (Button1 and Button2) to the form1.
b-Setting Properties :
The next step is to set properties for the objects. The properties window provides an easy
way to set properties for all objects on form. For this example, we’ll change three property
setting. Use the default setting fir all other properties .The three properties are (Name, Text
and Font).
c-Writing The Code :
The code consists of language statements, constants and declaration. To open the code
window, double click the form or control for which you choose to the code, or from the
Solution Explorer window select the name of a form and choose the view code button.
Choose the Button1 and type the following code:
Object Property Setting
Form1
Name Form1
Text Example1
Font Bold and size 12
Button1
Name Button1
Text OK
Font Bold and size 12
Button2
Name Button2
Text EXIT
Font Bold and size 12
Textbox1
Name Textbox1
Text (-) or (Empty)
Font Bold and size 12
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 9
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click TextBox1.Text = " Welcome " End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click End End Sub
Running the Application: To run the application, choose Debug from the menu, and then
click on Start Debug in or ( F5) ;
Saving the Project: Choosing save project from the file menu click on Save all.
Example2:
Design a form with three textbox, one Button and three Labels. Write a code in the
Button1(Execute). so when run project enter the First name in Textbox1 and Second name
inTextbox2. When click on Button1 (Execute) display both names (Full name) in the
Textbox3. And Font size is 14 Bold.
Solution :
a- Creating the interface:
Create the form then draw the following objects on the form2.
1- Adding three Textbox’s (TxtBox1, TxtBox2, TxtBox3) to the form2.
2- Adding one Button (Button1) to the form2.
3- Adding three Labels (Label1, Label2, Label3) to the form2.
B-Setting Properties : Bold and size 14
C-Writing Code :
Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click TextBox3.Text = TextBox1.Text + " " + TextBox2.Text End Sub End Class
Note : The statement END used to close the program runtime .
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 10
3-Data types :
The data types of a programming element refers to what kind of data it can hold and how it
stores that data . Every variable, literal, constant, enumeration(counting), property
(characteristic)return value has a data type.
*There are two major data types: the numeric data types and the non-numeric data types
1- Numeric data types: are types of data that consist of numbers, which can be computed
mathematically with various standard operators such as add, minus, multiply, divide
In Visual Basic 2012, numeric data are divided into 7 types, depending on the range of
values they can store:
# Type Storage Range of Values
1 Byte 1-byte 0 to 255
2 Integer 2-bytes – 32,768 to 32,767
3 Long 4-bytes – 2,147,483,648 to 2,147,483,647
4 Single 4-bytes
– 3.402823E38 to – 1.401298E – 45 (negative values)
1.401298E – 45 to 3.402823E38 (positive values)
// floating-point number//
5 Double 8-bytes
– 1.79769313486231E308 to
– 4.94065645841247E – 324 (negative values)
// floating-point number//
4.94065645841247E – 324 to 1.79769313486231E308
(positive values)
6 Currency 8-bytes – 922,337,203,685,477.5808 to 922,337,203,685,477.5807
//number with fixed decimal point//
7 Decimal 12-bytes
+/- 79,228,162,514,264,337,593,543,95O,335 if no decimal is
use
+/- 7.9228162514264337593543950335 (28 decimal places).
2- Non-numeric data types: are data that cannot be manipulated mathematically using
standard arithmetic operators. The non-numeric data comprises text or string data types, the
Boolean data types that store only two values (true or false), Object data type.
1-String : Use to store alphanumeric values. A variable length string can store
approximately 4 billion Characters (Size 10 Byte + String length )
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 11
2-Data: Use to store date and time values. A variable declared as date type can store both
date and time values and it can store date values 01/01/0100 up to 12/31/9999. (Size 8 byte)
3-Boolean:Boolean data types hold either a true or false value. These are not stored as
numeric values and cannot be used as such. Values are internally stored as: 1 (True) and 0
(False) and any non-zero value is considered as true. (Size 2 byte)
4- Variant: Stores any type of data and is the default Visual Basic data type. ln Visual Basic
if we declare a variable without any data type by default the data type is assigned as default.
(Size 16 byte)
5- Char: The Char variable type holds a single character (such as the letter 'B'). The value of
a Char can be any character. (Size 1 byte)
Example :
Dim x As Integer Dim B As Boolean Dim Y As Long Dim Strname As String Dim A As Double : Dim B As Double Dim Max As Single Dim Ch As Char Dim B As Boolean Dim Month As Date Dim D, E, F As String
4- Variable
A variable is a location in memory where a value can be stored during the execution of a
Visual Basic application, and that values may be: (Integer ( 23 ), Floating point number
(23.5),String ( Hello ) , Char ( H ) } and many other data type.
Using Variable: ln order to use variable in program it must first be declared.
Syntax:
Dim Variable [As Type]
Example:
Dim StrName As String Dim ChWord As Char Dim Number As Integer Dim Average As Double
Variable declared with the Dim statement within a procedure exit only as long as the
procedure is executing. When the procedure finishes the value of the variable disappears.
Assignment Statement: (Variable-Name = Expression )
as in the following example.
x= “Hawler" z=25 B = 7.5
Y= ‘H’ A=4*Z Sum = Number1 +Number2
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 12
Storing Information in Variables:
There are three steps to using a variable:
1. Declare the variable. Tell the program the name and kind of variable you want to use.
2. Assign the variable. Give the variable a value to hold.
3. Use the variable. Retrieve the value held in the variable and use it in your program.
The following are the rules when naming the variables in Visual Basic .
1- The name must be less than 255 characters
2.No spacing is allowed
3. The name must not begin with a number
4.Period is not permitted
Valid Name Invalid Name
My_Car My.Car
ThisYear 1newBoy
Long_Name_can_beUSE He&HisFather *&is not acceptable
5- The Assignment Statement in Visual Basic "‘
The Assignment Statement is used to assign values to a property of an object such as a
control. The value on the right side of the equal sign is assigned to the property of the object
on the left side of the equal sign.
*Object . Property = Value
Button1. Text = "HPCl-VB- Bock“
TextBox1. BackColor = Color. Red
LabeI1.Text= “Your Name“
*Object. Method:
Me. Close()
TexBox1. Clear()
Form2.Show()
7-Visual Basic Help
The Microsoft Developer Network (MSDN) library contains books and technical articles to
help you answer questions that will arise as you learn the VB language. This must be
installed on your computer in order for it to be available from the Help menu within VB.
View Help Ctrl +F1 Manage Help Setting Ctrl+Alt+F1
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 13
8-Operator in Visual Basic
*Arithmetical Operators :
*Relational Operator:
*Logical Operators:
Operators Description
OR Operation will be true if either of the operands is true
AND Operation will be true only if both the operands are true
9-Comment :
As you read the code examples, you often encounter the comment symbol ('). This symbol
tells the Visual Basic compiler to ignore the text following it, or the comment. Comments are
brief explanatory notes added to code for the benefit of those reading it.
' This is a comment beginning at the left edge of the screen.
TextBox1.Text = "Hi!" 'This is an inline comment.
Menu >> Edit >> Advanced >> ( Comment Selection; or Uncomment Selection ).
By Keyboard:
CTRL + K + C (comment); CTRL + K + U (uncomment).
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 14
10-Val Function:
Returns/Converts the numbers contained in a string to a numeric value of appropriate type.
Syntax:
Val ( string )
Example: Dim Myvalue MyValue = Val("2457") 'Returns 2457. MyValue = Va|(" 2 45 7") 'Returns 2457. 11-Message Box Function :
Displays a message in a dialog box, waits for the user to click a button, and then returns an
integer indicating which button the user clicked.
MsgBox(" Message ")
Parameters:
Prompt:Required. String expression displayed as the message in the dialog box. The
maximum length of Prompt is approximately 1024 characters, depending on the width of the
characters used.
Buttons: Optional. Numeric expression that is the sum of values specifying the number and
type of buttons to display, the icon style to use, the identity of the default button, and the
modality of the message box.
Title: Optional. String expression displayed in the title bar of the dialog box. The
MsgBoxStyle enumeration values:
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 15
The first group of values (0-7) describes the number and type of buttons displayed in the
dialog box. The second group (16, 32, 48, 64) describes the icon style.
Syntax:
MsgBox( msg,style,title )
MsgBox("Do you want to continue?", MsgBoxStyle.YesNo, "Cautions!")
Example :
Dim testMsg As Integer testMsg = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message") If testMsg = 6 Then MessageBox.Show("You have clicked the yes button") ElseIf testMsg = 7 Then MessageBox.Show("You have clicked the NO button") Else MessageBox.Show("You have clicked the Cancel button") End End If
Example2:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim r As Integer r = MessageBox.Show("Please Select Option ", "OPTION", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop) If r = DialogResult.Abort Then Label1.Text = "You Select Abort" ElseIf r = DialogResult.Ignore Then Label1.Text = "You select Ignore " ElseIf r = DialogResult.Retry Then Label1.Text = "You Select Retry" End If End Sub
12-InputBox Function :
ls used to input a value or character for one variable from keyboard at running stage, displays
a prompt in a dialog box, waits for the user to input text or click a button, and returns a
String containing the contents of the text box.
Syntax:
Variable-Name = inputBox ( “ Message “,“ Title " )
Example:
Dim x As Integer X = InputBox (" Enter vour student Number: ," Aga Private Institute ")
Example:
Sum of two Numbers by InputBox?
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 16
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim num1 As Integer Dim num2 As Integer Dim sum As Integer num1 = InputBox("Enter The First Number : ", "InputBox Massage ") num2 = InputBox("Enter The Second Number : ", "InputBox Massage ") sum = num1 + num2 TextBox1.Text = sum End Sub
More Example : Simple Calculator
4 buttons – 3 labels – 3 Textbox’s
--------------------------------------------------------------------------------------------------------------
Chapter 3
*Conditional Operators:
The conditional operators are powerful tools that resemble mathematical operators . These
operators allow to compare data values and then decide what actions to take.
“+” Button
Dim x, y, z As Double
x = TextBox1.Text
y = TextBox2.Text
z = x + y
TextBox3.Text = z
“-” Button
Dim x, y, z As Double
x = TextBox1.Text
y = TextBox2.Text
z = x - y
TextBox3.Text = z
“*” Button
Dim x, y, z As Double
x = TextBox1.Text
y = TextBox2.Text
z = x * y
TextBox3.Text = z
“/” Button
Dim x, y, z As Double
x = TextBox1.Text
y = TextBox2.Text
z = x + y
TextBox3.Text = z
“Clear” Button
TextBox1.Text=””
TextBox2.Text=””
TextBox3.Text=””
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 17
*Logical Operators
Sometimes we might need to make more than one comparisons 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 known as the logical operators. The logical
operators are shown in Table :
*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:
A-If….Then statement.
B-If….Then… Else statement.
C-If….Then….ElseIf statement.
A- If….Then Statement
This is the simplest control structure which ask the computer to perform a certain action
specified by the Visual Basic 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
Visual Basic expression
End If
Example
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim x As Integer x = TextBox1.Text If x > 100 Then Label1.Text = " You win a lucky prize" End If End Sub
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 18
B- If….Then…Else Statement
Using only If….Then statement is not very useful in programming and it does not provide
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 Visual Basic expression if the condition is true. And when the condition is false ,an
alternative action will be executed. The general format for the if…then.. Else statement is:
If condition Then
Visual Basic expression
Else
Visual Basic expression
End If
Example1:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim myNumber As Integer myNumber = TextBox1.Text If myNumber > 100 Then Label1.Text = " Congratulation! You win a lucky prize" Else Label1.Text = " Sorry, You didn't win any prize " End If End Sub
Example2:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim myNumber, MyAge As Integer myNumber = TextBox1.Text MyAge = TextBox2.Text If myNumber > 100 And MyAge > 60 Then Label1.Text = " Congratulation! You win a lucky prize" Else Label1.Text = " Sorry, You did not win any prize" End If End Sub
C- If….Then…ElseIf Statement
If there are more than two alternative choices, using jus If….Then….Else statement will not
be enough. In order to provide more choices, we can use the If….Then…ElseIf Statement.
executed. The general format for the if…then.. Else statement is:
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 19
If condition Then
Visual Basic expression
ElseIf condition Then
Visual Basic expression
ElseIf condition Then
Visual Basic expression
Else
Visual Basic expression
End If
Example :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim Mark As Integer Mark = TextBox1.Text If Mark >= 80 Then TextBox2.Text = "A" ElseIf Mark >= 60 And Mark < 80 Then TextBox2.Text = "B" ElseIf Mark >= 40 And Mark < 60 Then TextBox2.Text = "C" Else TextBox2.Text = "D" End If End Sub
*The Select Case…End Select Structure
The syntax of the Select Case control structure is as follows:
Select Case test expression
Case expression list 1
Block of one or more Visual Basic statements
Case expression list 2
Block of one or more Visual Basic Statements
Case expression list 3
Block of one or more Visual Basic statements
Case expression list 4
.
.
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 20
.
Case Else
Block of one or more Visual Basic 2010 Statements
End Select
Example1:
Grades in high school are usually presented with a single capital letter such as A, B, C, D or
E. The grades can be computed as follow:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim Mark As Single Mark = TextBox1.Text Select Case Mark Case 0 To 49 TextBox2.Text = "E" Case 50 To 59 TextBox2.Text = "D" Case 60 To 69 TextBox2.Text = "C" Case 70 To 79 TextBox2.Text = "B" Case 80 To 89 TextBox2.Text = "A" Case 90 To 100 TextBox2.Text = " Very Good " Case Else TextBox2.Text = "Error Please Re Enter The Mark" End Select
Example2: Advanced Calculator
Public Class Form1 'Declaration. Dim x, y As Double Dim op As Char Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load End Sub ------------------------------------------------------------------------------------- Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click TextBox1.Text = TextBox1.Text & "1" End Sub ------------------------------------------------------------------------------------ Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click TextBox1.Text = TextBox1.Text & "2" End Sub --------------------------------------------------------------------------------------- Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click TextBox1.Text = TextBox1.Text & "3" End Sub ------------------------------------------------------------------------------------- Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click TextBox1.Text = TextBox1.Text & "4" End Sub --------------------------------------------------------------------------------------
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 21
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click TextBox1.Text = TextBox1.Text & "5" End Sub ---------------------------------------------------------------------------------------- Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click TextBox1.Text = TextBox1.Text & "6" End Sub Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click TextBox1.Text = TextBox1.Text & "7" End Sub ------------------------------------------------------------------------------------- Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click TextBox1.Text = TextBox1.Text & "8" End Sub --------------------------------------------------------------------------------------- Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click TextBox1.Text = TextBox1.Text & "9" End Sub ---------------------------------------------------------------------------------------- Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click TextBox1.Text = TextBox1.Text & "0" End Sub ------------------------------------------------------------------------------------------ Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click TextBox1.Text = TextBox1.Text & "." End Sub ----------------------------------------------------------------------------------------- Private Sub Button17_Click(sender As Object, e As EventArgs) Handles Button17.Click 'Clear Button. TextBox1.Text = " " End Sub ----------------------------------------------------------------------------------------- Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click '+ Button. x = TextBox1.Text op = "+" TextBox1.Text = "" End Sub ----------------------------------------------------------------------------------------- Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click '-Button. x = TextBox1.Text op = "-" TextBox1.Text = "" End Sub ---------------------------------------------------------------------------------------- Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click '* Button. x = TextBox1.Text op = "*" TextBox1.Text = "" End Sub ----------------------------------------------------------------------------------------- Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click 'Button. x = TextBox1.Text op = "/" TextBox1.Text = "" End Sub -------------------------------------------------------------------------
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 22
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click '= Button. y = TextBox1.Text Select Case op Case "+" TextBox1.Text = x + y Case "-" TextBox1.Text = x - y Case "*" TextBox1.Text = x * y Case "/" TextBox1.Text = x / y End Select End Sub -------------------------------------------------------------------------------------------------- Private Sub Button18_Click(sender As Object, e As EventArgs) Handles Button18.Click 'Exponential . TextBox1.Text = TextBox1.Text ^ 2 End Sub --------------------------------------------------------------------------------------- Private Sub Button19_Click(sender As Object, e As EventArgs) Handles Button19.Click '-/+ Button. TextBox1.Text = TextBox1.Text & "-" End Sub End Class
Example3:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Select Case TextBox1.Text Case "1" MsgBox("One") Case "2" MsgBox("Two") Case "3" MsgBox("Three") Case Else MsgBox("Enter a value from 1 to 3 ") End Select End Sub
-------------------------------------------------------------------------------------------------------------
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click If TextBox1.Text = "1" Then MsgBox("One") ElseIf TextBox1.Text = "2" Then MsgBox("Two") ElseIf TextBox1.Text = "3" Then MsgBox("Three") End If End Sub
---------------------------------------------------------------------------------------------
Q: How to save project as executable File ?
1-Go To File Menu >> Save All
2-Go to Build Menu >> Build (Name Of Project) For Example (Build Calculator)
3-Go to Documents >> Visual Studio 2012 Folder >>Calculator>>bin>>Debug>>Calculator.exe
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 23
2-Looping:
In VB programming, a sequence of instructions that is repeated until a certain condition is
met is called looping. For example, we can write VB code that adds a series of numbers
until the sum exceeds a certain value,
-we have three types of Loops, they are:
1- For…..Next loop,
2- While…..End while loop
3- Do loop.
A-The For ….Next Loop:
The For … Next Loop is another way to make loops in visual basic .
The Format is:
For counter = StartNumber to EndNumber
One or more visual Basic statements
Next
To exit a for…. Next loop you can place exit for statements within the loop, and it is
normally used together with the if ….. then .
Example1 :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim counter As Integer For counter = 1 To 10 Step 2 ListBox1.Items.Add(counter) Next End Sub
Example2 :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click For var = 1 To 5 MsgBox("Message Box Shows: " & var & "Times ") Next var End Sub
Example3:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim number As Integer For number = 1 To 10 If number = 5 Then MsgBox("This is Number 5,Don't Print it ") Else TextBox1.Text = TextBox1.Text & number & "," End If Next End Sub
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 24
B. While... End While Statement:
The While....End While Statement runs a series of statements as long as a given condition is
True.
Example1:
The statements in the loop continue to run until the index
variable is greater-than 15.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim counter As Integer Do While counter <= 15 TextBox1.Text &= counter counter += 1 Loop
End Sub
Output: 0123456789101112131415
Example2:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim i As Integer = 0 While i < 15 MsgBox("MessageBox:" & i) i += 14 End While End Sub
End Class
C. Do While... Loop Statement:
The Do While...Loop is used to execute statements until a certain condition is met. The
following Do Loop counts from 1 to 30.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim number As Integer Number = 1 Do While number <= 30 number = number + 2 TextBox1.Text &= number Loop End Sub
A variable number is initialized to 1 and then the Do While Loop starts. First, the condition
is tested; if condition is True, then the statements are executed. When it gets to the Loop it
goes back to the Do and tests condition again. If condition is False on the first pass, the
statements are never executed.
D. Do...Loop While Statement:
The Do...Loop While statement first executes the statements and then test the condition after
each execution. The following program block illustrates the structure:
Visual Basic 2012 By : Sarwar Saber & Fareed Suliman 2015-2016 P a g e | 25
Example1:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim number As Long number = 0 Do number = number + 1 TextBox1.Text & = number Loop While number < 10 End Sub
The programs executes the statements between Do and Loop While structure in any case.
Then it determines whether the counter is less than 10. if so, the program again executes the
statements between Do and Loop While else exits the Loop.