Вы находитесь на странице: 1из 79

What Is Programming A

Detailed Analysis on Computer


Programming
JUNE 17, 2015
Information is usually processed in a computer when the computer
using its parts completes task. However, these tasks are not simple to
perform, when we see it in context to the language of computer. Mostly,
these tasks are performed using different languages or often called
various set of instructions to perform different tasks.

What Does Programming Mean?

Programming can be referred to a way of developing and executing


numerous sets of commands to let a computer implement different
tasks. Programming is often referred to as computer programming and
involves different activities or tasks like examination, accepting,
discerning, and disentangling problems. Programming also refers to
confirmation of requests of the set of rules together with its exactness
and its resource consumption, execution of the algorithm in an
objective programming language. The algorithm is also known as a
source code that is written by a programmer and is fed into the machine
for its execution and to see possible results. When it comes to the
generation of the source code, programmers have to choose any of the
following programming languages:
1. C
2. C++
3. C#
4. Java
5. Python
6. Smalltalk
7. JavaScript
8. Perl
9. Ruby
10. PHP

Using any of the above-mentioned languages, a programmer can


execute the source code and can find the results. The result could be a
solution to a problem, as well. Therefore, as a programmer, you need to
have deep-insight of every part of programming method i.e. from source
code formation to its execution, and from execution to the solution of
the problem. A programmer must have logical as well critical thinking
while forming a source code and executing it.

How Does It Work:


Coding is all about implementing a set of instructions using a machine
language to obtain a specific result. However, keep in mind that
machines (computers) only understand the language of on and off. A
binary code is a combination of 1s and 0s or you can simply say it a
combination of on and off. For instance, 00101100 here represent 8 bits
or 1 byte (1 Byte equals 8 bits in binary language). If you would go for
writing a source code into binary language, it will need super
imagination, logical thinking, and high-level implementation to write
that binary code as a source code. Thus, to ease up the matter, we
choose a programming language, write a source code in any chosen
language, and implement it on the machine (computer) to obtain
required results.

History of Programming Languages And Development:


Programming languages and their derivatives have been discovered
and re-discovered in order to make the programming more logical and
less prone to viruses and attacks. Back in 1843, Ada Lovelace wrote the
very first code for the Analytical Engine, also known as the Early
mechanical Computer. Since then, programming became the main
field for logical analysis and implementation of source codes on
machines.
1. Programming Era (1957-59):
FORTAN (Formula Translation), LISP (List Processor)
and COBOL(Common Business-Oriented Language) are well-thought-
out to be the ancient languages that are still used today.
Primary Uses: Supercomputing Applications, Artificial Intelligence
Development, and Business Software.
Used by: Nowadays, NASA, different credit cards, and ATMs are using one
or a combination of these languages.

2. Programming Era (1970):


Niklaus Wirth created Pascal (After French mathematician/Physicist
Blaise Pascal) back in 1970. It is a high-level language, used for
educating structured programing and data structuring. The public
versions of this language were in use in late 1980s.
Primary Uses: Teaching Programming, and Object Pascal
Used by: Apple Lisa (1983) and SKYPE.

3. Programming Era (1972):


Dennis Ritchie (Bell labs) created the programming language
called C (with the mixed version of earlier language called B) back in
1972. Often known as low-level language, it commonly created for Unix
Systems. Many other languages are known to be the full or half
derivatives of C including Java, Perl and PHP.
Primary Uses: Computer Gaming Applications, Unix System
Programming and System Development.
Used by: Unix Systems.
4. Programming Era (1983-87):
Bjarne Stroustrup (Bell labs) created the programming language
called C++ (with the mixed version of C including classes) back in
1983. It is an intermediate-level language with object-orientation and
inclusion of classes and other templates.
Brad Cox and Tom Love (Stepstone) created the programming
language called Objective-C (with an extension of object-orientation in
C language) in 1983. It is a high-level language with an extension of
object-orientation in C language and message-passing feature.
Larry Wall (Unisys) created Perl programming language in 1987. It is a
high-level programming language used for Unix Systems report
processing.

Primary Uses: C++ is used for Commercial and Embedded Software


Development and Video Gaming. Objective-C is used for Apple
Programming. Perl is used for Graphic Programming, Network System
Programming, System Development, Administration, Database
Development, and Applications.
Used by: Used by IMDB, Amazon, Apple, Adobe and Google Chrome.

5. Programming Era (1990-95):


Guido Van Rossum (CWI) created the programming
language Python back in 1991. It is general-purpose and high-level
language for introducing different programming styles within a same
language.
Yukihiro Matsumoto created RUBY in 1993. It is also a high-level
language and is used for teaching programming and to run entertaining
programming techniques.
James Gosling (Sun Microsystems) created Java programming
language in 1995. It is a high-level programming language used for
collaborative TV project with cross-platform feature. It is also known as
the worlds famous Programming language nowadays.
Rasmus Lerdorf created PHP (Previously known as Personal Home
page but now Hypertext preprocessor) in 1995. An open-source
language with Web-pages building functionality.
Brendan Eich (Netscape) created JavaScript in 1995. It is known as the
final choice after Mocha and LiveScript. It is also a high-level
programming language for designing webpages, animations, and
interactivity.
Primary Uses: Python is used for Information Security and Web
Applications. Ruby is used for Ruby on Rails and Web Development. Java
is highly used for Network programming, GUI development and Software
Development. PHP is used for server-side development and Webpages.
JavaScript is used for PDF, Web browsers, and Web Development.
Used by: Used by Gmail, Adobe, Facebook, Digg, WordPress, Android,
Google, Yahoo, Hulu, Twitter and Groupon.

Summary of Most Used Languages:


A brief summary for comparing the attributes (in %) of programming
languages is mentioned below:

Java .NET C/C++


Code Quality 82 % 73 % 78 %
Cryptographic
Issues 55 % 62 % 46 %
Information
Leakage 58 % 60 % 5%
Time And State 34 % 30 % 32 %
Directory
Traversal 49 % 56 % 40 %
Buffer Overflow 25 % 1% 48 %
SQL Injection 31 % 30 % 30 %
Market Need For Programmers/Future Of Programming:
Be it about website development, structural designing, software
development, webpage development, Web Browsers Development,
Information Security, Data Integrity, ATM communication, Online
Banking, Network Programming, Graphical user Interface development,
Server-Side Development or Database Administration or Development,
market would need programmers. These niches are so well-focused
today that there would be numerous versions of the same niche
mentioned above in the future.

Every organization or business need some level of technical expertise at


programming level for securing their enterprise. Therefore,
programmers are in high-demand in each organization and that is just
the beginning of the era. Let the entrepreneurs discover more sub-
niches and programmers would then be in high demand.
What is Visual Basic - A Detailed
Analysis on Visual Basic
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
Visual Basic is, in general, a computer programming and integrated
development environment (IDE)-enabled system developed by Microsoft.
John Kemeny and Thomas Kurts invented the very basic version of Visual
Basic that is known as BASIC. The main aim of visual basic is to provide an
easy platform to write programs that are mostly windows-based.

History and Background:


In 1991, Visual Basic 1.0 was introduced and after its introduction, the
commercial copy was released as well. Alan Cooper is highly known for his
drag and drop design work within the visual basic environment. The user
interface created by the Alan Cooper is highly developed to introduce new
way of generating programming codes for windows operating systems.
Later, Microsoft contacted Alan Cooper and offered him to develop Tripod
(the drag and drop design named after Alan Coopers company Tripod) in a
programmable form for Windows 3.0. The name was later decided to be
Ruby that has no affiliation with the programming language known as
Ruby.

The main defect in the tripod programming system was that it did not
support a programming language to further support programmable systems
within the Windows platform. Microsoft; however, took the initiative to mix
Ruby with some basic language and the rise of Visual Basic as a platform
was started. Microsoft had abandoned one of its database program known
as Omega. The amalgamation of Ruby interface together with the
Embedded BASIC engine created for Omega provided another platform to
proceed with the programmable systems. One of the best advantages of
Ruby is to support the ability of loading dynamic link libraries. These
libraries contained GIZMOS (also known as supplementary controls) that
helped the designers to design the VBX interface later. With the
advancement in the visual basic platform and programming techniques,
different visual basic versions were released both commercially and as
freeware. Freeware versions; however, did not include complete features
that the commercial released had.

Previous Versions And How It Was Developed:


After the origination of the concept of visual basic and the ability to support
flexible design, designers tried to develop and introduced new versions of
Visual basic. All of these versions fulfilled the needs of different operating
systems and programmable systems in one way or the other. Penned down
below is a summary of the different versions developed and introduced in
the market as the basic versions of visual basic:
1. Visual Basic 1.0:

Visual Basic 1.0 was released back in 1991. The sole purpose of visual
basic 1.0 was to act as a programming platform for different programmable
systems within the Windows environment.

2. Visual Basic 1.0 for DOS:

After the release of visual basic 1.0, another version with the name of
Visual Basic 1.0 for DOS was introduced back in 1992. This version was
actually the post-release for the DOS-based BASIC compilers, QuickBasic
(another compiler developed by Microsoft) and Basic Professional
Development System made by Microsoft. That was the only reason for the
non-compatibility of the language with the Visual Basic for Windows. The
features of this version greatly tackled the interface that used to stimulate
the look of a Graphical user interface with the help of ASCII characters.
3. Visual Basic 2.0:

Visual Basic 2.0 version of old Visual Basic was released back in late 1992.
The sole purpose of this release was to modify some of the buds and
speed up the overall performance of the platform. The environment was
also shifted towards an easier version to help people use the Visual Basic
easily.

4. Visual Basic 3.0:

In the mid of 1993, another version of visual basic with the name of Visual
Basic 3.0 was released. This version was further released in two different
variants namely Standard Visual Basic 3.0 and Professional Visual basic
3.0. The main addition to Visual Basic 3.0 was its provision of database
engine. The main ability of this database engine is that it could read and
write databases, normally Access Databases.
5. Visual Basic 4.0:

Visual Basic 4.0 was released in 1995. This was the first ever release of
Visual Basic that has the ability to create programs of 32-bit and 16-bit. In
addition, for the first time, this release enabled programmers to write
classes in VB.
6. Visual Basic 5.0:

In 1997, another version of visual basic was released with the name of
Visual basic 5.0. This version was enabled for 32-bit programs within the
Windows environment. One good advantage of visual basic 5.0 was that it
enabled programmers to write programs in 5.0 and import programs that
are already written in visual basic 4.0. Customer User Controls and
Compilation of codes to native windows executable codes are the two main
features of visual basic 5.0. This release also came up with speedy runtime
execution of codes.
7. Visual Basic 6.0:

In 1998, another version of visual basic hit the market with the name Visual
Basic 6.0. With this release, a number of aspects within the Visual basic
arena were improved. For the first time, programmers and designers could
mutually use Visual Basic 6.0 to create programs within the Windows
environment as well as Website applications using IE browser.

Visual Basic.NET:
Visual basic.NET is a high-language programming language with an
integrated implementation of .NET Framework. Launched in 2002, Visual
Basic.NET acted as a basic platform for programmers to program codes
within the Windows environment using .NET Framework. Visual Studio is
the next-level pack for further development of Visual Basic.NET using
integrated development environment (IDE). More important is to know
about VBC.EXE, which is a freeware command line compiler. VBC.EXE
was included in the .NET Framework SDK. A simple example to execute
Hi Buddy in a VB.NET program is given below:

?
Module Module1
1
Sub Main()
2
' The classic "Hi Buddy" demonstration program
3
Console.WriteLine("Hi, Buddy!")
4
End Sub
5
End Module
6

The code opens up with Sub Main () and ends with End Sub to execute the
main body of the program. In the above-mentioned program, the program
will execute the result as hi Buddy.

What is DOT NET (.NET) FrameworkA


Detailed Analysis on Background and
Working
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
.Net framework is a technology or a programming infrastructure used for building and
deployment of applications and services that use .NET technologies like XML web-based
services or some .NET based desktop applications. The three major parts that the .NET
framework consists of are the Common Language Runtime (CLR), the framework class library
and the ASP.NET.

History and Background:


Microsoft initiated DOT NET Framework or simple .NET Framework back in 1990s. The
original name assigned to the project was Next Generation Windows Services (NGWS).

1. .NET Framework Era (Late 2000):


The first version of DOT NET Framework was released in 2000 by the tag name of
.NET Framework 1.0. The version was introduced with IDE (Visual Studio .NET). The
very first version of .NET framework included various features like introduction of
Common Language Runtime (CLR), DLL class libraries, and provisioning of Object-
oriented web application development.

2. .NET Framework Era (2007-08):


After introducing .NET Framework version 1.1 and 2.0 adding numerous features,
the development succeeded in launching .NET Framework version 3.0. This was for
the first time that this version included Windows Presentation Foundation (also
known as WPF), Windows Communications Foundation (also known as WCF),
Windows Workflow Foundation (also known as WF) and CardSpace. Microsoft
announced the .NET Framework version 3.5 to synchronize the use of Windows 7,
XP and Server 2003.

3. .NET Framework Era (2010):


Proceeding further, Microsoft announced .NET Framework version 4.0 in 2010. The
version introduced Common Language Runtime (CLR) 4.0, Managed Extensibility
Framework (MEF), and Dynamic Language Runtime (DLR). This version also
included Task Parallel Library alongside visual studio 2010.

4. .NET Framework Era (2012-13):


The .NET version 4.5 and 4.5.1 included some enhanced features addition to
Common Language Runtime (CLR) 4.0, A-synchronization support, Windows Store
Applications accessibility feature, and some common feature enhancements to
Windows Presentation Foundation (also known as WPF), Windows Communications
Foundation (also known as WCF), Windows Workflow Foundation (also known as
WF) and ASP.NET. The .NET Framework version 4.5 and 4.5.1 also introduced Visual
Studio 2012 and 2013.

How Does .NET Framework Actually Work:


The .NET framework is used for building and deployment of applications and services
that use .NET technologies like XML web-based services or some .NET based desktop
applications. The three major parts that the .NET framework consists of are the Common
Language Runtime (CLR), the Framework Class Library (FCL), and the ASP.NET.

1. Common Language Runtime (CLR):


The main part of .NET Framework, which develops the base of the architecture, is
the Common Language Runtime (CLR). CLR acts as a bridge that is used to handles
code at execution. It is the core part of .NET Framework and is responsible for
memory management and thread management. In this way, the Common Language
Runtime (CLR) in .NET Framework empowers safety and also provide code accuracy
which is essential in order to provide security. Therefore, code management at the
time of execution is the primary role of Common Language Runtime (CLR) in .NET
Framework. Two types of codes are available in Common Language Runtime (CLR)
in .NET Framework:

1. Managed Code: Code that directly targets the Common Language Runtime
(CLR) in .NET Framework
2. Unmanaged Code: Code that does not directly targets the Common Language
Runtime (CLR) in .NET Framework

2. Framework Class Library (FCL):


The Framework Class Library (FCL) in .NET Framework is also a main part of .NET
Framework. The Class library includes the reusable classes (types) that are based on
object-orientation. This part is highly imperative while developing applications.
Applications could either be developed using command-line interface (CLI) or
Graphical User Interface (GUI). Several platforms include Windows forms, Web
Forms and ASP.NET. XML Web-based services are also used to develop
applications.

The main synchronization is required while writing a code. A code that is written in
a CLS should synchronize with that written in another CLS-based language.

Versions And How It Developed:


.NET Framework consists of nine major versions, of which two versions are further
extension of .NET Framework 4.0. Penned down below is a brief overview of the
different versions of .NET Framework:

1. .NET Framework 1.0:


The first version of DOT NET Framework was released in 2000 by the tag name of
.NET Framework 1.0. The version was introduced with IDE (Visual Studio .NET). The
very first version of .NET framework included various features like introduction of
Common Language Runtime (CLR), DLL class libraries, and provisioning of Object-
oriented web application development.
2. .NET Framework 2.0:
.NET Framework 2.0 was released in 2003 backing up with Visual Studio .NET. This
framework includes additional feature that were absent in the first version of .NET
Framework. These features include enhancement of ASP.NET and ADO.NET, mobile
ASP.NET controls preferred integrated support, more added security features,
Database management system integrated support, and IP version 6 support.

3. .NET Framework 3.0:


After introducing .NET Framework version 1.1 and 2.0 adding numerous features,
the development succeeded in launching .NET Framework version 3.0. This was for
the first time that this version included Windows Presentation Foundation (also
known as WPF), Windows Communications Foundation (also known as WCF),
Windows Workflow Foundation (also known as WF) and CardSpace. Microsoft
announced the .NET Framework version 3.5 to synchronize the use of Windows 7,
XP and Server 2003.

4. .NET Framework 3.5:


.NET Framework 3.5 extended the features missing in the processor .NET
Framework. Integrated Ajax support, LINQ, Dynamic Data, and Framework Support
with Multi-targeting are some of the key features of this framework version.

5. .NET Framework 4.0:


Proceeding further, Microsoft announced .NET Framework version 4.0 in 2010. The
version introduced Common Language Runtime (CLR) 4.0, Managed Extensibility
Framework (MEF), and Dynamic Language Runtime (DLR). This version also
included Task Parallel Library alongside visual studio 2010.

6. .NET Framework 4.5/4.5.1/4.5.2:


The .NET version 4.5, 4.5.1 and 4.5.2 included some enhanced features addition to
Common Language Runtime (CLR) 4.0, A-synchronization support, Windows Store
Applications accessibility feature, and some common feature enhancements to
Windows Presentation Foundation (also known as WPF), Windows Communications
Foundation (also known as WCF), Windows Workflow Foundation (also known as
WF) and ASP.NET. The .NET Framework version 4.5 and 4.5.1 also introduced Visual
Studio 2012 and 2013.

.NET Framework 4.5.2 has recently been launched in 2014. For Windows forms, high
DPI scenarios improvements have been made. However, for ASP.NET platform,
HTTP header scrutiny and adjustments procedures have been made to improve its
overall working.

How to Install Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
Follow this guide to install Visual Studio Express 2013 for Windows
Desktop

Visual Studio (Express 2013 for Windows Desktop) is a development tool,


which provides a rich environment where you can rapidly create modern
and complex desktop and WPF applications.

Although theoretically you could create a Desktop application without


Visual Studio (using the .NETs command-line compilers), that task would
be tedious, painful, and prone to error.
For that reason, you should always use a design tool like Visual Studio.

By the way the Express products are slimmed-down versions of their Visual
Studio 2013 counterparts and are primarily targeted for the .NET hobbyists
and students. Though completely free this version of Visual Studio is
surprising capable; Some of the most valuable features are object browsing
tools, a Windows Forms designer, the Add References dialog box,
IntelliSense capabilities etc.

The installation of the VS Express 2013 for Windows Desktop is


straightforward and smooth when accepting the default installation options.

1. Please download the Setup from the link below:


Visual Studio Express 2013 for Windows Desktop (Download Link)
2. Provide the needed details (name, email and country) and then click the
"Your Selection" link:

3. As soon as you start the wdexpress_full.exe the dialog below will be


shown up. Optionally change the install path and check the "I agree to
the License Terms and Privacy Policy" checkbox. Finally click the INSTALL
link to the bottom.
4.The setup process may take for a while so please be patient:
5. Once you get the "Setup Successful!" message click the LAUNCH link
(at the very bottom):
6. The new Welcome dialog will offer you to Sign in to Visual
Studio which is optional so just click "Not now, maybe later".
7. After a while the new dialog will be shown up saying that it's preparing
for first use.
8. Voila! Now you have the latest Visual Studio Express for Windows
Desktop running on your computer. Congratulations!
9. By default you'll see the Start Page showing Start section, Recent
Projects (empty as for now), Getting Started etc.
10. Please create a new project to be sure that everything is installed and
working properly.

For more information about creating a new project check our other tutorials.

NOTE: For long-term use you need to register your Express Edition so
please find the "Register Product" in the Help menu to get your FREE
key and unlock it. You will not be prompted again for this info. Enjoy!

Getting to know the IDE - Visual Basic


.NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson as mentioned describes some of the most important Visual
Studio features. It explains the most important windows, menus, and
toolbars that make up the environment, and show how to customize them
to suit your needs. In addition we gonna see some of the tools that provide
help while you are writing Visual Basic applications and how to use
the IDE to debug your programs.
Please notice that the Visual Studio IDE is extremely customizable which
means that you can move, hide, or modify the menus, toolbars, and
windows. You can create your own toolbars and then dock, undock, or
rearrange them. Finally you can change the behavior of the built-in text
editors and much more. However as beginner you should probably not
customize the IDE's basic menus and toolbars too much because it will
only cause confusion later.

NOTE: The screenshots in this tutorial may not look exactly like the ones
on your system because of the OS and selected style. These screenshots
were taken on a computer running Windows 8.1 so they display the
Windows 8.1 look and feel. Also it may look different if you have chosen a
different configuration (we assume you have configured VS for Visual Basic
development).

1. The New Project dialog lets you start a new project.


Use the Project Types tree view on the left to select the project category
that you want. After that select a specific project type on the right (as you
see we have selected the Windows Forms Application project type). Finally
set the location (default is My Documents), enter a name for the new
project and click OK to create the project.
2. The Toolbox window displays tools that you could use with the
currently active document. These tools are available when you are editing
an item that can contain objects such as controls and components. By
the way, these tools are grouped into sections callif you right-click a certain
tab and select one of the commands in the context menu.

3. The Properties window allows you to view and modify the properties of
the form and of the controls that it contains.

On our screenshot you may see the Properties window displaying


properties for a Button control named ButtonLogin. You can see in the
figure that the Text property of this control is "Login" and that's what the
button displays to the user.

In addition please note the drop-down list at the top of the window. Well
that list holds the names of all of the controls on the form. To select a
certain control, you can either click it on the Designer or select it from this
drop-down list.

The small icons below the dropdown determine what items are displayed in
the window and how they are arranged. For example if you click the
leftmost button, the window lists properties grouped by category and if
you click the second icon that holds the letters A and Z, the window lists the
control's properties alphabetically.

4. The Solution Explorer lets you manage the files associated with the
current solution. For example, in the Figure below, you could select
LoginForm.vb in the Solution Explorer and then click the View Code button
(the third icon from the right at the top of the Solution Explorer) to open the
form's code editor.

You can also right-click an object in the Solution Explorer to get a list of
appropriate commands for that object. This window makes it easier to find
a command by right-clicking an object related to whatever you want to do
than it is to wander through the menus.
5. The Error List window shows errors and warnings in the current
project. For example, if the code contains invalid character, this list will say
so. It's extremly useful as it clearly tells you the type of the
error(s) showing a full description, file name, line and everything else that
helps you easily find and fix the error. If you don't see the Error List it is
probably hidden. You can display it by selecting the appropriate item in
the View menu.

6. The Output window displays compilation results and output printed by


the application. Usually an application interacts with the user through its
forms and dialog boxes, but it can display information here, usually to help
you debug the code. The Output window also shows informational
messages generated by the IDE. For example, when you compile an
application, the IDE sends messages here to tell you what it is doing and
whether it succeeded.
7. The Windows Forms Designer allows you to design forms for typical
Windows applications. It lets you add, size, and move controls on a form
using your mouse. Together with the Properties window, it lets you view
and modify control properties, and create event handlers to interact with
the controls.
8. You use the Visual Basic Code Editor to write a code that responds to
control events.

The most obvious feature of the code editor is that it lets you type code, but
the code editor is far more than a simple text editor such as Notepad.

It provides many features to make writing correct Visual Basic code much
easier. For example you can create an event handler within the code
editor. The upper left part of the code editor displays a drop-down listing all
the controls.

If you select a control from the list, you can then pick an event for that
control from a second dropdown in the code editor's upper right. If you
select an event, the code editor generates a corresponding empty event
handler for you.

To make referring to the code lines easier, code editor may display line
numbers too.
To switch between design and code view:

To navigate from design to code view:


1. Right click anywhere in the Designer and select "View Code"
2. Open View menu and select "View Code"
3. Right-click the form in the Solution Explorer and select "View Code"
4. Use the hotkey "Ctrl + Alt + 0"

To navigate from code to design view:


1. Right click anywhere in the Code editor and select "View Designer"
2. Open View menu and select "View Designer"
3. Right-click the form in the Solution Explorer and select "View Designer"
4. Use the hotkey "Shift + F7"

Placing Controls on Form


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson explains how to add controls to a form

Visual Studio (Express 2013 for Windows Desktop) and its Windows
Forms Designer are configured to be quite usable. As soon as you open
the Designer you can immediately use the Toolbox to place controls on
the form.

However the Windows Forms Designer allows you to add controls to a form
in a several different ways.

1. First way is, if you double-click a control on the Toolbox, Visual Studio
places an instance of the control on the form in a default location and at a
default size. Then you can use the mouse to relocate and resize the
control.

2. Second way is, if you click a control in the Toolbox, the mouse cursor
changes while the mouse is over the form. The new cursor looks like a
plus sign with a small image of the control's Toolbox icon next to it. If you
click the form, Visual Studio adds a control at that location with a default
size.

Figure 1 (with selected control in the toolbox you click the form)
Figure 2 (Visual Studio adds a control at the location you've clicked)

3. Third way is, if you do add and configure control programmatically at


run time:

?
1
Dim CheckBox1 As New CheckBox
2
Me.CheckBox1.AutoSize = True
3 Me.CheckBox1.Location = New System.Drawing.Point(31, 144)

4 Me.CheckBox1.Name = "CheckBox1"

5 Me.CheckBox1.Size = New System.Drawing.Size(94, 17)

6 Me.CheckBox1.TabIndex = 4

Me.CheckBox1.Text = "Remember me"


7
Me.CheckBox1.UseVisualStyleBackColor = True
8
Me.Controls.Add(CheckBox1)
9
Changing Controls Properties in Visual
Basic .NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson explains how to change properties of your controls

The Properties window lets you change a control's properties at design


time. When you select control in a Form Designer or in the Solution
Explorer, the Properties window displays the properties of that control. To
change a property's value, simply click the property and enter the new
value. Meaning, for most properties, you can simply click the property
and type a new value for the control. However some properties are little
more complex than others and provide drop-down lists or special
dialogs for setting the property value.

Tip #1: If your Properties window is hidden just press F4 on your keyboard
or select Properties Windows on the View menu.

Tip #2: Arranging properties alphabetically makes it easier for many


developers to find the certain property.
Another way to set control's property is using Smart Tags. Many controls
display a smart tag when you select them on the Designer and it looks like
a little box containing a right-pointing triangle. When you click the smart
tag, a small dialog appears to let you perform common tasks for the
control quickly and easily.
NOTE: You may also set the control properties programmatically at run
time:

?
1 ' this code sets the checkbox's text property

2 Me.CheckBox1.Text = "Remember me"

Visual Basic .NET Debugging


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson explains how to debug your project

As soon as you create a new project, it is ready to run.


However if you run it immediately it will display only an empty
form containing no controls.
This form will compile and run smoothly because there is nothing to be
debugged/validated yet.

As soon as you add some controls to your form and write appropriate code
for them you will want to test your application. To do that you simply start
debugging!

There are several ways to start debugging:


1. Open the Debug menu and select "Start Debugging".
2. If youre using the Visual Basic environment settings, you can
simply press F5
3. Click Debug item in the toolbar as shown on the image below:

If there are no errors your app will run shortly after you started debugging.
Please watch the Output Windows as this window displays compilation
results and output produced by Debug and Trace statements.

Visual Basic .NET Comments


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson explains the comments in Visual Basic .NET

The comments are one of the few typographic code elements that make a
programs structure a bit easier to understand.
They do not execute and they are ignored by the compiler but are an
important part of how you organize your code.

Generally speaking, comments can help you as well as other


developers (at a later date) to understand the code purpose.

The comment starts with a single quotation mark (') and everything until
the end of the line is part of the comment and as mentioned ignored by
Visual Basic.
NOTE: you cannot use line continuation characters to make a multi-line
comment nor you can have block comment as they are not supported in
VB.NET

If you want to comment or uncomment a large block of code quickly, just


select the code and then open Edit > Advanced > Comment
Selection and Uncoment Slection respectively.

You should always use comments to make your code clear and
understandable.
' checking if the username and password are valid
If Username.Text = "admin" AndAlso Password.Text =
"mypwd" Then
Dim mForm As Form = MainForm ' instantiate the
MainForm
mForm.ShowDialog() ' display the main form
Me.Close() ' close the login form
Else
' incorrect username or password provided
Username.Text = String.Empty ' reset the
username textbox
Password.Text = String.Empty ' reset the
password textbox
' let them know that username or password is
incorrect
MessageBox.Show("Incorrect username or
password. Please try again!")
End If

Variables in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the variables in Visual Basic .NET

Generally speaking, the variables are among the most fundamental


components of programming.

A variable is an object that stores a value which can be a number, letter,


string, date etc.

If a variable contains a value, the program can manipulate it. Meaning, it


can perform arithmetic operationson numbers, string operations on
strings (concatenate, calculate substrings, finding a match within string and
so on), date operations (find the difference between two dates, add a time
period to a date), and so forth.
The variable's behavior is determined by:

1. Scope - it indicates the scope levels from where the variable can be
accessed (private, public etc.)
2. Data type - can be an Integer, String, Boolean etc.
3. Accessibility - determines what code in other modules can access the
variable
4. Lifetime - determines how long the variable value is valid

For instance, any variable declared inside a subroutine has scope equal
to the subroutine and cannot be accessed by the code outside of the
subroutine.

?
1 Private Sub DoSomething()

2 Dim InsideVariable As String = String.Empty;

3 ' Do Something with the variable

4 End Sub

6 Console.Write(InsideVariable)

' ERROR: variable is not in scope (can't be accessed from outside)


7

In Visual Basic you use the keyword Dim to tell Visual Basic officially that
you want to declare a variable.
You can avoid the Dim only if you specify Private, Public, Protected etc.
however a variable delared using a Dim keyword is Private by default so
the next two declarations are identical:
?

1 Dim MyString As String = String.Empty

2 Private MyString As String = String.Empty

Arithmetic Operators in Visual Basic


.NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the Arithmetic operators in Visual Basic

An arithmetic operator is a code element that performs some operation


on one or more values and creates a result. Those values are
called operands. For example, in the next statement, the operator is *
(multiplication), the operands are A and B while the result is assigned to the
variable C:

?
1 C = A * B

Here we have a table that lists the most used arithmetic


operators provided by Visual Basic:

OPERATOR PURPOSE EXAMPLE RESULT

+ Addition 2+2 4

- Substraction 4-2 2

- Negation 1 operand* -2 -2

* Multiplication 2*2 4

/ Division 4/2 2

\ Integer Division 9\2 4

^ Exponentiation 2^3 2*2*2=8

Mod Modulus 4 Mod 2 0

Most of you are already familiar with these except


maybe Modulus and Integer Division that may need a little more
explanation:

As shown in the table, \ operator performs integer division and returns the
result of dividing the first operand by the second, dropping any remainder.
It's very important to understand that the result is truncated toward zero,
not rounded.

The Mod operator returns the remainder after dividing the operand by the
second one e.g. 5 Mod 2 = 1 because 5 = 2 * 2 + 1
The following example code prints all even numbers in range 1 to 10:

?
1
For i As Integer = 1 To 10
2 If i Mod 2 = 0 Then

3 Console.WriteLine(i) ' an even number

4 Else

5 ' we do nothing as the number is odd

End If
6
Next
7

Getting User Inputs in Visual Basic


.NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson illustrates how do you get an user input in Visual Basic

It often happens that you need to prompt the user to enter an expected
value.

You could do it using InputBox method which displays a prompt in a dialog


box or using a console application using ReadLine method which reads the
next line of characters.

VB.NET Console Application:

?
Dim nl As String = Environment.NewLine
1
' say hi and ask them for a name
2
Console.WriteLine("Hello there. What's your name?" + nl)
3
Dim input = Console.ReadLine()
4
' say something to the user
5 Console.WriteLine(nl & "Nice to meet you " & input & "." & nl)

6 Console.Read()

VB.NET Windows Forms Application:

?
1
2 Dim prompt As String = String.Empty
3 Dim title As String = String.Empty
4 Dim defaultResponse As String = String.Empty
5
Dim answer As Object
6 ' Set prompt.
7 prompt = "Hello there. What's your name?"
8 ' Set title.
9 title = "Getting user input"
10 ' Set default value.
defaultResponse = "Your name here"
11
12 ' Display prompt, title, and default value.
13 answer = InputBox(prompt, title, defaultResponse)
14
15 ' Say something to the user
16 Messagebox.Show("Nice to meet you " & answer)
17

f ElseIf Else Statements in Visual Basic


.NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to write a code that selectively perform
different actions depending on the circumstances.

When you want to choose between executing two different blocks of code
depending on the result of a Boolean expression, you usually use an if
statement.

An if statement may be composed of complex expressions as well and can


contain else/elseif statements to perform more complex testing.
Whenever you need to choose between executing two different blocks
of code depending on the result of a Boolean expression, you use an if
statement.
The syntax of an if statement is as follows:

?
1 If booleanExpression = True Then

2 DoSomething()

3 Else

4 DoSomethingElse()

5 End If

' NOTE: an if statement is optionally followed by an else clause


6

Meaning, if booleanExpression evaluates to true, DoSomething() runs;


otherwise, DoSomethingElse()runs. The Else keyword and the
subsequent code are as previously mentioned optional. If there is no else
clause and the booleanExpression is false, execution continues with
whatever code follows the if statement.

Sometimes when you need to evaluate an identical expression with a


different value you write a cascading if statement using ElseIf clause

?
1
Dim IsUsernameValid As Boolean
2
If Username.Text = "user" Then
3 IsUsernameValid = False

4 ElseIf Username.Text = "admin"

5 IsUsernameValid = True

6 Else

IsUsernameValid = False
7
End If
8
' NOTE: an if statement is optionally followed by an ElseIf clause as well
9
Conditional and Logical Operators in
Visual Basic .NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the Conditional and Logical operators.

For building complex expressions, VB.NET offers an expected set


of Logical and Bitwise Operators as shown below:

Not Is performing logical negation on a Boolean expression, or bitwise


negation on a numeric expression. (For a Boolean negation, the data type
of the result is Boolean. For a bitwise negation, the result data type is the
same as that of expression but if expression is Decimal, the result is Long.)

?
1 Dim IsUsernameValid As Boolean

2 IsUsernameValid = Not (Username.Text = "admin")

And Is performing a logical conjunction on two Boolean expressions, or a


bitwise conjunction on two numeric expressions. (In a Boolean comparison,
the And operator always evaluates both expressions)

?
1 Dim IsUserValid As Boolean

2 IsUserValid = (Username.Text = "admin") And (Password.Text = "mypwd")

AndAlso Is performing short-circuiting logical conjunction on two


expressions (In a Boolean comparison, AndAlso performs short-circuiting,
which means that if expression1 is False, then expression2 is not
evaluated.)

?
1 Dim IsUserValid As Boolean
2 IsUserValid = (Username.Text = "admin") AndAlso (Password.Text = "mypwd")

Or Is performing a logical disjunction on two Boolean expressions, or a


bitwise disjunction on two numeric expression (In a Boolean comparison,
the Or operator always evaluates both expressions)

?
1 Dim IsPasswordValid As Boolean

2 IsPasswordValid = (Password.Text = "mypass") Or (Password.Text = "mypwd")

OrElse Is performing short-circuiting inclusive logical disjunction on two


expressions (In a Boolean comparison, OrElse performs short-circuiting
which means that if expression1 is True, then expression2 is not
evaluated.)

?
1 Dim IsPasswordValid As Boolean

2 IsPasswordValid = (Password.Text = "mypwd") OrElse (Password.Text = "mypass")

Xor Is performing a logical exclusion on two Boolean expressions, or a


bitwise exclusion on two numeric expressions. (In a Boolean comparison,
the Xor operator always evaluates both expressions as there is no short-
circuiting counterpart to Xor, because the result always depends on both
operands.)

?
1 Dim IsUsernameValid As Boolean

2 IsUsernameValid = (Username.Text = "admin") Xor (Username.Text = "user")

Concatenate Strings in Visual Basic


.NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson explains concatenating strings in Visual Basic .NET

Visual Basic provides two concatenation operators: + and &. Both join
two strings together.

Because the + symbol also represents an arithmetic operator, your code


will be easier to read if you use the & symbol also knows as ampersand, for
concatenation.

Using & can also make your code faster and lead to fewer problems
because it lets Visual Basic know that the operands are strings.

?
1 ' make a full name concatenate the first and the last name

2 Dim FullName As String = String.Empty

3 FullName = FirstName.Text & " " & LastName.Text

4 ' test the result

Console.WriteLine(FullName)
5

Get Length of Strings in Visual Basic


.NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the String.Length Property

The String type has a built-in Length property, which returns an


integer that represents the number of characters in the string (its length).
Those characters include things like spaces as well
as punctuation marks.

For example the string "Hello World!" is not only 10 characters long.
Rather its length is 12 because of the empty space and the exclamation
mark.
this example demonstrates the Length property:

?
1 Dim MyString As String = String.Empty
2 MessageBox.Show(MyString.Length) ' = 0
3 MyString = "Hello World!"
4 MessageBox.Show(MyString.Length) ' = 12

Sub Strings in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson is teaching you how to work with substrings.

You often manipulate strings by using a set of characters that appears at


the start, at the end, or a set that appears somewhere in between. Those
sets are called substrings.

The Substring method allows you to grab a set of characters from any
position in the string and can be used in two ways.

The first way is to give it a starting point/index and a number of characters


to grab (length of the string data).

In this example we instruct it to start at character position 0 (the beginning


of the string), and grab the next 5 characters:

?
1 Dim MyString As String = "Hello World!"

2 Dim substring As String = MyString.Substring(0, 5)

3 MessageBox.Show(substring) ' = Hello

The other way is calling Substring method with a single argument.

When you're providing only one parameter it tells the Substring to start at
the given position and copy everything right up to the end of the string
data.

In this example we instruct it to grab everything at the index 6 and following


that index:

?
1 Dim MyString As String = "Hello World!"

2 Dim substring As String = MyString.Substring(6)

3 MessageBox.Show(substring) ' = World!

Formatting Strings in Visual Basic


.NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to format the strings in VB.NET

The String.Format method is taking a composite formatting string


parameter that contains literal characters plus placeholders for values.
Other parameters in the the method gives the values.

The value placeholder has the next format:


{ index [, alignment ][: format_string ] }

The index value gives the index numbered (zero based) of the parameter
that should be inserted in that placeholder's position.

?
1 Dim project As String = "World"

2 Dim result As String = String.Format("Hello {0}!", project)

3 MessageBox.Show(result) ' = Hello World!


The alignment value is optional and it defines a minimum number of
spaces the item should use.
If alignment is negative, the result is left-justified and if it's positive, the
result is right-justified.

?
1 Dim amount As Decimal = 500

2 Dim result As String = String.Format("{0, -20} {1, -3} dollars", _

3 "Thanks for paying me ", amount)

4 Console.WriteLine(result) ' = Thanks for paying me 500 dollars

The format_string is also optional and indicates how the item will be
formatted:

?
1 Dim amount As Decimal = 500

2 Dim result As String = String.Format("{0, -20} {1, 10:c}", _

3 "Thanks for paying me ", amount)

4 Console.WriteLine(result) ' = Thanks for paying me $500.00

Please notice that braces { } are required

Check if String Contains, Replacing


Sub Strings - Visual Basic .NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the Contains and Replace methods

The String.Contains method is used when you want to check whether


a specified substring occurs within the string.
It returns True if the value parameter occurs within the string, otherwise it
returns False.
The String.Replace method is used when you want to replace all
occurences of a specified string with another specified string.
It returns new string that is same as the current string except that all
instances of oldValue are replaced with newValue.
If oldValue is not found this method returns the same string unchanged.

Dim OriginalString As String = "Hello User"


Dim ModifiedString As String = String.Empty;
If OriginalString.Contains("Hello") Then
ModifiedString =
OriginalString.Replace("Hello", "Good Bye")
Console.WriteLine(ModifiedString) ' = Good Bye
User"
End If

Comparing Strings in Visual Basic


.NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the methods for comparing the values of
strings.

The most common way to compare two strings is the following:

?
1 Dim MyStringA As String = "Hello World!"

2 Dim MyStringB As String = "HELLO WORLD!"

3 If MyStringA = MyStringB Then

4 ' Do something

5 Else

' Do something else


6
End If
7

However in some situations this approach is not efficient because it offer


no options for case and cultural variance like the other .NET built-in value-
comparison methods.

1. String.Compare: compares two strings and returns integer as


result indicating their position in sort order this method is culturally
aware and has overloads that regard or disregard case-sensitivity and
cultural difference. The result as mentioned is an integer and can be:

negative number (MyStringA is less than MyStringB)


zero (MyStringA equals MyStringB)
positive number (MyStringA is greater than MyStringB) or 1 if Value is
Nothing

?
1 Dim MyStringA As String = "Hello World!"

2 Dim MyStringB As String = "HELLO WORLD!"

3 If String.Compare(MyStringA, MyStringB) = 0 Then

4 ' Do something

5 Else

' Do something else


6
End If
7

2. String.CompareOrdinal: compares two strings but without


considering the local culture.
this method is mainly used for strings ordering and sorting.

?
1 Dim MyStringA As String = "Hello World!"

2 Dim MyStringB As String = "HELLO WORLD!"

3 If String.CompareOrdinal(MyStringA, MyStringB) = 0 Then

4 ' Do something

5 Else

' Do something else


6
End If
7
3. String.CompareTo: compares a string that encapsulates to other
string.
this method is also mainly used for strings ordering and sorting.

?
1 Dim MyStringA As String = "Hello World!"

2 Dim MyStringB As String = "HELLO WORLD!"

3 If MyStringA.CompareTo(MyStringB) = 0 Then

4 ' Do something

5 Else

' Do something else


6
End If
7

You could also use String.Equals to find out if two strings have the same
value

The Select Case Statement


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to write a Select Case statement for
multiple selection.

Beside the if statement there is another conditional statement which is


Select Case.

It is a powerful and easy-to-use technique for making a decision from


several options.

Actually the Select Case statement is nothing but an instance of the If


Then ElseIf structure.

I would suggest using of Select Case whenever you have more than three
else if statements.
In a Select Case statement, every case has its own block.

Dim intDay As Integer = 4


Dim strDay As String = String.Empty
Select Case intDay
Case 1
strDay = "Sunday"
Case 2
strDay = "Monday"
Case 3
strDay = "Tuesday"
Case 4
strDay = "Wednesday"
Case 5
strDay = "Thursday"
Case 6
strDay = "Friday"
Case 7
strDay = "Saturday"
Else
strDay = "There is no such day"
End Select Console.Write(strDay) ' = Wednesday

As you see Select Case provides more compact and more elegant code
than multiple nested if statements.

For Next Loop in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to use the For Next loop in Visual Basic
.NET.

We can safely say that For Next loop is the simplest loop to understand
and it's certainly the most commontype of looping statement in Visual
Basic.

Its syntax is as follows:

?
For variable [As data_type ] = start_value To stop_value [ Step increment ]
1
statements
2
[Exit For]
3
statements
4 [Continue For]

5 statements

Next [ variable ]
6

The variable value is the looping variable that controls the loop so when
the app reaches the For statement, it sets variable equal to start_value .
Then it compares variable to stop_value and if variable has passed
stop_value, the loop exits.

?
1 For i As Integer = 0 To 10 Step 1

2 Console.WriteLine(i)

3 Next i

Visual Basic doesn't require the variable's name in the Next statement, but
it makes the code easier to read

Note: the loop may not execute even once depending on the start and
stop values.

For Each Loop in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to use the For Each loop in Visual Basic
.NET.

The For Each loop iterates over the items in a collection, array, or other
container class that supports For Each loops.

Its syntax is as follows:

?
1
For Each variable [As object_type ] In group
2 statements

3 [Exit For]

4 statements

5 [Continue For]

statements
6
Next [ variable ]
7

In this loop, group is a collection, array, or other object that supports For
Each and it's important that control variable must be of a data
type compatible with the objects contained in the group.

Visual Basic doesn't automatically understand what kind of objects are


stored in a collection or array until it "tries" to use them.

If the control variable's type is not compatible with an object's type, the
program generates an error.

?
1 For Each user As User In Users

2 Console.WriteLine(user.Username)

3 Next user

Note: Visual Basic doesn't require the variable's name in the Next
statement, but it makes the code easier to read

Exiting For Loop in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to exit For Next loop in Visual Basic .NET.

To leave a For loop before it would normally finish you use the Exit For
statement.

For example, the following code loops through an array looking for value
10.
When it finds the element with value 10 it uses Exit For to immediately
stop looping.

?
1 Dim array() As Integer = {1, 3, 5, 7, 10, 20, 50}

2 For i As Integer = 0 To array.GetUpperBound(0)

3 If (array(i) = 10) Then

4 'Quit the loop immediately

5 Exit For

End If
6
Next
7

The Exit For statement exits only the For loop immediately
surrounding the statement.
If a For loop is nested within another For loop, the Exit For statement only
exits the inner loop.

Continue For Loop in Visual Basic


.NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to Continue For loop in Visual Basic .NET.

When you want to start your loop over again you use the Continue
For statement which makes the loop jump back to its For statement and
increment its looping variable.

This is particularly useful if the program doesn't need to execute the rest of
the steps within the body of the loop and wants to start the next iteration
quickly.

?
1
Dim array() As Integer = {1, 3, 5, 7, 10, 20, 50}
2 For i As Integer = 0 To array.GetUpperBound(0)

3 If (array(i) <> 10) Then

4 'Continue the loop

5 Continue For

End If
6
Console.WriteLine(array(i))
7
Next
8

This will not execute Console.WriteLine(array(i)) when value is not 10 but


will be executed when value is 10.

Do Until Loop in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to use Do Until loop in Visual Basic .NET

One of the Do Loop statements variations is the Do Until and it keeps going
until something happens (until a condition is true).

Its syntax is as follows:

?
1 Do {Until} condition

2 statements

3 [Exit Do]

4 statements
5 Loop

Meaning the Until loop keeps running until the condition is satisfied. In this
type of loop, there is not a control variable in itself so you have to keep
track of the current position of the loop.

1 Dim array() As Integer = {1, 3, 5, 7, 10, 20, 50}

2 Dim counter As Integer = array.GetUpperBound(0) + 1

3 Do Until counter > 0

counter -= 1
4
'print the array elements
5
Console.WriteLine(array(counter))
6
Loop
7
' Visual Basic won't execute the statements because counter is already greater
8 than 0

Do While Loop in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to use Do While loops in Visual Basic .NET

One of the Do Loop statements variations is the Do While and it executes


as long as a condition is true (while a particular condition is true).

Its syntax is as follows:

?
1 Do {While} condition

2 statements
3 [Exit Do]

4 statements

Loop
5

This While loop keeps running as long as the expression is True. As soon
as the expression becomes False, it stops.

?
1
Dim array() As Integer = {1, 3, 5, 7, 10, 20, 50}
2 Dim counter As Integer = array.GetUpperBound(0) + 1

3 Do While counter > 0

4 counter -= 1

5 'print the array elements

6 Console.WriteLine(array(counter))

Loop
7
' this loop prints out all the array elements
8

Exit Do Statement in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the quitting Do loops in Visual Basic .NET

The Exit Do statement allows the program to leave the nearest enclosing
loop before it would normally finish.

Meaning, it lets you end a loop early and can be used e.g. when testing an
endless loop.

Its syntax is as follows:

?
1 Do {While} condition

2 statements

3 [Exit Do]

4 statements

Loop
5

In the following example, condition stops the loop if the counter is equal to
zero. The If statement in the loop, however, causes the Exit Do statement
to stops the loop when the array element value is 10:

?
1
Dim array() As Integer = {1, 3, 5, 7, 10, 20, 50}
2
Dim counter As Integer = array.GetUpperBound(0) + 1
3
Do While counter > 0
4 ' quit the do loop if element's value is 10

5 If array(counter) = 10 Then

6 Exit Do

7 End If

8 counter -= 1

'print the array elements


9
Console.WriteLine(array(counter))
10
Loop
11
' this loop prints out only 50 and 20
12

Infinite Loop in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the Infinite Loops in Visual Basic .NET

When you work with loops, you can easily create an infinite loop. This is a
loop that is never finishing. This logic error is one of the most difficult
to find and troubleshoot so you should be very careful when you work
with loops to not end up with loops whose exit condition can never be
satisfied.

Tip: Whenever you suspect a program has fallen into an infinite loop, just
force the program to stop using Debug menu - Stop Debuging or use Ctrl
+ Shift + A in your Visual Studio.
This will stop the program immediately.

The following code is a classic example of an infinite loop and will not
stop:

?
1 Dim counter As Integer = 10

2 Do While counter > 0

3 counter += 1 ' + instead -

4 'Do something

5 Loop

' this loop just keeps going forever as counter is always greater than 0
6

MessageBox Dialog in Visual Basic


.NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson explores MessageBox dialog and demonstrates how you
can use it in your Visual Basic applications.

MessageBox is one of these built-in dialog boxes that help you to provide
a rich user interface in your front-end applications.

As a developer you will use this dialog pretty often as it lets you to
display custom messages to your users and accept their input regarding
the choice that they have made.
It's very flexible and provide many properties and methods that enable you
to customize them to suit your needs.

You can customize it to display a variety of icons with your messages and
choose which buttons to display while still maintaining the standard
look of Windows Forms application.

The MessageBox suports the following standard icons:

MEMBER ICON

Asterisk Information Icon

Information Information Icon

Error Error Icon

Hand Error Icon

Stop Error Icon

Exclamation Exclamation Icon

Warning Exclamation Icon

Question Question Icon

None Will not display any icon

It also supports the following combinations of buttons:

MEMBER DESCRIPTION

Abort, Retry, and Ignore


AbortRetryIgnore
buttons

OK an OK button

OKCancel OK and Cancel buttons

RetryCancel Retry and Cancel buttons


YesNo Yes and No buttons

YesNoCancel Yes, No, and Cancel buttons

To display the message box you call its Show method which by the way,
cannot be inherited because it's shared so the only way to change the
default MessageBox behaviour is using windows hooks.

?
1 MessageBox.Show( "The username or password you entered is incorrect", _

2 "Login Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Stop)

Get the message box response clicked


by user:
You can get the response of the message box clicked by the user (Yes, No,
Cancel, etc) by using the following code:

?
Dim msgRslt As MsgBoxResult = MsgBox("Are you 21 years old or older?.", MsgBoxStyle.Y
1
If msgRslt = MsgBoxResult.Yes Then
2
MsgBox("You are welcome to join.")
3
ElseIf msgRslt = MsgBoxResult.No Then
4
MsgBox("You must be at least 21 years old to join.")
5
End If
6

Input Box in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson explores InputBox dialog and demonstrates how you can
use it in your Visual Basic applications.

When you need to prompt the user to enter an expected value you use
InputBox.

It displays a prompt in a dialog box, waits for the user to enter value and
finally returns a string containing the entry.

Except the prompt all other parameters are optional!

?
1 Dim prompt As String = String.Empty

2 Dim title As String = String.Empty

3 Dim defaultResponse As String = String.Empty

4
Dim answer As Object
5
' Set prompt.
6
prompt = "Hello there. What's your name?"
7
' Set title.
8
title = "Getting user input"
9
' Set default value.
10 defaultResponse = "Your name here"

11

12 ' Display prompt, title, and default value.

13 answer = InputBox(prompt, title, defaultResponse)

14

15 ' Say something to the user


16 Messagebox.Show("Nice to meet you " & answer)

17

Subroutines in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes Subroutines in Visual Basic .NET

By definition, a Visual Basic Soubroutine is chunk of code enclosed by


the Sub and End Sub.
It performs a task for the code that invokes it and unlike the
Function does not return a value.

Its syntax is as follows:

?
1 [ accessibility ] Sub routine_name [ paramaters ]

2 statements

3 End Sub

The accessibility can be Public, Protected, Friend, Protected Friend, or


Private and determines which pieces of code can invoke the subroutine.

The name of the subroutine must be a valid Visual Basic identifier and
should begin with a letter or an underscore.

The parameters are declared similarly to how you declare


variables specifying passing mechanism, name, datatype and if the
parameter is optional.

The passing mechanism determines the interaction between the


element's data type and the passing mechanism.

If you include ByVal keyword in the declaration, the subroutine makes own
local copy of the parameter and then can modify this value without
affecting the value of the original parameter.
If you include ByRef keyword in the declaration, the subroutine does not
create a separate copy of the parameter variable.
Instead, it uses a reference to the original parameter passed into the
subroutine and any changes the subroutine makes to the value are
reflected in the calling subroutine too.

To declare an optional parameter you use Optional keyword, so the code


that uses it may omit that parameter.

1 Private Sub DoSomething(Optional ByVal message As String = "")

2 ' do something

3 End Sub

Most importantly the subroutines allow you to extract code that you may
need to use under more than one circumstance and place it in one
location where you can call it as needed:

1 Private Sub ShowWarningMessage(ByVal message As String, ByVal title As String)

MessageBox.Show( message, title, MessageBoxButtons.OK,


2
MessageBoxIcon.Exclamation)
3 End Sub

Then whenever you want to warn your user you simply call the
ShowWarningMessage subroutine e.g.

?
1 ShowWarningMessage("Please provide a valid email.", "Warning")

Functions in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes Functions in Visual Basic .NET

By definition, a Visual Basic Function is chunk of code enclosed by


the Function and End Function.
It performs a task for the code that invokes it and then returns some
value.

Meaning, they are basically the same as subroutines, except that they
return some sort of value.

Its syntax is as follows:

?
1 [ accessibility ] Function function_name [ paramaters ] [As return_type ]

2 statements

3 End Function

The accessibility can be Public, Protected, Friend, Protected Friend, or


Private and determines which pieces of code can invoke the function.

The name of the function must be a valid Visual Basic identifier and
should begin with a letter or an underscore.

The parameters are declared similarly to how you declare


variables specifying passing mechanism, name, datatype and if the
parameter is optional.

The passing mechanism determines the interaction between the


element's data type and the passing mechanism.

If you include ByVal keyword in the declaration, the function makes own
local copy of the parameter and then can modify this value without
affecting the value of the original parameter.

If you include ByRef keyword in the declaration, the function does not
create a separate copy of the parameter variable.
Instead, it uses a reference to the original parameter passed into the
subroutine and any changes the function makes to the value are reflected
in the calling function as well.
To declare an optional parameter you use Optional keyword, so the code
that uses it may omit that parameter.

?
1 Private Function GetValue(Optional ByVal entry As String = "") As String

2 Return entry

3 End Function

The function can set its return value either by setting its name equal to the
value it wants to return, or by using the Return keyword followed by the
value that the function should return.

?
1
Private Function GetValue(Optional ByVal entry As String = "") As String
2
Dim result As String = String.Empty
3 If entry = "" Then

4 result = "No value found"

5 Else

6 result = entry

End If
7
GetValue = result
8
End Function
9

OR

?
1 Private Function GetValue(Optional ByVal entry As String = "") As String

2 Dim result As String = String.Empty

3 If entry = "" Then

4 result = "No value found"

5 Else

result = entry
6
7 End If

8 Return result

End Function
9

Most importantly the functions allow you to extract code that you may
need to use under more than one circumstance and place it in one
location where you can call it as needed:

?
1 Private Function CubeVolume(ByVal x As Double) As Double

2 Dim result As Double = 0

3 result = x * x * x

4 Return result

End Function
5

Then whenever you want to calculate the cube volume you simply call
the CubeVolume with side of the cube as parameter provided e.g.

?
1 Console.WriteLine("The volume of the cube is: " & CubeVolume(5))

Exit Sub Statement in Visual Basic


.NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to use Exit Sub in Visual Basic .NET

The Exit Sub statement is an unconditional jump command


that stops performing tasks early (if necessary).

It makes the program stop executing the current subroutine but unlike
GoTo and such, cannot make the program jump around arbitrarily, possibly
leading to spaghetti code.

Ex example of Exit Sub statement:


?
1 Private Sub MyTask(ByVal size As Integer)

2 For i As Integer = 0 To size

3 If i = 10 Then

4 Exit Sub ' should stop the task early

Else
5
MyTextBox.Text &= "The value of i is: " & i.ToString &
6 Environment.NewLine

7 End If

8 Next

9 End Sub

Global Variables in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the global variables in Visual Basic .NET

A global variable is a variable with global scope, and unlike the local
variable can be accessed from anywhere.

Meaning when the variable is available globally, any code in your


application has access to read and modify this variable.

For storing global variables in VB.NET you "usually" have a Module


because it's static and doesn't have to be instantiated.

?
1 Module GlobalVariables

2 ' sets the Form's text property (title)

3 Public global_FormText As String = "Hello World!"

4 End Module

Then you can call global_FormText like so:


?
1 Me.Text = global_FormText

2 ' or

3 Me.Text = GlobalVariables.global_FormText

Arrays in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to declare and use arrays in Visual Basic
.NET

Whenever you need to hold a list of similar or related data you use an
array. Arrays can only hold a single data type.

To declare an array you use parentheses and unlike the standard variable
it can hold more than one value.

For example, the following code declares an one-dimensional array of


Strings named days with seven elements:

?
1 Dim days(6) As String

2 ' arrays are zero-based (the numbering in an array starts at zero)

To initialize an array you place the values inside curly braces separated
by commas. The following code initializes a one-dimensional array of
Strings:

?
' Like this:
1
Dim days(6) As String = _
2
{ "Sunday", "Monday", "Tuesday", "Wednesday", _
3 "Thursday", "Friday", "Saturday" }

5 ' Or like this:

6
' Declare the array
7
Dim days(6) As String
8

9
' Populate the array
10
days(0) = "Sunday"
11
days(1) = "Monday"
12
days(2) = "Tuesday"
13 days(3) = "Wednesday"

14 days(4) = "Thursday"

15 days(5) = "Friday"

16 days(6) = "Saturday"

17

18

To access individual element in the array you do it by providing


an index value between 0 and a maximum possible value (total size of
the array less 1) e.g.

?
1 Dim days(6) As String = _

2 { "Sunday", "Monday", "Tuesday", "Wednesday", _

3 "Thursday", "Friday", "Saturday" }

4 Console.WriteLine(days(0)) ' = Sunday

Dates in Visual Basic .NET


Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the Dates in Visual Basic .NET

To represents an instant in time in Visual Basic .NET, you tipically use


the DateTime Structure.

This structure supports many helpful methods that you can be used for
various tasks like getting yesterday's date or the current month name.

When you declare the DateTime variable its default value is 1/1/0001,
12:00 AM midnight e.g.

?
1 Dim defaultDate As DateTime

2 Console.WriteLine(defaultDate.ToShortDateString & ", " & defaultDate.ToShortTimeStrin

3 ' this code yields to 1/1/0001, 12:00 AM

However you can easily set its value to Today's date:

?
1 Dim TodaysDate As DateTime = DateTime.Now

2 Console.WriteLine(TodaysDate.ToShortDateString & ", " & TodaysDate.ToShortTimeString)

3 ' this code yields to 5/11/2014, 2:26 PM

Then you can go further and for example, get the Yesterday's date:

?
1 Dim YesterdayDate As DateTime = DateTime.Now.AddDays(-1)

2 Console.WriteLine(YesterdayDate.ToShortDateString & ", " & YesterdayDate.ToShortTimeS

3 ' this code yields to 5/10/2014, 2:26 PM

You can also display the result in a format defined by a specific format
specifier e.g.
?

1 Dim TodaysDate As DateTime = DateTime.Now

2 Console.WriteLine(TodaysDate.ToString("g"))

3 ' this code ALSO yields to 5/11/2014, 2:26 PM

You can additionally format your date using specific culture e.g.

1 Dim TodaysDate As DateTime = DateTime.Now

Console.WriteLine(TodaysDate.ToString("F"), New
2
System.Globalization.CultureInfo("fr-FR"))
3 ' this code yields to: dimanche 11 Mai, 14:26:00

Erros and Catching Them in Visual


Basic .NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to handle errors in Visual Basic .NET

Error handling is a very important part of any application.

In Visual Basic, the error mechanism is based on the concept


of exceptions that can be thrown to raise an error and caught when the
error is handled.

If you don't have an error handling in your code and an error occurs, your
users receive a message about an unhandled exception, and then the
program may terminate.

This message is not a user-friendly and does not inform the users about
the true nature of the error or how to resolve it.

The unhandled exception could also cause users to lose the data that they
were working with which can be very frustrating.

The structured error handling statements that Visual Basic offers is a


great way to organize blocks of code in a structure that handles errors.
This mechanism is incorporated with the Try... Catch... Finally block and
helps you to incorporate error handling into your programs with very little
effort.

Esentially you execute the code that might throw an exception in the Try
block, and you handle the errors in the Catch block.

The Finally block, which is optional, is always executed if present and


helps you cleanup your code regardless of whether an error has occurred.

Usually in the Finally block you keep your dispose and close
methods like connection.Close() that unsures that your connection is
closed no matter what error you get in the Try block.
?

1
Dim connection As New SqlConnection("connection_string")
2
Try
3
connection.Open()
4
Dim command As SqlCommand = connection.CreateCommand
5
command.CommandText = "SELECT FieldName FROM Table1"
6
Dim reader As SqlDataReader = command.ExecuteReader
7 While reader.Read

8 ' Do something with the reader(0).ToString

9 End While

10 reader.Close()

command.Dispose()
11
Catch ex As Exception
12
' display the error
13
Console.Write(ex.Message)
14
Finally
15
connection.Close() ' this code will be always executed
16
End Try
Breakpoints in Visual Basic .NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the breakpoints in Visual Basic .NET

Sometimes when you try to debug only a small part of already large
program you will want your code to run up to a certain point and then stop
there.

This is where breakpoints come in handy as they cause execution of your


code to stop anywhere they are set.

The breakpoints can be set anywhere in the code and that code will
execute to that point and then will stop.

Note: Execution of the code stops before executing the code on which the
breakpoint is set.

The breakpoints can be set when you write your code, or you can set
them at runtime by switching to your code and setting the breakpoint at
the desired location.

To set a breakpoint you click the gray margin next to the line you want to
debug or press F9 on your keyboard.
When Visual Studio encounters a breakpoint, execution of your code
halts, and then the program gets in a break mode.

When your program gets in a break mode, a lots of debug


features become available.
Publish Application in Visual Studio
2013
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to publish an application in Visual Studio
2013 Express

To make your application available for distribution in a local file, FTP site,
or web site you need to first publish it.

1. Right-click your project in the Solution Explorer and


choose Publish from the context menu or use the Build
menu selecting Publish [Your Project Name]

2. Specify the location to publish your application:

3. Select install type (how will users install your application):


4. Define where will the application check for updates:

5. Click Finish. Voila! Congratulations, you published your first


application successfully.
This is how your setup should look like:

Вам также может понравиться