2.BYTE: Visual Basic
2.BYTE: Visual Basic
2.BYTE: Visual Basic
IDE stands for Integrated Development Environment. It is a War etc. If you are in business, you can also create business
programming environment that contains a lot of things in a single applications such as inventory management system , Amortization
package i.e. code editor, compiler, debugger and what you see is what Calculator , investments calculator, point-of-sale system, payroll
you get (WYCIWYG). It is actually a software application that provides system, accounting program and more to help manage your business
comprehensive facilities to computer programmers for software and increase productivity. For those of you who like games , you can
development. It combines all the basic tools that developers need to create programs such as slot machine, reversi, tic tac toe and more.
write or test software. This type of environment allows an application Besides, you can create multimedia programs such as Smart Audio
developer to write code while compiling, debugging and executing it at Player, Multimedia Player and more Visual Basic Data Types
the same place. It can be a standalone application or a part of one or In Visual Basic, Data Types are useful to define a type of data the
more compatible applications. variable can hold, such as integer, float, string, etc., in our application.
For example: The IDE for developing .NET applications is Microsoft Visual Basic is a Strongly Typed programming language. Before we
Visual Studio and IDE for developing Java Application is Eclipse, perform any operation on a variable, it’s mandatory to define a variable
NetBeans, JDeveloper, MyEclipse, BlueJ, RSA etc. with a required data type to indicate what type of data the variable can
In an Integrated development environment we can develop, run ,test, hold in our application.
and debug our application that is, an IDE has three distinct states - DATATYPES IN VISUAL BASIC
Design, Run, Debug. The visual basic provide an IDE which also has 1.Boolean Data type
three distinct state, the current state appear in the title bar. The VB IDE Holds values that can be only True or False. The
composed of these parts:- 1.The menu bar 2.The tool bar 3.The keywords True and False correspond to the two
project explorer 4.The properties window 5.The form layout window states of Boolean variables.
6.The tool box 7.The form designer 8.The code window Dim male As Boolean
An IDE typically contains a code editor, a compiler or interpreter, and a
2.BYTE
debugger, accessed through a single graphical user interface (GUI).
Holds unsigned 8-bit (1-byte) integers that range in value from 0
The user writes and edits source code in the code editor. The compiler
through 255.
translates the source code into a readable language that is executable
Dim byteValue As Byte = 201
for a computer. And the debugger tests the software to solve any
3.Char Data Type
issues or bugs.
Holds unsigned 16-bit (2-byte) code points ranging in value from 0
Subversion.
through 65535. Each code point, or character code, represents a single
Unicode character.
VISUAL BASIC Dim charVar As Char
In the early days of computer programming even a single program 4.Date Data Type
could take days or even weeks to complete. When Visual Basic was Holds IEEE 64-bit (8-byte) values that represent dates ranging from
first introduced in 1991, it revolutionized programming we no longer January 1 of the year 0001 through December 31 of the year 9999,
needed to write code to create a user interface, and we no longer and times from 12:00:00 AM (midnight) through 11:59:59.9999999 PM.
needed to worry about memory management. This new way of Each increment represents 100 nanoseconds of elapsed time since
programming was known as Rabid Application Development, or RAD. the beginning of January 1 of the year 1 in the Gregorian calendar.
The main benefit of RAD programming is increased productivity – The maximum value represents 100 nanoseconds before the
Visual Basic of 6.0 has many features that can help us to create better beginning of January 1 of the year 10000.
applications, faster than ever before, the following are few of features1. Dim someDateAndTime As Date = #8/13/2002 12:14
Code snipper ->small block 2. Development with Mg 3. Intelligence. PM# 5.Integer data type
Visual Basic is the fastest and easiest way to create single user The Integer data type provides optimal performance on a 32-bit
applications for Microsoft Windows. It is an Object-Oriented processor. The other integral types are slower to load and store from
Programming development system for creating applications that run and to memory.
under any of the Microsoft Windows Environment. In the name Visual The default value of Integer is 0.
Basic, 8Visual9 part refers to the method used to create the Graphical Dim intValue1 As Integer = 90946
User Interface. The 8Basic9 part refers to the Basic programming 6.Decimal Data Type
language, as its basic syntax of statements, is retained by Visual Holds signed 128-bit (16-byte) values representing 96-bit (12-byte)
Basic. Visual Basic is an event driven programming language. This integer numbers scaled by a variable power of 10. The scaling factor
means that code is executed as a response to an event. specifies the number of digits to the right of the decimal point; it ranges
Visual Basic is the fastest and easiest way to create single user from 0 through 28. With a scale of 0 (no decimal places), the largest
applications for Microsoft Windows. It is an Object-Oriented possible value is +/-79,228,162,514,264,337,593,543,950,335 (+/-
Programming development system for creating applications that run 7.9228162514264337593543950335E+28). With 28 decimal places,
under any of the Microsoft Windows Environment. In the name Visual the largest value is +/-7.9228162514264337593543950335, and the
Basic, 8Visual9 part refers to the method used to create the Graphical smallest nonzero value is +/-0.0000000000000000000000000001 (+/-
User Interface. The 8Basic9 part refers to the Basic programming 1E-28).
language, as its basic syntax of statements, is retained by Visual Dim d1, d2, d3, d4 As Decimal
Basic. Visual Basic is an event driven programming language. This 7.Double Data Type
means that code is executed as a response to an event. Holds signed IEEE 64-bit (8-byte) double-precision floating-point
Visual Basic is a third-generation event-driven programming language
numbers that range in value from -1.79769313486231570E+308
first released by Microsoft in 1991. It evolved from the earlier DOS through -4.94065645841246544E-324 for negative values and from
version called BASIC. BASIC means Beginners' All-purpose Symbolic 4.94065645841246544E-324 through 1.79769313486231570E+308
Instruction Code. Since then Microsoft has released many versions of for positive values. Double-precision numbers store an approximation
Visual Basic, from Visual Basic 1.0 to the final version Visual Basic of a real number.
6.0. Visual Basic is a user-friendly programming language designed for
Dim dub As Double = 4.0R
beginners, and it enables anyone to develop GUI window applications
8.Long data type
easily.
Holds signed 64-bit (8-byte) integers ranging in value from -
In 2002, Microsoft released Visual Basic.NET(VB.NET) to replace
9,223,372,036,854,775,808 through 9,223,372,036,854,775,807
Visual Basic 6. Thereafter, Microsoft declared VB6 a legacy
(9.2...E+18).
programming language in 2008. Fortunately, Microsoft still provides
Dim longValue1 As Long =
some form of support for VB6. VB.NET is a fully object-oriented
4294967296 9.Object Data Type
programming language implemented in the .NET Framework. It was
Holds addresses that refer to objects. You can assign any reference
created to cater for the development of the web as well as mobile
type (string, array, class, or interface) to an Object variable. An Object
applications. However, many developers still favor Visual Basic 6.0
variable can also refer to data of any value type (numeric, Boolean,
over its successor Visual Basic.NET.
Char, Date, structure, or enumeration).
In VB 6, you can create any program depending on your objective. For
Dim myObject As Object
math teachers, you can create mathematical programs such
10.SByte data type
as Geometric Progression, Quadratic Equation Solver, Simultaneous
Holds signed 8-bit (1-byte) integers that range in value from -128
Equation Solver ,Prime Number Tester, Factors Finder, Quadratic
through 127.
Function Graph Plotter and so on. For science teachers, you can create
Dim sbyteValue1 As SByte = -102
11.Short data type of the reference is passed. Because a copy is passed in mutations to
Holds signed 16-bit (2-byte) integers that range in value from -32,768 the parameter via = it won't be visible to the calling function . If you
through 32,767. pass value, it's the same as if another variable is created at the
Dim shortValue1 As Short = 1034 method, so even if you modify it, the original variable (at the call site)
12.Single Data Type won't have its value changed.
Holds signed IEEE 32-bit (4-byte) single-precision floating-point Call By Reference
numbers ranging in value from -3.4028235E+38 through -1.401298E- Call by reference means that a reference to the original value will be
45 for negative values and from 1.401298E-45 through sent to the function. It's almost like the original value is being directly
3.4028235E+38 for positive values. Single-precision numbers store an used within the function. Operations like = will affect the original value
approximation of a real number. and be immediately visible in the calling function . If you pass in a
13.String Data Type reference, when you modify the value in the method, the variable in the
Holds sequences of unsigned 16-bit (2-byte) code points that range in call site will also be modified.
value from 0 through 65535. Each code point, or character code, The default in Visual Basic is to pass arguments by value . You can
represents a single Unicode character. A string can contain from 0 to make your code easier to read by using the ByVal keyword. It is good
approximately two billion (2 ^ 31) Unicode characters. programming practice to include either the ByVal or ByRef keyword
Dim h As String = "Hello" with every declared parameter.
14.UInteger data type
The UInteger data type provides the largest unsigned value in the What is the difference between call by value and call by
most efficient data width. reference? Call by reference
The default value of UInteger is 0. 1. When we pass arguments to a procedure by reference, you’re
Dim uintValue1 As UInteger = actually passing the variable itself.
3000000000ui 15.ULong data type 2. Any changes made to the argument by the procedure will be
Holds unsigned 64-bit (8-byte) integers ranging in value from 0 through permanent
18,446,744,073,709,551,615 (more than 1.84 times 10 ^ 19). 3. The arguments can be passed by reference using the ByRef
Dim ulongValue1 As ULong = keyword or by omitting any qualifier.
7934076125 16.UShort data type 4. Arguments passed by reference can be modified by the called
Holds unsigned 16-bit (2-byte) integers ranging in value from 0 through procedure and the caller can read the modified value back.
65,535. 5. If the procedure changes the value, the change in the value gets
Dim ushortValue1 As UShort = 65034 reflected to the data.
Call by value
Event-driven Programming 1.When we pass arguments by value, the procedure gets the copy of
The event-driven programming revolves around recognizing the the variable, which is discarded when the procedure ends.
occurrences of events and then responding to those events by taking 2. Any changes made to the arguments by the procedure won’t affect
appropriate actions. In event-driven programming an application is the variable of the calling program.
build up as a series of responses to user-events. 3. The arguments can be passed by value using the ByVal keyword.
Event-driven programming is a programming paradigm in which the 4. Changes to arguments passed by value are never propagated back
flow of program execution is determined by events - for example a to the caller.
user action such as a mouse click, key press, or a message from the 5. If the procedure changes the value, the change affects only the copy
operating system or another program. An event-driven application is and not the variable itself.
designed to detect events as they occur, and then deal with them
using an appropriate event-handling procedure. The idea is an ARRAY IN VISUAL BASIC
extension of interrupt-driven programming of the kind found in early an array is a variable with a single name that represents many different
command-line environments such as DOS, and in embedded systems items. When we work with a single item, we only need to use one variable.
(where the application is implemented as firmware). However, if we have a list of items which are of similar type to deal with, we
Event-driven programs can be written in any programming language, need to declare an array of variables instead of using a variable for each
although some languages(Visual Basic for example) are specifically item. For example, if we need to enter one hundred names, it is difficult to
designed to facilitate event-driven programming, and provide an declare 100 different names. Besides, if we want to process those data that
integrated development environment (IDE) that partially automates the involves decision making, we might have to use hundreds of if...then
production of code, and provides a comprehensive selection of built-in statements, this is a waste of time and efforts.So, instead of declaring one
objects and controls, each of which can respond to a range of events. hundred different variables, we need to declare only one array. We
Virtually all object-oriented and visual languages support event-driven differentiate each item in the array by using subscript, the index value of
programming. Visual Basic, Visual C++ and Java are examples of each item, for example, name(1), name(2), name(3) .......etc. , makes
such languages. declaring variables more streamline.
A visual programming IDE such as VB.Net provides much of the code Arrays occupy space in memory. The programmer specifies the array
for detecting events automatically when a new application is created. type and the number of elements required by the array so that the
The programmer can therefore concentrate on issues such as compiler may reserve the appropriate amount of memory. Arrays may
interface design, which involves adding controls such as command be declared as Public (in a code module), module or local. Module
buttons, text boxes, and labels to standard forms (a form represents an arrays are declared in the general declarations using keyword Dim or
application's workspace or window). Once the user interface is Private. Local arrays are declared in a procedure using Dim or Static.
substantially complete, the programmer can add event-handling code Array must be declared explicitly with keyword "As".
to each control as required. STATIC ARRAY
Basically, you can create either static or dynamic arrays. Static arrays
“call by value” and “call by reference” function call? must include a fixed number of items, and this number must be known
Let's say we have an integer variable named x. A call to a function by value at compile time so that the compiler can set aside the necessary
using x means (a copy of) the value that x stores is passed in the function amount of memory. You create a static array using a Dim statement
call and no matter what the function does with that value, the value stored with a constant argument:
in x remains unchanged. A call to a function by reference using x means a Array is dimensioned during design time.
reference (also called a pointer or alias) to the variable x is passed in the Array size cannot be changed.
function call and so any changes the function makes using this reference By using erase function, only array element values in the memory
will actually change the value stored in x. will be emptied, elements memory will not be deleted.
When referencing something by ByVal in our method we are only Memory is fixed during design time.
taking a 'copy' of the value, so any changes are only made to our copy.
When using the ByRef we are taking the reference of our object so any Visual Basic starts indexing the array with 0. Therefore, the preceding
changes made are made to the actual object. array holds 101 items.
Call By Value Dim intData() As Integer = {1, 2, 3, 4, 5}
Call by value means that a copy of copy of the provided value will be Dim intData(5) As Integer
sent to the function. For value types (Integer, Single, etc.) this will Dim array_name() As String = {"Peter", "John", "Brock", "James", "Mari
provide a shallow copy of the value. With larger types this can be a"}
inefficient. For reference types though (String, class instances) a copy Dim misc() as Object = {"Hello friends", 16c, 12ui, "A"c}
Dim Emp(0 to 2) As String You can populate the list box items either from the properties window
Emp{0} = "Mathew" or at runtime. To add items to a ComboBox, select the ComboBox
Emp(1) = " Anthony" control and go to the properties window for the properties of this
Emp(2) = "Prince" control. Click the ellipses (...) button next to the Items property. This
DYNAMIC ARRAY opens the String Collection Editor dialog box, where you can enter the
Sometimes we may not know how large to make an array. Instead of values one at a line
making it large enough to hold the maximum of data (which means the Properties of the ComboBox
most of the array may be empty) we can declare a dynamic array. The Control 1.AllowSelection
size of a dynamic array can vary during the course of the program, or Gets a value indicating whether the list enables selection of list
we might need an array until the user has entered a bunch of data and items. 2.AutoCompleteCustomSource
the application has processed it and displayed the results. Gets or sets a custom System.Collections .Specialized.StringCollection to
Array is dimensioned during runtime use when the AutoCompleteSourceproperty is set to CustomSource.
Array size can be changed (Shrink or Enlarge) any number of 3.AutoCompleteMode
times. Gets or sets an option that controls how automatic completion works
By using erase function, both array element values and for the ComboBox.
elements memory will be deleted. 4.AutoCompleteSource
We can utilise the memory efficiently. Gets or sets a value specifying the source of complete strings used for
automatic completion.
The first step in declaring a dynamic array is by using the Dim 5.DataBindings
statement without specifying the dimenson list, as follows: Gets the data bindings for the control.
“ Dim myArray()” 6.DataManager
Then at run time we can specify the actual array size using the ReDim Gets the CurrencyManager associated with this control.
statement,as follows: 7.DataSource
“ ReDim myArray(1 to n) when n is decided during run time “ Gets or sets the data source for this ComboBox.
You can also declare a two dimensional array using ReDim statement, 8.DropDownHeight
as follows: Gets or sets the height in pixels of the drop-down portion of the
“ReDim myArray(1 to n, 1 to m) “ when m and n are known during ComboBox.
run time 9.DropDownStyle
With a dynamic array, we can discard the data and return the Gets or sets a value specifying the style of the combo box.
resources if occupied the system. Example:= 10.DropDownWidth
Gets or sets the width of the of the drop-down portion of a combo box.
private sub command1_click()
Dim dynastring() as string What are the differences between Combo box and List box?
ReDim dynastrings(10) List Box
Dynastring(1)=”the first string” Need more data space Redim Definition:- It contains lists of items and provides the facility to select
dynastrings(100) items from the list of items. Items can only be shown at runtime.
Dynastrings(50)=”the fiftieth string” ( It displays a box with a list of item from which a user can make a
End sub selection.
LISTBOX AND COMBO BOX ( It doesn’t have any edit area to enter information at runtime.
List Box ( It has 2 style properties
The List Box represents a Windows control to display a list of items to • 0 (zero) Standard
a user. A user can select an item from the list. It allows the • 1 (One) Checkbox list box.
programmer to add items at design time by using the properties ( It has multi select property to make multiple selections.
window or at the runtime. You can populate the list box items either ( It has “selcount” and ‘selected” Properties. To count the no. of
from the properties window or at runtime. To add items to a ListBox, selected item in the list & the selection status (True if selected, False if
select the ListBox control and get to the properties window, for the not selected) of an item in the list respectively.
properties of this control. Click the ellipses (...) button next to the Items Combo Box
property. This opens the String Collection Editor dialog box, where you Definition:- It combines a dropdown list with the data control and the
can enter the values one at a line. dropdown list is populated at runtime depending upon the data
Properties of the List Box Control supplies to it.
1.AllowSelection ( It provides a combination of a list box & text box control.
Gets a value indicating whether the ListBox currently enables selection ( Combo box control has an edit area where user can enter or edit
of list items. information at runtime.
2.BorderStyle ( It has 3-type properties
Gets or sets the type of border drawn around the list box. • 0 (Zero) dropdown combo
3.ColumnWidth . • Simple combo
Gets of sets the width of columns in a multicolumn list box. . • Dropdown list.
4.HorizontalExtent ( It has no multi select property.
Gets or sets the horizontal scrolling area of a list box. ( No such property Is available.
5.HorizontalScrollBar
Gets or sets the value indicating whether a horizontal scrollbar is 'VB.Net program to create the simple calculator
displayed in the list box. Module Module1
6.ItemHeight
Gets or sets the height of an item in the list box. Sub Main()
7.Items Dim choice As Integer
Gets the items of the list box. Dim num1 As Integer = 0
8.MultiColumn Dim num2 As Integer = 0
Gets or sets a value indicating whether the list box supports multiple Dim result As Integer = 0
columns.
9.ScrollAlwaysVisible Console.WriteLine("############################")
Gets or sets a value indicating whether the vertical scroll bar is shown Console.WriteLine(" 1: Addition")
at all times. Console.WriteLine(" 2: Subtraction")
10.SelectedIndex Console.WriteLine(" 3: Multiplication")
Gets or sets the zero-based index of the currently selected item in a Console.WriteLine(" 4: Division")
list box. Console.WriteLine("############################")
ComboBox
The ComboBox control is used to display a drop-down list of various Console.Write("Enter choice: ")
items. It is a combination of a text box in which the user enters an item choice = Integer.Parse(Console.ReadLine())
and a drop-down list from which the user selects an item. Console.Write("Enter number1: ")
num1 = Integer.Parse(Console.ReadLine()) now learn how to write errors handling code in Visual Basic 2019. The
Console.Write("Enter number2: ") syntax for errors handling is
num2 = Integer.Parse(Console.ReadLine()) On Error GoTo program_label
where program_label is the section of code that is designed by the
Select Case choice programmer to handle the error committed by the user. Once an error
Case 1 is detected, the program will jump to the program_label section for
result = num1 + num2 error handling.
Case 2 EXAMPLE : The Division Error
result = num1 - num2 In this example, we will deal with the error of entering non-numeric
Case 3 data into the text boxes that supposed to hold numeric values. The
result = num1 * num2 program_label here is error_handler. When the user enters non-
Case 4 numeric values into the text boxes, the error message will display the
result = num1 / num2 phrase "One or both of the entries is/are non-numeric!". If no error
Case Else occurs, it will display the correct answer. Try it out yourself.
Console.WriteLine("Invalid choice") Errors Handling using Try…..Catch….End Try Structure
End Select Visual Basic 2017 has adopted a new approach in handling errors or
rather exceptions handling. It is supposed to be more efficient than the
Console.WriteLine("Result: {0}", result) old On Error Goto method, where it can handle various types of errors
End Sub within the Try…Catch…End Try structure. The structure looks like this
End Module
Try
ERROR IN VISUAL BASIC statements
When you compile or run a Visual Basic application, the following Catch exception_variable as Exception
types of errors can occur: statements to deal with exceptions
Run-time errors End Try
If a Visual Basic application tries to perform an action that the system
can't execute, a run-time error occurs, and Visual Basic throws an Looping statement
Exception object. Visual Basic can generate custom errors of any data Some statements are used in visual basic programming for repetition.
type, including Exception objects, by using the Throw statement. An These statements are called looping statement. Visual basic provide a
application can identify the error by displaying the error number and large amount of looping statements. Function of all looping statement
message of a caught exception. If an error isn't caught, the application are about same. The computer is capable of repeating a group of
ends. statement number of times without calling the procedure for each new
The code can trap and examine run-time errors. If you enclose the set of data. The process of repeating a series of statements called
code that produces the error in a Try block, you can catch any thrown looping. Visual basic support the following looping statements. They
error within a matching Catch block. For information about how to trap are Do-Loop, For-Next and While-Wend.
errors at run time and respond to them in your code, see Do-Loop: – These looping statements execute single or block of
Compile-time errors statements for as long as a condition is true. Visual basic evaluate an
If the Visual Basic compiler encounters a problem in the code, a expression, and if it is true, the statements are executed. If the
compile-time error occurs. In the Visual Studio code editor, you can expression is false, the program continues and the statement following
easily identify which line of code caused the error because a wavy line the loop is executed.
appears under that line of code. The error message appears if you Do While <Text Expression>
either point to the wavy underline or open the Error List, which also Statement Block
shows other messages. Loop
If an identifier has a wavy underline and a short underline appears Or,
under the rightmost character, you can generate a stub for the class, Do Until <Text Expression>
constructor, method, property, field, or enum. For more information, Statement block
see Generate From Usage (Visual Studio). Loop
By resolving warnings from the Visual Basic compiler, you might be Basic difference between While and Until that is the keyword while
able to write code that runs faster and has fewer bugs. These warnings continue the loop until condition is true and keyword until continue the
identify code that may cause errors when the application is run. For loop until condition is false.
example, the compiler warns you if you try to invoke a member of an
unassigned object variable, return from a function without setting the For-Next: – The For-Next is a fixed looping statement. Single or block
return value, or execute a Try block with errors in the logic to catch of statements are executed fixed number of times. The structure of
exceptions. For more information about warnings, For-Next statement begins with a go-to statement and ends with a next
Logic Errors statement. In between are the statement to be executed. Syntax of the
A logic error occurs when the program (the code) is written fine but the for-next statement is –
result it produces is not reliable. With a logic error, the Code Editor For <Counter> = <Start> To <End> [Step Increment /
does not see anything wrong in the document and therefore cannot Decrement] Statement Block
point out a problem. One of the worse types of logic errors is one that Next [Counter]
makes a computer crash sometimes, regularly, or unpredictably, while The arguments counter, start, end and increment / Decrement are all
there is nothing obviously wrong in the code. numeric. The for-to statement specifies the number of passes through the
Logic errors are, or can be, difficult to spot because you will have to know loop. Within this is statement counter is variable whose value begins with
for sure that the result is wrong and why (and sometimes worse, you will start, increase, and decrease by numeric value in each time until the loop
have to agree or accept that it is your program that is causing a problem in is executed, until it reached end. Note that the value of counter will be end
the computer; imagine a user reports that her computer crashes every time during the last pass through the loop. The next statement identifies the end
she starts the application you created). Because you or the user of your of the loop. In executing, visual basic follows this step.
program would know with certainty that the result is questionable, you
would have to use some means of correcting it. One of the techniques you While-Wend: – The While-Wend statement is a conditional looping
can use is referred to as debugging. statement this statement executes single or block of statement while a
Error Handling condition is true. Syntax of the While-Wend statement is – While <Test
Visual Basic 2019 has improved a lot in its built-in errors handling Expression>
capabilities compared to Visual Basic 6. For example, when the user Statement Block
attempts to divide a number by zero, Visual Basic 2019 will not return Wend
an error message but gives the ‘infinity’ as the answer (although this is If condition is true, all statements between while and wend are
mathematically incorrect because it should be undefined) executed. If condition is still true, the process is repeated. If condition
Using On Error GoTo Syntax become false, the program resume with the student following the wend
Visual Basic 2019 still supports the vb6 errors handling syntax, that is statement. This While-Wend is analogous to a Do-While-Loop
the On Error GoTo program_label structure. Although it has a more statement.
advanced error handling method, we shall deal with that later. We shall