0% found this document useful (0 votes)
42 views22 pages

Gui Unit 1

The .NET Framework is a software framework developed by Microsoft that allows development of various application types. It includes a large class library and provides language interoperability. The framework architecture includes the Common Language Runtime (CLR), Base Class Library (BCL), and supported programming languages. The CLR handles execution of .NET programs and provides features like exception handling and garbage collection. The BCL includes standard classes. Supported languages include C#, VB.NET, and ASP.NET for building Windows desktop, web, and database applications respectively.

Uploaded by

dawngliani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views22 pages

Gui Unit 1

The .NET Framework is a software framework developed by Microsoft that allows development of various application types. It includes a large class library and provides language interoperability. The framework architecture includes the Common Language Runtime (CLR), Base Class Library (BCL), and supported programming languages. The CLR handles execution of .NET programs and provides features like exception handling and garbage collection. The BCL includes standard classes. Supported languages include C#, VB.NET, and ASP.NET for building Windows desktop, web, and database applications respectively.

Uploaded by

dawngliani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT 1

OVERVIEW OF .NET FRAMEWORK

.NET Framework is a software framework developed by Microsoft that runs primarily on


Microsoft Windows. It includes a large class library named Base Class Library and provide
language interoperability across several programming languages. The first version of the
.Net framework was released in the year 2002.The version was called .Net framework 1.0.
The .Net framework has come a long way since then, and the current version is 4.7.1.
Unlike the Win32 API,.NET is totally object-oriented. Anything you want to do in.NET, you
are going to be doing with an object. If you want to open a file, you create an object that
knows how to do this. If you want to draw a window on the screen, you create an object an
object that knows how to do this.
.Net Framework Architecture
The basic architecture of the .Net framework is as shown below.

.net framework architecture diagram


The architecture of the .Net framework is based on the following key components;
1. Common Language Runtime
The "Common Language Runtime” or CLR is a platform on which the .Net programs are
executed.
The CLI has the following key features:
 Exception Handling - Exceptions are errors which occur when the application is
executed. Examples of exceptions are:
o If an application tries to open a file on the local machine, but the file is not
present.
o If the application tries to fetch some records from a database, but the
connection to the database is not valid.
 Garbage Collection - Garbage collection is the process of removing unwanted
resources when they are no longer required. Examples of garbage collection are
o A File handle which is no longer required. If the application has finished all
operations on a file, then the file handle may no longer be required.
o The database connection is no longer required. If the application has
finished all operations on a database, then the database connection may no
longer be required.
 Working with Various programming languages –

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 1
A developer can develop an application in a variety of .Net programming languages.
1. Language - The first level is the programming language itself, the most common
ones are VB.Net and C#.
2. Compiler – There is a compiler which will be separate for each programming
language. So underlying the VB.Net language, there will be a separate VB.Net
compiler. Similarly, for C#, you will have another compiler.
3. Common Language Interpreter – This is the final layer in .Net which would be
used to run a .net program developed in any programming language. So the
subsequent compiler will send the program to the CLI layer to run the .Net
application.

2. Base Class Library


The .NET Framework includes a set of standard class libraries. A class library is a
collection of methods and functions that can be used for the core purpose.
For example, there is a class library with methods to handle all file-level operations. So
there is a method which can be used to read the text from a file. Similarly, there is a
method to write text to a file.
Most of the methods are split into either the System.* or Microsoft.* namespaces. (The
asterisk * just means a reference to all of the methods that fall under the System or
Microsoft namespace).A namespace is a logical separation of methods. We will learn these
namespaces more in detail in the subsequent chapters.

3. Languages
The types of applications that can be built in the .Net framework is classified broadly into
the following categories.
 WinForms – This is used for developing Forms-based applications, which would
run on an end user machine. Notepad is an example of a client-based application.
 ASP.Net – This is used for developing web-based applications, which are made to
run on any browser such as Internet Explorer, Chrome or Firefox.
o The Web application would be processed on a server, which would have
Internet Information Services Installed.
o Internet Information Services or IIS is a Microsoft component which is used
to execute an Asp.Net application.
o The result of the execution is then sent to the client machines, and the
output is shown in the browser.
 ADO.Net – This technology is used to develop applications to interact with
Databases such as Oracle or Microsoft SQL Server.

4. The Common Types System and Common Language Specification


The Common Type System (CTS) enables software written in different languages to work
together. Before .NET Visual Basic and C++ handled stings completely differently, and you
had to go through a conversion process each time you went from one to the other. With
the CTS in place, all .NET languages use strings, integers, and so on in the same way, so no
conversion needs to take place.

The Common Language Specification (CLS) was introduced by Microsoft to make it easier
for language developers to adapt their languages to be compatible with .NET. This means
that C, C++, C# and Java can be easily made to be compatible with .NET environment.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 2
.Net Framework Design Principle
The following design principles of the .Net framework is what makes it very relevant to
create .Net based applications.
1. Interoperability - The .Net framework provides a lot of backward support.
Suppose if you had an application built on an older version of the .Net framework,
say 2.0. And if you tried to run the same application on a machine which had the
higher version of the .Net framework, say 3.5. The application would still work.
2. Portability- Applications built on the .Net framework can be made to work on any
Windows platform. And now in recent times, Microsoft is also envisioning to make
Microsoft products work on other platforms, such as iOS and Linux.
3. Security - The .NET Framework has a good security mechanism. The inbuilt
security mechanism helps in both validation and verification of applications. Every
application can explicitly define their security mechanism. Each security
mechanism is used to grant the user access to the code or to the running program.
4. Memory management - The .Net framework has all the capability to see those
resources, which are not used by a running program. It would then release those
resources accordingly. This is done via a program called the "Garbage Collector"
which runs as part of the .Net framework. The garbage collector runs at regular
intervals and keeps on checking which system resources are not utilized, and frees them
accordingly.
5. Simplified deployment - The .Net framework also have tools, which can be used to
package applications built on the .Net framework. These packages can then be
distributed to client machines. The packages would then automatically install the
application.

MSIL
Microsoft Intermediate Language (MSIL) is a language used as the output of a number of
compilers (C#, VB, .NET, and so forth). It is a set of indeoendent instructions that are
generated by language compiler when the project is compiled. MSIL code is not executable
but can be processed by CLR before it becomes executable. The advantages of MSIL are as
follows:
1. MSIL provides language interoperability, as code in any .NET language is compiled on
MSIL.
2. Same performance in all .NET languages.
3. It support different runtime environments.
4. JIT compiler in CLR converts MSIL code into native machine code which is executed by
OS.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 3
INTRODUCTION TO .NET
Visual Basic 2010 is a language you can use to tell your computer how to do things; but,
like a child, the computer will understand only if you explain things very clearly. If you
have never programmed before, this sounds like an arduous task, and sometimes it can be.
However, Visual Basic 2010 offers an easy-to-use language to explain some complex tasks.
Although it never hurts to have an understanding of what is happening at the lowest
levels, Visual Basic 2010 frees the programmer from having to deal with the mundane
complexities of writing Windows applications. You are free to concentrate on solving real
problems.

EVENT-DRIVEN PROGRAMMING
Event-driven programming is a programming paradigm in which the flow of program
execution is determined by events - for example a user action such as a mouse click, key
press, or a message from the operating system or another program. An event-driven
application is designed to detect events as they occur, and then deal with them using an
appropriate event-handling procedure.

Event-driven programs can be written in any programming language, although some


languages(Visual Basic for example) are specifically designed to facilitate event-driven
programming, and provide an integrated development environment (IDE) that partially
automates the production of code, and provides a comprehensive selection of built-in
objects and controls, each of which can respond to a range of events. Virtually all object-
oriented and visual languages support event-driven programming. Visual Basic, Visual C++
and Java are examples of such languages.

A visual programming IDE such as VB.Net provides much of the code for detecting events
automatically when a new application is created. The programmer can therefore
concentrate on issues such as interface design, which involves adding controls such as
command buttons, text boxes, and labels to standard forms (a form represents an
application's workspace or window). Once the user interface is substantially complete, the
programmer can add event-handling code to each control as required.
Many visual programming environments will even provide code templates for event-
handlers, so the programmer only needs to provide the code that defines the action the
program should take when the event occurs. Each event-handler is usually bound to a
specific object or control on a form. Any additional subroutines, methods, or function
procedures required are usually placed in a separate code module, and can be called from
other parts of the program as and when needed.

The most common event are Click, DoubleClick, KeyPress, KeyDown, MouseMove,
MouseDrag etc.

THE VISUAL STUDIO 2010 IDE


The capability to run Visual Basic .NET code is included with the .NET Framework. the
easiest way to write in Visual Basic .NET code is by using the Visual Studio 2010 IDE. The
IDE provides a wealth of features unavailable in ordinary text editors — such as code
checking, visual representations of the finished application, and an explorer that displays
all of the files that make up your project.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 4
1.The Menu Editor
The Visual Studio 2010 menu is dynamic, which means items are added or removed
depending on what you are trying to do. When looking at the blank IDE, the menu bar
consists only of the File, Edit, View,Tools, Test, Window, and Help menus.

2.The Toolbars
Many toolbars are available within the IDE, including Formatting, Image Editor, and Text
Editor, which you can add to and remove from the IDE through the View ➪ Toolbars menu
option. Just beneath the Menu Editor is a toolbar. The toolbar contains frequently accessed
functionality that is a subset of what is available via menu. Each one provides quick access

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 5
to frequently used commands, preventing you from having to navigate through a series of
menu options.

The toolbar is segmented into groups of related options, which are separated by vertical
bars:
➤ The first six icons provide access to the commonly used project and file manipulation
options available through the File and Project menus, such as opening and saving files.
➤ The next group of icons is for editing (Cut, Copy, and Paste). The next icon is for finding
and replacing items in your code.
➤ The third group of icons is used for commenting out and un-commenting sections of
code. This can be useful in debugging when you want to comment out a section of code to
determine what results the program might produce by not executing those lines of code.
➤ The fourth group of icons is for undoing and redoing edits and for navigating through
your code.
➤ The fifth group of icons provides the ability to start (via the green triangle), pause, and
stop your application. You can also use the last three icons in this group to step into your
code line by line, step over entire sections of code, and step out of a procedure. These
icons will be covered in depth in Chapter 10.
➤ The final group of icons provides quick links to the Solution Explorer, Properties
window, Object Browser, Toolbox, Error List, ExtensionManager, and the Immediate
window. If any of these windows is closed, clicking the appropriate icon will bring it back
into view.

3.THE TOOLBOX
The Toolbox is a palette of developer objects, or
controls, that are placed on forms or web pages, and then code
is added to allow the user to interact with them. An example
would be TextBox, Button and ListBox controls. With these
three controls added to a Windows Form object the developer
could write code that would take text, input by the application
user, and added to the ListBox after the button was clicked.
The toolbox is accessed through the view -> Toolbox
menu option, by clicking the Toolbox icon on the standard
menu bar,or by pressing Ctrl+Alt+X. Alternatively, the toolbox
tab is displayed on the left of the IDE; hovering your mouse
over this tab will cause the Toolbox window to fly out ,
partially covering your form.
You can also add controls by clicking on the space
available on the toolbox and then select component menu.A
dialog box will appear list all the available component that is
installed in your system. Click on the box which is available
before the component name,then select OK. A new component will appear on the toolbox.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 6
4. SOLUTION EXPLORER
This is a section that is used to view and modify the contents of the project. A Visual Studio
Windows Application Project will generally have a Form object with a code page,
references to System components and possibly other modules with special code that is
used by the application. All the forms, modules and associated files are displayed in the
solution explorer. You can also add forms and files from this explorer by right clicking on
the application name and add. By default, when creating a new application Form1.vb file is
created which is the first form and can be renamed as desire.

5. PROPERTIES WINDOW
The properties windows shows all the control (like textbox)
properties to be change at design time. Most of this
properties can be change at run time with some code, but
basically most of this properties change the way the control
is display on your application. Every control has their own
properties, so according to the control you can change its
properties. Some of the common properties of a control are
name, visible, enable, font, forecolor, backcolor etc.

6. THE DESIGN VIEW/ CODE EDITOR


The Deisgn view is the place where the layout of
pages are done. You can drag and drop the required control
like textbox, label, imagebox, redio button etc from the
toolbox. After you finish the design, you have to add some
code to make it actually do something interesting. To add
the code for a control, you just double-click the form or control. This opens the code editor
in the main window. Note that an additional tab has been created in the main window.
Now you have the design tab and the code tab , each containing the name of the form you
are working on.You draw the controls on your form in the design tab , and you write code
for your form in the code tab. The visual definition and the code behind it exist in separate
files.Eg:Hello user.Designer.vb and Hello user.vb.Using the design mode you can visually
lay out your application ; then, using Code view, you add just the bits of code to implement
your desired functionality.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 7
7.USING THE HELP SYSTEM
This menu contains a few more items than the typical Windows application.The main
reason for this is the vastness of the documentation .Few people could keep it all in their
heads-but luckily that Is not a problem, because you can always quickly and Easily refer to
the help system or search the forums for people who are experiencing or have
experienced a similar programming task. The following are the menu available under help:

INTRODUCTION TO VB.NET PROGRAMMMING


VB.Net is an object-oriented programming language. In Object-Oriented Programming
methodology, a program consists of various objects that interact with each other by means
of actions. The actions that an object may take are called methods. Objects of the same
kind are said to have the same type or, more often, are said to be in the same class.

When we consider a VB.Net program, it can be defined as a collection of objects that


communicate via invoking each other's methods. The following are the different Elements
in an Object Oriented Programming Language:
1. Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors - wagging, barking, eating, etc. An object is an instance of a
class.

2. Class − A class can be defined as a template/blueprint that describes the


behaviors/states that objects of its type support.

3. Methods − A method is basically a behavior. A class can contain many methods. It is in


methods where the logics are written, data is manipulated and all the actions are executed.

4. Instance Variables − Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 8
Let's have a look at a simple code that would print the string "Welcome to VB.NET
Tutorial."

Imports System
Module Program
'It will display a string on the console
Sub Main(args As String())
Console.WriteLine("Welcome to VB.NET Tutorial.")
End Sub
End Module

VARIABLES
In visual basic, as in any other programming language, variables store values
during a program’s language execution. A variable has a name and a value. The variable’s
username, for example, might have the value Joe, and the variable Discount might have the
value 0.35.UserName and Discount are variable Names, and Joe and 0.35 and their values .
Joe is a string (that is,text), and 0.35 is a numeric value . When a variable’s value is a
string, it must be enclosed in double quotes.

DECLARING VARIABLES
When programming in VB 2010, you should declare your variables because this is
the default mode. If you attempt to use undeclared variables in your code, VB 2010 will
throw an exception. It is possible to change the default behavior and use undeclared
variables. To declare variables use the Dim statement and the As keyword,
Dim meters As integer
Dim greetings As string
The first variable, meters, will store integers, such as 3 or 1,002; the second
variable, greetings will store text. You can declare multiple variables of the same or
different type in the same line, as follows:
Dim Qty As Integer , Amount As Decimal, Volume As String
Dim Length,Width, Height As Integer, Volume, Area As Double

VARIABLE INITIALIZATION
Visual basic allows you to initialize variables in the same lines that declare them.
The following statement declares an integer variable and immediately places in the value
3,045 in it:
Dim distance As integer = 3045
This statement is equivalent to the following two:
Dim Distance As integer
Distance = 3045

IDENTIFIERS
As the name defines, an identifier is used to identify the name of variable, function, class,
or any other user-defined elements in the program. An identifier should be the
combination of letter, digit, and underscore. Still, the first character of the identifier or
variable name should start with alphabet letter or underscore (_) of any length.
There are various rules for identifier in VB.NET, as follows:

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 9
1. The first character of an identifier must start with an alphabet or
underscore, that could be followed by any sequence of digits (0-9), letter or
underscore.
2. An identifier should not contain any reserved keyword.
3. It should not start with any digit.
4. It should not more than 51 characters.
5. An identifier can contain two underscores, but should not be consecutive.
6. It should not include any commas or white spaces in-between characters.

KEYWORDS
A keyword is a reserved word with special meanings in the compiler, whose meaning
cannot be changed. Therefore, these keywords cannot be used as an identifier in VB.NET
programming such as class name, variable, function, module, etc.

Some of the reserved keyword available in the VB.NET language are:

And Boolean ByVal Char Const Continue


Date Dim Else End End if Enum
Integer If Loop New Next Private
Public Then True

DATA TYPE (Types of Variables)


Variables have a data type, which determines what kind of values you can store to a
variable. Visual basic organizes the following categories of variables:
7. Numeric
8. String
9. Boolean
10. Date
11. Object

Numeric Variables
All programming languages provide a variety of numeric data types, including the
following:
◆ Integer (there are several Integer data types)
◆ Decimal
◆ Single (floating-point numbers with limited precision)
◆ Double (floating-point numbers with extreme precision)
Decimal, Single, and Double are the three basic data types for storing floating-point
numbers (numbers with a fractional part).
Integer Variables
There are three types of variables for storing integers, and they differ only in the range of
numbers each can represent. As you understand, the more bytes a type takes, the larger
values it can hold. The type of Integer variable you’ll use depends on the task at hand. You
should choose the type that can represent the largest values you anticipate will come up in
your calculations. You can go for the Long type, to be safe, but Long variables take up four
times as much space as Short variables and it takes the computer longer to process them.
Single- and Double-Precision Numbers

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 10
The Single and Double data type names come from single-precision and double-precision
numbers. Double-precision numbers are stored internally with greater accuracy than
singleprecision numbers.
Eg: Dim a As Single, b As Double
Visual Basic numeric data types

Data Type Size Stores


Byte (Byte) 1 byte Integers in the range 0 to 255.
Signed Byte(SByte) 1 byte Integers in the range −128 to 127.
Short (Int16) 2 bytes Integer values in the range −32,768 to 32,767.
Integer (Int32) 4 bytes Integer values in the range
−2,147,483,648 to 2,147,483,647.
Long (Int64) 8 bytes Integer values in the range −9,223,372,036,854,755,808
to9,223,372,036,854,755,807.
Unsigned Short 2 bytes Positive integer values in the range 0 to 65,535.
(UShort)
Unsigned Integer 4 bytes Positive integers in the range 0 to 4,294,967,295.
(UInteger)
Unsigned Long 8 bytes Positive integers in the range 0 to
(ULong) 18,446,744,073,709,551,615.
Single Precision 4 bytes Single-precision floating-point numbers. A single can
(Single) represent negative numbers in the range−3.402823E38 to
precision variable −1.401298E –45 and positive numbers in the range
1.401298E–45 to 3.402823E38. The value 0 can’t be
represented precisely (it’s a very,very small number,but
not exactly 0)
Double Precision 8 bytes Double-precision floating-point numbers. A double
(Double) precision variable can represent negative numbers in
the range −1.79769313486232E308 to
−4.94065645841247E–324 and positive numbers in the
range 4.94065645841247E–324 to
1.79769313486232E308. Decimal (Decimal) 16 bytes
Integer and floating-point numbers scaled by a
factor in range from 0 to 28.

Boolean Variables
The Boolean data type stores True/False values. Boolean variables are, in essence,
integers that take the value –1 (for True) and 0 (for False). Actually, any nonzero value is
considered True. Boolean variables are declared as
Dim failure As Boolean

String Variables
The String data type stores only text, and string variables are declared as follows:
Dim someText As String

Character Variables
Character variables store a single Unicode character in two bytes. To declare a Character
variable, use the Char data type:

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 11
Dim char1, char2 As Char

Date Variables
Date variables store date values that may include a time part (or not), and they are
declared with the Date data type:
Dim expiration As Date

DATA TYPE CONVERSION


In many situations, you will need to convert variables from one type into another. Table
below shows the methods of the Convert class that perform data-type conversions.

TABLE: The data-type conversion methods of the Convert class


METHOD CONVERTS ITS ARGUMENT TO
ToBoolean Boolean
ToByte Byte
ToChar Unicode character
ToDate TimeDate
ToDecimal Decimal
ToDouble Double
ToInt16 Short Integer (2-byte integer, Int16)
ToInt32 Integer (4-byte integer, Int32)
ToInt64 Long (8-byte integer, Int64)
ToSByte Signed Byte
CShort Short (2-byte integer, Int16)
ToSingle Single
ToString String
ToUInt16 Unsigned Integer (2-byte integer, Int16)
ToUInt32 Unsigned Integer (4-byte integer, Int32)
ToUInt64 Unsigned Long (8-byte integer, Int64)

Type Characters
In addition to specifying a data type in a declaration statement, you can force the data type
of some programming elements with a type character. The type character must
immediately follow the element, with no intervening characters of any kind.
Visual Basic supplies a set of identifier type characters that you can use in a declaration to
specify the data type of a variable or constant. The following table shows the available
identifier type characters with examples of usage.
______________________________________________________________________________________________________
Type Character Description Example

C Converts value to a Char type Dim ch As String = "A"c

D or @ Converts value to a Decimal type Dim price As Decimal = 12.99D

R or # Converts value to a Double type Dim pi As Double = 3.14R

I or % Converts value to an Integer type Dim count As Integer = 99I

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 12
L or & Converts value to a Long type Dim distance As Long = 1999L

S Converts value to a Short type Dim age As Short = 1S

F or ! Converts value to a Single type Dim velocity As Single = 74.99F

CONSTANTS
The constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals. Constants can be of any of the basic data types
like an integer constant, a floating constant, a character constant, or a string literal. There
are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be
modified after their definition.

Declaring Constants
In VB.Net, constants are declared using the Const statement. The Const statement is used
at module, class, structure, procedure, or block level for use in place of literal values.
The syntax for the Const statement is:
Const constantname [ As datatype ] = initializer
 Const : keyword for const
 constantname: specifies the name of the constant
 datatype: specifies the data type of the constant
 initializer: specifies the value assigned to the constant
For example,
'The following statements declare constants.'
Const maxval As Long = 4999
Public Const message As String = "HELLO"
Private Const piValue As Double = 3.1415

VB.Net provides the following print and display constants:


Constant Description
vbCrLf Carriage return/linefeed character combination.
vbCr Carriage return character.
vbLf Linefeed character.
vbNewLine Newline character.
vbNullChar Null character.
vbNullString Not the same as a zero-length string (""); used for calling external
procedures.
vbObjectError Error number. User-defined error numbers should be greater than this
value.
vbTab Tab character.
vbBack Backspace character.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 13
ENUMERATIONS
Enumerations provide a convenient way to work with sets of related constants and to
associate constant values with names. For example, you can declare an enumeration for a
set of integer constants associated with the days of the week, and then use the names of
the days rather than their integer values in your code. An enumeration has a name, an
underlying data type, and a set of members. Each member represents a constant.
Enum Statement declares an enumeration and defines the values of its members.
Enum enumerationname [ As datatype ]
memberlist
End Enum

Enumerationname is a variable name of the enumeration, datatype is Optional and is the


data type of the enumeration and all its members and memberlist is a list of member
constants being declared in this statement. Multiple members appear on individual source
code lines. Each member list has a membername variable and an initialize where initialize
is optional
For eg,
Enum background
None = 0
green = 1
yellow = 2
red = 3
blue = 4
End Enum
Sub Main()
Dim value As background = background.green
If value=0 then
Console.WriteLine("None")
Elseif value=1 then
Console.WriteLine("green")
Elseif value=2 then
Console.WriteLine("yellow")
Elseif value=3 then
Console.WriteLine("red")
Elseif value=4 then
Console.WriteLine("blue")
End if
End Sub
The benefits of using enumerations include the following:
 Reduces errors caused by transposing or mistyping numbers.
 Makes it easy to change values in the future.
 Makes code easier to read, which means it is less likely that errors will be
introduced.
 Ensures forward compatibility. If you use enumerations, your code is less likely to
fail if in the future someone changes the values corresponding to the member
names.

OPERATORS IN VB.NET

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 14
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. VB.Net is rich in built-in operators and provides following types of
commonly used operators:
 Arithmetic Operators
 Comparison Operators
 Logical/Bitwise Operators
 Bit Shift Operators
 Assignment Operators
 Miscellaneous Operators

Arithmetic Operators
Following table shows all the arithmetic operators supported by VB.Net. Assume
variable A holds 2 and variable B holds 7, then:
Show Examples
Operator Description Example
^ Raises one operand to the power of another B^A will give 49
+ Adds two operands A + B will give 9
- Subtracts second operand from the first A - B will give -5
* Multiplies both operands A * B will give 14
/ Divides one operand by another and returns a floating B / A will give 3.5
point result
\ Divides one operand by another and returns an B \ A will give 3
integer result
MOD Modulus Operator and remainder of after an integer B MOD A will give 1
division

Comparison Operators
Following table shows all the comparison operators supported by VB.Net. Assume
variable A holds 10 and variable B holds 20, then:
Operator Description Example
= Checks if the values of two operands are equal or not; (A = B) is not
if yes, then condition becomes true. true.
<> Checks if the values of two operands are equal or not; (A <> B) is true.
if values are not equal, then condition becomes true.
> Checks if the value of left operand is greater than the (A > B) is not
value of right operand; if yes, then condition becomes true.
true.
< Checks if the value of left operand is less than the (A < B) is true.
value of right operand; if yes, then condition becomes
true.
>= Checks if the value of left operand is greater than or (A >= B) is not
equal to the value of right operand; if yes, then true.
condition becomes true.
<= Checks if the value of left operand is less than or equal (A <= B) is true.
to the value of right operand; if yes, then condition
becomes true.

Logical operators
BCA405-GUI Programming: Govt. Zirtiri Residential Science College
Page 15
Following table shows all the logical operators supported by VB.Net. Assume variable A
holds Boolean value True and variable B holds Boolean value False, then:
Operator Description Example
And It is the logical as well as bitwise AND operator. If both the (A And B) is
operands are true, then condition becomes true. This operator False.
does not perform short-circuiting, i.e., it evaluates both the
expressions.
Or It is the logical as well as bitwise OR operator. If any of the two (A Or B) is
operands is true, then condition becomes true. This operator True.
does not perform short-circuiting, i.e., it evaluates both the
expressions.
Not It is the logical as well as bitwise NOT operator. Use to reverses Not(A And B)
the logical state of its operand. If a condition is true, then Logical is True.
NOT operator will make false.
Xor It is the logical as well as bitwise Logical Exclusive OR operator. A Xor B is
It returns True if both expressions are True or both expressions True.
are False; otherwise it returns False. This operator does not
perform short-circuiting, it always evaluates both expressions
and there is no short-circuiting counterpart of this operator.
AndAlso It is the logical AND operator. It works only on Boolean data. It (A AndAlso
performs short-circuiting. B) is False.
OrElse It is the logical OR operator. It works only on Boolean data. It (A OrElse B)
performs short-circuiting. is True.
IsFalse It determines whether an expression is False.
IsTrue It determines whether an expression is True.

Bitwise Operators Assume that the variable A holds 60 and variable B holds 13, then:
Operator Description Example
And Bitwise AND Operator copies a bit to the result if it (A AND B) will give 12,
exists in both operands. which is 0000 1100
Or Binary OR Operator copies a bit if it exists in either (A Or B) will give 61, which
operand. is 0011 1101
Xor Binary XOR Operator copies the bit if it is set in (A Xor B) will give 49,
one operand but not both. which is 0011 0001
Not Binary Ones Complement Operator is unary and (Not A ) will give -61,
has the effect of 'flipping' bits. which is 1100 0011 in 2's
complement form
<< Binary Left Shift Operator. The left operands value A << 2 will give 240, which
is moved left by the number of bits specified by the is 1111 0000
right operand.
>> Binary Right Shift Operator. The left operands A >> 2 will give 15, which is
value is moved right by the number of bits 0000 1111
specified by the right operand.

Assignment Operators
There are following assignment operators supported by VB.Net:
Operator Description Example
= Simple assignment operator, Assigns values from right C = A + B will assign
BCA405-GUI Programming: Govt. Zirtiri Residential Science College
Page 16
side operands to left side operand value of A + B into C
+= Add AND assignment operator, It adds right operand to C += A is equivalent
the left operand and assigns the result to left operand to C = C + A
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent
operand from the left operand and assigns the result to to C = C - A
left operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent
operand with the left operand and assigns the result to to C = C * A
left operand
/= Divide AND assignment operator, It divides left operand C /= A is equivalent
with the right operand and assigns the result to left to C = C / A
operand (floating point division)
\= Divide AND assignment operator, It divides left operand C \= A is equivalent
with the right operand and assigns the result to left to C = C \A
operand (Integer division)
^= Exponentiation and assignment operator. It raises the C^=A is equivalent
left operand to the power of the right operand and to C = C ^ A
assigns the result to left operand.
<<= Left shift AND assignment operator C <<= 2 is same as C
= C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C
= C >> 2
&= Concatenates a String expression to a String variable or Str1 &= Str2 is
property and assigns the result to the variable or same as
property. Str1 = Str1 & Str2

Miscellaneous Operators
There are few other important operators supported by VB.Net.
Operator Description Example
AddressOf Returns the address of a AddHandler Button1.Click,
procedure. AddressOf Button1_Click
Await It is applied to an operand in
an asynchronous method or Dim result As res
lambda expression to = Await
suspend execution of the AsyncMethodThatReturnsResult()
method until the awaited task Await AsyncMethod()
completes.
GetType It returns a Type object for MsgBox(GetType(Integer).ToString())
the specified type. The Type
object provides information
about the type such as its
properties, methods, and
events.
Function It declares the parameters Dim add5 = Function(num As
Expression and code that define a Integer) num + 5
function lambda expression. 'prints 10
Console.WriteLine(add5(5))

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 17
If It uses short-circuit Dim num = 5
evaluation to conditionally Console.WriteLine(If(num >= 0,
return one of two values. The "Positive", "Negative"))
If operator can be called with
three arguments or with two
arguments.

Operators Precedence in VB.Net


Operator precedence determines the grouping of terms in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator:
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Operator Precedence
Await Highest
Exponentiation (^)
Unary identity and negation (+, -)
Multiplication and floating-point division (*, /)
Integer division (\)
Modulus arithmetic (Mod)
Addition and subtraction (+, -)
Arithmetic bit shift (<<, >>)
All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)
Negation (Not)
Conjunction (And, AndAlso)
Inclusive disjunction (Or, OrElse)
Exclusive disjunction (Xor) Lowest

STATEMENT IN VB.NET
A statement is a complete instruction in Visual Basic programs. It may contain keywords,
operators, variables, literal values, constants and expressions.
Statements could be categorized as:
 Declaration statements - these are the statements where you name a variable,
constant, or procedure, and can also specify a data type.
 Executable statements - these are the statements, which initiate actions. These
statements can call a method or function, loop or branch through blocks of code or
assign values or expression to a variable or constant. In the last case, it is called an
Assignment statement.

Declaration Statements
The declaration statements are used to name and define procedures, variables,
properties, arrays, and constants. When you declare a programming element, you can
also define its data type, access level, and scope.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 18
The programming elements you may declare include variables, constants, enumerations,
classes, structures, modules, interfaces, procedures, procedure parameters, function
returns, external procedure references, operators, properties, events, and delegates.
Following are the declaration statements in VB.Net:
S.N Statements and Description Example
1 Dim Statement Dim number As Integer
Declares and allocates storage space for Dim quantity As Integer = 100
one or more variables. Dim message As String = "Hello!"
2 Const Statement Const maximum As Long = 1000
Declares and defines one or more Const naturalLogBase As Object
constants. = CDec(2.7182818284)
3 Enum Statement Enum CoffeeMugSize
Declares an enumeration and defines the Jumbo
values of its members. ExtraLarge
Large
Medium
Small
End Enum
4 Class Statement Class Box
Declares the name of a class and Public length As Double
introduces the definition of the variables, Public breadth As Double
properties, events, and procedures that Public height As Double
the class comprises. End Class
5 Structure Statement Structure Box
Declares the name of a structure and Public length As Double
introduces the definition of the variables, Public breadth As Double
properties, events, and procedures that Public height As Double
the structure comprises. End Structure
6 Module Statement Public Module myModule
Declares the name of a module and Sub Main()
introduces the definition of the variables, Dim user As String =
properties, events, and procedures that InputBox("What is your name?")
the module comprises. MsgBox("User name is" & user)
End Sub
End Module
7 Interface Statement Public Interface MyInterface
Sub doSomething()
Declares the name of an interface and End Interface
introduces the definitions of the members
that the interface comprises.
8 Function Statement Function myFunction
Declares the name, parameters, and code (ByVal n As Integer) As Double
that define a Function procedure. Return 5.87 * n
End Function
9 Sub Statement Sub mySub(ByVal s As String)

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 19
Declares the name, parameters, and code Return
that define a Sub procedure. End Sub
10 Declare Statement Declare Function getUserName
Declares a reference to a procedure Lib "advapi32.dll"
implemented in an external file. Alias "GetUserNameA"
(
ByVal lpBuffer As String,
ByRef nSize As Integer) As Integer
11 Operator Statement Public Shared Operator +
Declares the operator symbol, operands, (ByVal x As obj, ByVal y As obj) As obj
and code that define an operator Dim r As New obj
procedure on a class or structure. ' implemention code for r = x + y
Return r
End Operator
12 Property Statement ReadOnly Property quote() As String
Declares the name of a property, and the Get
property procedures used to store and Return quoteString
retrieve the value of the property. End Get
End Property
13 Event Statement Public Event Finished()
Declares a user-defined event.
14 Delegate Statement Delegate Function MathOperator(
Used to declare a delegate. ByVal x As Double,
ByVal y As Double
) As Double

Executable Statements
An executable statement performs an action. Statements calling a procedure, branching
to another place in the code, looping through several statements, or evaluating an
expression are executable statements. An assignment statement is a special case of an
executable statement.
Example
The following example demonstrates a decision making statement:
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 10
' check the boolean condition using if statement '
If (a < 20) Then
' if condition is true then print the following '
Console.WriteLine("a is less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
BCA405-GUI Programming: Govt. Zirtiri Residential Science College
Page 20
End Module
When the above code is compiled and executed, it produces the following result:
a is less than 20;
value of a is : 10

SCOPE AND LIFETIME OF A VARIABLE


Variable’s Scope : The scope of a variable is the section of the application that can see and
manipulate the variable. If a variable is declared within a procedure, only the code in the
specific procedure has access to that variable. When the variable’s scope is limited to a
procedure it’s called local.
e.g.
Private Sub Command1_Click()
+-Dim i as Integer
Dim Sum as Integer
For i=0 to 100 Step 2
Sum = Sum +i
Next
MsgBox “ The Sum is “& Sum
End Sub
A variable whose value is available to all procedures within the same Form or Module are
called Form-wide or Module-wide and can be accessed from within all procedures in a
component. In some situations the entire application must access a certain variable. Such
variable must be declared as Public.

Lifetime of a Variable : It is the period for which they retain their value. Variables
declared as Public exist for the lifetime of the application. Local variables, declared within
procedures with the Dim or Private statement, live as long as the procedure.
You can force a local variable to preserve its value between procedure calls with the Static
keyword. The advantage of using static variables is that they help you minimize the
number of total variables in the application.
Variables declared in a Form outside any procedure take effect when the Form is loaded
and cease to exist when the Form is unloaded. If the Form is loaded again, its variables are
initialized, as if it’s being loaded for the first time.
One of the tasks performed by the application is to track the average of the numeric
values. Instead of adding all the values each time the user adds a new value and dividing
by the count, you can keep a running total with the function RunningAvg(), which is shown
below.

Calculations with Global Variables


Function RunningAvg(ByVal newValue As Double) As Double
CurrentTotal= CurrentTotal + newValue
TotalItems = TotalItems + 1
RunningAvg = CurrentTotal / TotalItems
End Function
You must declare the variables CurrentTotal and TotalItems outside the function so that
their values are preserved between calls. Alternatively, you can declare them in the
function with the Static keyword, as shown below.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 21
Calculations with Local Static Variables
Function RunningAvg(ByVal newValue As Double) As Double
Static CurrentTotal As Double
Static TotalItems As Integer
CurrentTotal = CurrentTotal + newValue
TotalItems = TotalItems + 1
RunningAvg = CurrentTotal / TotalItems
End Function
The advantage of using static variables is that they help you minimize the number of total
variables in the application. All you need is the running average, which the RunningAvg()
function provides without making its variables visible to the rest of the application.
Therefore, you don't risk changing the variables' values from within other procedures.

BCA405-GUI Programming: Govt. Zirtiri Residential Science College


Page 22

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy