You are on page 1of 39
Visual Basic 2008 Part 1: Setup…………………………………………………………………………… .. … 4 Part 2: Creating a Project………………………………………………………………… 6 Run

Visual Basic 2008

Part 1: Setup……………………………………………………………………………

..

4

Part 2: Creating a Project………………………………………………………………… 6 Run Visual Basic 2008 ……………………………………………………………… 6

File | New Project …………………………………………………………………

....

6

Part 3: The Windows Form Designer……………………………………………………. 8

Part 4:

Basic Concepts……………………………………………………………………. 12

Variables………………………………………………………………………………12

Operators……………………………………………………………………… 12 ...........

If………………………………………………………………………………………13

The Select Case

End

Select Structure……………………………………………….13

For

Next

Loop………………………………………………………………………14

While ...

End

While Loop……………………………………………………………

14

Properties and events…………………………………………………………………15

Common properties of objects………………………………………………………. 15 Objects……………………………………………………………………………… 15

Button………………………………………………………………

..

15

Label……………………………………………………………………… .16 TextBox……………………………………………………………………. 16 Timer………………………………………………………………………. 16 ListBox……………………………………………………………………. 16

ComboBox………………………………………………………….……

..

16

Exercise 1…………………………………………………………………. 16

1

Exercise 2…………………………………………………………………

..

17

Part 5: Functions and Commands……………………………………………………… 18

..

Mathematical Functions……………………………………………………

..............

18

Abs ………………………………………………………………

...............

18

Int……………………………………………………………………….…. 18

Fix …………………………………………………………………………. 18

Rnd ………………………………………………………………………

18

Round……………………………………………………………………… 18

Long………………………………………………………………………

..

18

Exp ………………………………………………………………

...............

18

Writing Visual Basic code…………………………………………………………

18

Exercise 3…………………………………………………………………

..

19

Exercise 4………………………………………………………….………. 19

String Function……………………………………………………………………… 19

Mid ………………………………………………………………………

..

19

Trim………………………………………………………………………. 19

Instr………………………………………………………………………

..

20

UCase……………………………………………………………………… 20

LCase……………………………………………………………………… 20

Chr………………………………………………………………………… 20

Asc………………………………………………………………………… 20

Val ………………………………………………………………………… 20

Str ………………………………………………………………………… 20 ..

Len………………………………………………………………………….21

Exercise 5………………………………………………………………… 21

..

MsgBox ( ) ………………………………………………………………… ……….21

..

2

InputBox( ) ………………………………………………….……………………

.22

Command Dialogs…………………………………………………………………

...

22

ColorDialog …………………………………………………………….…. 22

FontDialog ……………………………………………

………………….

23

OpenFileDialog ………………………………………

………………….

23

SaveFileDialog ……………………………………………………………. 23

FolderBrowserDialog…………………………………

..

…………………

..

24

Part 6: Compiling, Running and Saving your project…………………………………. 25

Debug | Start Debugging …………………………………………………………… 25

File | Save All ………………………………………………………………………. 25

Open Windows Explorer…………………………………………………………… 25

Double-click executable file ………………………………………………………

..

25

Navigate back up to Project folder ………………………………………………… 26

Part 7: Errors and Debugging…………………………………………………………

..

27

Insert Breakpoint ………………………………. ………………………………

....

27

Debug | Step Over …………………………………………………………………. 28

Right-click ColorDialog1 | Add Watch ………………………………………

..

…… 28

Part 8: Project Files, Properties and Customization…………………………………… 29

Right-click UTM Sample1 | Select Add | New Item ………………………………. 29

Select Windows Form | Click Add ………………………………………………… 29

Click Play | Click Show Form2 | Close Windows …………………………………. 29

Tools | Options ……………………………………………………………………

..

30

Part 9: Web Browser……………………………………………………………………

..

31

Part 10: Data……………………………………………………………………………

...

32

Part 11: Menu……………………………………………………………………………

...

36

Part 12: PictureBox……………………………………………………………………

...

38

Part 13: Shell and EXE file………………………………………………………………… ...39

Introduction to Visual Basic 2008

Part 1: Setup =============

First, let's get started by downloading and installing the software, which you can do from the Visual

Studio website at http://www.microsoft.com/express/. You should check whether your computer meets

the requirements before installing. You can find this under the Support section of the website.

Click on the "Download" button to get to the Downloads page and then click on Visual Basic to begin

the download process. If you have installed a beta version of Visual Studio 2008 , then it is important to

uninstall this before continuing. If you would like to create an installation CD or if you need to perform

an installation disconnected from the internet, then you can download an IMG file that contains the

complete setup in the Offline Download section.

Run Setup

When you start the install process, this first screen asks if you want to give feedback to Microsoft on your

setup experience.

<Next>

Then you will be asked to accept the license agreement.

<Next>

The next screen presents an additional installation option. Note that if you‟ve already installed another

product and selected this option, then this screen may not appear.

The MSDN Library is a useful additional download that installs product documentation and help files

locally onto your computer, so you can access support information while disconnected from the internet.

<Next>

This screen shows us

what‟s

about

to be installed

(this list

components):

 

.NET Framework 3.5

 

VB

may vary based on existing installed

4

MSDN Library

SQL CE

SQL CE Design Tools

SQL Server Compact Edition is great complementary, free product that is the default database

automatically installed with Visual Basic

and is good to have if you plan on creating any data-driven

applications such as a collection tracking program or a reporting utility.

Notice that this is a change from Visual Basic 2005 which uses SQL Server as the default database

engine. In comparison, SQL Server Compact Edition is a lighter weight version and a bit easier to use.

However, if you do want to use the SQL Server Edition, it is also provided as a free download on the

website, and also works well with Visual Basic 2008.

<Next>

Please be patient during the installation process on some older computers the installation may take up to

an hour. You will also be prompted to reboot your computer so make sure you have saved any open

documents.

On this last screen you can check for any updates. When you get a chance I would highly recommend

that you register the product. This quick step gives you access to some free resources such as e-books to

help you get started working with Visual Basic , some free images from Corbis to use on your

applications, and lots of other cool components and discounts. It also allows you to enjoy uninterrupted

use of the Visual Basic development environment because otherwise, the software will expire after 30

days.

Note: If you have already had CD of Visual Studio 2008 or 2010, you can install as same way.

Note: if you have already installed the Visual Studio 2008 or 2010 in your computer and you have used

Visual C++, you can change languages as follows:

5

Part 2: Creating a Project ================================== Now that the installation is complete, you can run the

Part 2: Creating a Project ==================================

Now that the installation is complete, you can run the VB (Microsoft Visual Studio 2008) from the Start

menu, under "All Programs". The first time you run it, it may take a few moments to load.

6

Run Visual Basic 2008 The first thing you‟re presen ted with is something called the Start

Run Visual Basic 2008

The first thing you‟re presented with is something called the Start Page. This has some useful links:

You can open projects you've worked on recently

See samples and tutorials in the Getting Started section

And view the latest news headlines for recreational developers

Let's dive right in and create a new project. From the File menu, select New Project.

File | New Project

This window that appears offers several different project templates that can be used as starting points for

your

project,

type of application

Run Visual Basic 2008 The first thing you‟re presen ted with is something called the Start

7

depending on what

you want to create.

•The "Windows Forms Application" template lets you easily design familiar windows-style

applications.

•The "Class Library" template allows you to create a block of code that can be reused by several

different applications.

•The "Console Application" template creates a program that uses a simple text interface which runs

in the command window (or at a DOS prompt).

•Something that‟s new in Visual Basic 2008 is the “WPF Application” and “WPF Browser

Application” templates.

WPF stands for Windows Presentation Foundation and is a new technology that allows you to

create applications with a rich graphical user interface. A great example of a WPF application is

the British Library‟s “Turning the Pages” application that let‟s you virtually browse through some

rare books.

Demo http://ttpdownload.bl.uk/browserapp.xbap

Unfortunately we don‟t have time to cover WPF, but if you want to learn more, there are plenty of

tutorials and resources on the web to help you.

Part 3: The Windows Form Designer ============================================

Let's go ahead and build a Windows Forms application. We can name the new project anything that we'd

like. This becomes the name of the folder in which the application is built, and also the name of the

executable file that‟s created for our program. We will call this project "UTM Sample1 ".

8

Visual Basic gives us a head-start on our project by providing us with a blank window

Visual Basic gives us a head-start on our project by providing us with a blank window or form that is

already started for us. A form is a container upon which you can place controls to define the interface of

your application. We‟ll talk more about controls a bit later on. There are some familiar windows

components already here at the top of our form:

An icon that you can customize in the top left corner

A title for the form. The first form is called “Form1” by default.

And the minimize, maximize & close buttons in the upper right hand corner

Notice that when we click on our form, these white squares appear at the edges of our form. This allows

us to resize the form.

You can see that our Form opened in a separate tab called Form1.vb [Design] overlaying the Start Page

that we were looking at before. This is called the Designer view of our program.

Solution Explorer On the left side of the Designer is a window called the Solution Explorer.
Solution Explorer
On the left side of the Designer is a window called the Solution Explorer. In the same way that you can
manage and navigate files on your computer system with the Windows Explorer, you can use the Solution
Explorer to manage and navigate the files in your solution. Right now our UTM Sample1 project
contains 2 files – My Project (which contains the properties for our project), and Form1.vb.

9

Just below the Solution Explorer panel is the Properties Window. This window shows all the properties

or settings associated with the selected object. For example, if we click on Form1, the Properties window

updates to be focused on that object.

Note: If your properties panel or others is hidden, you can show them by using the following icons.

Just below the Solution Explorer panel is the Properties Window. This window shows all the properties

It‟s easy to use the Properties window to modify the settings of an object we can just change the value

in the right column next to the name of the property. For example, we can change the appearance of this

form by setting its properties. Let‟s go ahead and change the title on our form from Form1 to My

Window.

Text = “FSKSM

Notice that this is now reflected in the title bar of our Form. And let‟s set another property that we‟ll use

later called Back Color. By picking a certain color from this palette the BackColor of form will be paint

by the color.

BackColor = Maroon

Just below the Solution Explorer panel is the Properties Window. This window shows all the properties

On the right side of the Designer you‟ll see a tab that says Toolbox. If you don‟t see this tab, you can go

to the View menu and select Toolbox. When you hove the mouse over this tab, the window will pop out

and then pop back in when you move the mouse away. Let‟s go ahead and pin this window in place using

this pushpin icon on the top right corner. The Toolbox contains a list of all types of different controls you

can use in your project. You can think of controls as common building blocks that provide interactive

10

functionality on a form, such as checkboxes, calendars, and grids of data. Some controls are containers

for other controls, such as our blank Form1.

To place controls on your form, simply drag and drop them from the Toolbox onto the Form in the

Designer.

Drag textbox, button, label, radiobutton onto form & move them around

functionality on a form, such as checkboxes, calendars, and grids of data. Some controls are containers

The pink and blue snap lines help you to place controls with a consistent spacing and alignment, which

helps with the layout and design of your form.

Notice that the controls are grouped into categories depending on what they‟re used for. You can expand

or collapse these groups by clicking on the plus or minus signs.

Expand/Collapse groups & Scroll slowly (keep mouse off controls)

For example, there are different categories for controls dealing with Menus & Toolbars, Data, and

Printing. If you have your mouse over a control, you will be able to get a description of what that control

does.

Hove mouse over RichTextBox

To remove controls from your form, you can right-click on them and select Delete, or you can select

multiple controls at once and press the Delete key on your keyboard.

11

Variables:

Part 4: Basic Concepts =============

Like others programming languages VB.Net has some variables. The most important of them are as

follows:

12

There are two kinds of variables local and global. Local variables can be used just in

There are two kinds of variables local and global. Local variables can be used just in the local subroutine

that has already been defined. Global variable can be used in all subroutine that they must be defined in

the first of class.

To define a variable following template can be used.

DIM <variable name> as <variable type>

Example

Dim a as integer, b as string

Dim c as date

Operators:

There are two kinds of variables local and global. Local variables can be used just in

If:

13

If condition Then

VB expression

 

End If

OR

If condition Then

VB expression

 

Else

VB expression

 

End If

Using jus If

Then

statement is not very useful in programming and it does not provide choices for the

users. In order to provide a choice, we can use the If

....

Then

Else

Statement. This control structure will

ask the computer to perform a certain action specified by the VB expression if the condition is true. And

when the condition is false ,an alternative action will be executed.

The Select Case

...

End

Select Structure:

The format of the Select Case control structure is show below:

Select Case test expression

Case expression list 1

Block of one or more VB statements

Case expression list 2

Block of one or more VB Statements

Case expression list 3

Block of one or more VB statements

Case expression list 4

.

.

.

Case Else

Block of one or more VB Statements

End Select

For

....

Next

Loop

For counter=startNumber to endNumber (Step increment)

One or more VB statements

Next

Do Loop

14

The formats are :

  • a) Do While condition

Block of one or more VB statements

Loop

  • b) Do

Block of one or more VB statements

Loop While condition

  • c) Do Until condition

Block of one or more VB statements

Loop

  • d) Do

Block of one or more VB statements

Loop Until condition

While ...

End

While Loop

The structure of a While….End While is very similar to the Do Loop. it takes the following format:

While condition

Statements

End While

The above loop means that while the condition is not met, the loop will go on. The loop will end when the

condition is met.

Properties and events:

Properties of object means characterizes of that object such as back color, foreColor, size and

appearance. Events are some activates of object such as click, double click, drag and press a key or so on.

Common properties of objects:

Name: object‟s name that it must be unique

15

Text: content of objects

BackColor: Back ground color of object

ForeColor: font color of object

TextAlign: Alignment(right , center, left)

Enabled: If it is True the object is enabled. If it is False the object cannot work.

Visible: If it is True the object is visible. If it is False the object cannot be seen.

TabIndex: It shows order of object that appear in the form

TabStop: If it is false by pressing Tab key the object cannot have focus

Size: Size of object

Cursor: Type of pointer when the mouse is moving over the object.

Location: location of object

Objects:

Button: is a 3D button with following properties:

Image: Image for button‟s background

Text: caption of button

Visible: if True it means button is visible else invisible.

Locked: if it is true it means button cannot resize

Cursor: to show pointer cursor over the button

Label: is a flat caption with following properties:

BordeStyler: style of border

Text: caption

TextBox: is a 3D box to show and get data with following properties:

Text: contain as a text

Maxlenght: max size on term of length

Multiline: if it is True it means it can have multi line

16

PasswordChar: a character for show such as password. You just can see the character not real

data.

ScrollBar: To have scroll

Timer: is an invisible object to run a command in arbitrary time with arbitrary frequency with following

properties:

Enabled: True for enable Timer and False for disable the timer

Interval: The time, in milliseconds, between Elapsed events. The value must be greater than zero, and

less than or equal to 32768. The default is 100 milliseconds.

This object has only one event called Tick

Private Sub Timer1_Tick() End Sub

ListBox: is list box like array with following properties:

Items: for collection data

SelectedIndex: index of selected item that started from 0

ItemCount: Number of all Items

To add an item add method of items properties is provided.

ListBox1.Items.Add(TextBox1.Text)

ComboBox: is list box like array with following properties:

Items: for collection data

To add an item add method of items properties is provided.

ComboBox1.Items.Add(TextBox1.Text)

Exercise 1: Try to prepare a form such as windows calculator

17

Exercise 2 : Try to prepare a form such as following window 18

Exercise 2: Try to prepare a form such as following window

Exercise 2 : Try to prepare a form such as following window 18

18

Part 5: Functions and Commands

Mathematical Functions:

=============

Math. Abs (number): The Abs return the absolute value of a given number.

Int(number): The Int is a function that converts a number into an integer by truncating its decimal part

and the resulting integer is the largest integer that is smaller than he number. For example

Int(2.4)=2, Int(6.9)=6 , Int(-5.7)=-6, Int(-99.8)=-100

Fix(number): The Fix function truncate the decimal part of a positive number and returns the largest

integer smaller than the number. However, when the number is negative, it will return smallest integer

larger than the number.

Fix(9.2)=9 but Fix(-9.4)=-9

Rnd: The Rnd is very useful when we deal with the concept of chance and probability. The Rnd function

returns a random value between 0 and 1. Random numbers in their original form are not very useful in

programming until we convert them to integers. For example, if we need to obtain a random output of 6

integers ranging from 1 to 6, which makes the program behave like a virtual dice, we need to convert the

random numbers to integers using the formula Int(Rnd*6)+1.

Round(number): The Round function is the function that rounds up a number to a certain number of

decimal places. The Format is Round (n, m) which means to round a number n to m decimal places.

Math.Round (7.2567, 2) =7.26

Long(number): The Log function is the function that returns the natural logarithm of a number.

Log(10)=2.302585

Math.Exp(number): The Exp of a number x is the exponential value of x, i.e. ex .

Exp(1)=e=2.71828182

Writing Visual Basic code

Each Windows form is defined both by its design, which we have seen so far, and also by its underlying

code. To see the code for your form, just select View | Code from the menu bar or alternately, right click

on the Form in the Solution Explorer and select View Code.

Right-click on Form | Select View Code

Notice that the Code editor window opens up in a new tab. We can also drag these tabs down to create a

new tab group, and see both views at once.

19

Exercise 3: Create a project with output like below with all events.

Exercise 3 : Create a project with output like below with all events. Exercise 4 :

Exercise 4: Try to prepare a form such as following window with working.

String Function:

Exercise 3 : Create a project with output like below with all events. Exercise 4 :

Mid(phrase, position,n): The Mid function is used to retrieve a part of text form a given phrase.

where

phrase is the string from which a part of text is to be retrieved.

position is the starting position of the phrase from which the retrieving process begins.

n is the number of characters to retrieve.

Trim(“Phrase”):The Trim function trims the empty spaces on both side of the phrase.

20

Trim (“

Visual Basic

”) = Visual basic

Instr (n, original phase, embedded phrase): The InStr function looks for a phrase that is embedded

within the original phrase and returns the starting position of the embedded phrase.

Where n is the position where the Instr function will begin to look for the embedded phrase. For example

Instr(1, “Visual Basic”,” Basic”)=8

*The function returns a numeric value.

Microsoft.VisualBasic.UCase(Phrase):

Microsoft.VisualBasic.LCase(Phrase)

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

function converts all the characters of a string to small letters.

For example,

Microsoft.VisualBasic.Ucase(“Visual Basic”) =VISUAL BASIC

Microsoft.VisualBasic.Lcase(“Visual Basic”) =visual basic

Chr(charcode): The Chr function returns the string that corresponds to an ASCII code while the Asc

function converts an ASCII character or symbol to the corresponding ASCII code. ASCII stands for

“American Standard Code for Information Interchange”. Altogether there are 255 ASCII codes and as

many ASCII characters. Some of the characters may not be displayed as they may represent some actions

such as the pressing of a key or produce a beep sound. The format of the ASC function is

Asc(Character):

The following are some examples:

Chr(65)=A, Chr(122)=z, Chr(37)=% ,

Asc(“B”)=66, Asc(“&”)=38

Val(string): The Val function stops reading the string at the first character it cannot recognize as part of a

number. Symbols and characters that are often considered parts of numeric values, such as dollar signs

and commas, are not recognized. However, the function recognizes the radix prefixes &O (for octal) and

&H (for hexadecimal). Blanks, tabs, and linefeed characters are stripped from the argument.

The following call returns the value 1615198.

Val(" 1615 198th Street N.E.")

Str(number) : convert the number to string for example:

Str(1)+str(2)= “ 1 2”

21

Cstr(1)+Cstr(2)=”12”

Len():The length function returns an integer value which is the length of a phrase or a sentence, including

the empty spaces.

Exercise 5: Try to prepare Backspace for your Calculator

Cstr(1)+Cstr(2)=”12” Len(): The length function returns an integer value which is the length of a phrase

Len (Visual Basic) = 12 and Len (welcome to VB tutorial) = 22

MsgBox ( ) Function: The objective of MsgBox is to produce a pop-up message box and prompt the user

to click on a command button before he /she can continues. This format is as follows:

yourMsg=MsgBox(Prompt, Style Value, Title)

Cstr(1)+Cstr(2)=”12” Len(): The length function returns an integer value which is the length of a phrase

22

InputBox( ) Function An InputBox( ) function will display a message box where the user can

InputBox( ) Function

An InputBox( ) function will display a message box where the user can enter a value or a message in the

form of text. In VB2005, you can use the following format:

myMessage=InputBox(Prompt, Title, default_text, x-position, y-position)

myMessage is a variant data type but typically it is declared as string, which accept the message

input by the users. The arguments are explained as follows:

Prompt

- The message displayed normally as a question asked.

Title

- The title of the Input Box.

default-text - The default text that appears in the input field where users can use it as his intended

input or he may change to the message he wish to enter.

x-position and y-position - the position or the coordinates of the input box.

Command Dialogs

Now let’s look at the Dialog controls.

The nice thing about these is that instead of having to build out commonly-used forms, these dialog boxes

allow you to use common screens that are built into the Windows operating system itself. Among these

dialogs are the very common forms to open or save a file,

ColorDialog

Because these dialog controls only become visible when required, the designer

shows them at the bottom of the screen, off the form. But we can treat them the

same as any other control, they‟re just not visible on the Form.

The controls we‟ve placed get named according to the type of control, with a

number afterwards like Button1 or ColorDialog1. We see these names in the

Properties window when we click on the control. And we can also see a list of

all the controls in our project including our Form using this drop-down box at

the top of the Properties window.

To show this panel, showDialog is related method.

ColorDialog1.ShowDialog()

23

InputBox( ) Function An InputBox( ) function will display a message box where the user can

To use the selected color, color properties is related.

For example

Label1.ForeColor = ColorDialog1.Color

FontDialog

To show this panel, showDialog is related method.

FontDialog1.ShowDialog()

To use the selected font, Font properties is related.

For example

Label1.font = FontDialog1.font

OpenFileDialog

To show this panel, showDialog is related method.

OpenFileDialog1.ShowDialog()

To use the selected file, Filename properties is related.

For example

Label1.Text = OpenFileDialog1.FileName

SaveFileDialog

To show this panel, showDialog is related method.

SaveFileDialog1.ShowDialog()

To use the selected file, Filename properties is related.

For example

Label1.Text = SaveFileDialog1.FileName

FolderBrowserDialog

To show this panel, showDialog is related method.

FolderBrowserDialog1.ShowDialog()

To use the selected folder, selectedPath properties is related.

For example

Label1.Text = FolderBrowserDialog1.SelectedPath

Because these dialog controls only become visible when required, the designer shows them at the bottom

of the screen, off the form. But we can treat them the same as any other control, they‟re just not visible

on the Form.

The controls we‟ve placed get named according to the type of control, with a number afterwards – like

Button1 or ColorDialog1. We see these names in the Properties window when we click on the control.

And we can also see a list of all the controls in our project including our Form using this drop-down box

at the top of the Properties window.

25

Part 6: Compiling, Running and saving your project

======================

Compiling or Building your project is the process of converting all the code you‟ve written into an

executable file that can be run. This also has the effect of doing some checking to your code for mistakes.

Let‟s build our project and see if there are any errors. Select “Build Desktop Window” from the “Build”

menu, and we can then see the results at the bottom left of the screen.

So far so good. Now for the fun part! Let's see how our application performs by running it. We can use

the green "Play" button on the toolbar, or we can also select "Start Debugging" from the "Debug" menu.

If you hadn‟t yet compiled your code before doing this, it will automatically compile everything before

running, so you can skip the Build stage if you are confident you don‟t have any bugs.

Debug | Start Debugging

Here‟s our running program! Notice that while our program is running, you won‟t be able to edit it in

Visual Basic Express.

Now let‟s save our project by selecting “Save All” from the “File” menu.

File | Save All

By default, projects are stored in their own folder under “My Documents” | “Visual Studio 2008” |

“Projects”.

Let‟s look at this directory in Windows Explorer.

Open Windows Explorer

We see a couple files and a folder in this directory. The UTM Sample1 "Solution File" has a .SLN

extension and contains all references to your project. This is the file that you will double-click to open up

your project again in Visual Basic. You can ignore the file with the .SUO extension for now, it just

contains some user options that you set for your solution.

Let‟s look in the UTM Sample1 project folder. This contains all the files related to your project.

The “bin” folder is where Visual Studio puts together the actual executable file for us. "bin" is short for

"Binary". When we compiled or built our project Visual Studio created this folder. Notice that there are

2 versions the Release (or final) version, and the Debug version of our program. To run our program

we just double-click the “Desktop Window.exe” file in one of these folders.

Double-click executable file

26

You can share the programs you create with others by simply copying the files that are generated in this

folder to another computer that also has the .NET Framework installed.

Navigate back up to Project folder

The My Project folder contains files that pertain to your project‟s properties and settings.

The obj folder contains some intermediate project files that you can ignore for now.

The UTM Sample1 .vbproj and .vbproj.user files are your project files, and the Form1 files are all the

files associated with your Form.

27

Part 7: Errors and Debugging

================================

As you write code, there will be occasions that you make small mistakes. In the world of software

development, these are called “bugs”. Fortunately, Visual Basic can automatically find some kinds of

errors for you. These bugs will appear underlined in either blue or red squiggly lines in the Code Editor,

similar to misspellings in the Microsoft Word program.

Let‟s look at this in our code. Say we accidentally use the wrong property name, for example “MyColor”

instead of “Color”.

Me.BackColor=ColorDialog1.MyColor

Notice that Visual Basic

immediately underlines this as a mistake. We can see the specific error

message by moving our mouse over the underlined section.

Or if we attempt to compile the application from the Build menu, notice that the error is shown down

below in the Error List.

Me.BackColor=ColorDialog1.Color

Sometimes a program will run fine, but not produce the result you expected. Debug mode is also useful

in this case to diagnose these logic errors. You can manually set a place in the code where the execution

will halt, called a breakpoint. This is done by clicking to the left of the line of code of interest.

Insert Breakpoint at ColorDialog1.ShowDialog()

Then when you run the application in Debug mode, it halts on that line so you can examine all the

variables, and find the area of your code that is not working as expected. The program is still in memory,

and just frozen at this point.

28

Click Play In this break mode you can step line-by-line through the application by using either

Click Play

In this break mode you can step line-by-line through the application by using either the Step Into or Step

Over feature. Step Into offers a more thorough analysis of the code because it digs into any methods that

are called from here, whereas Step Over will skip these called methods.

Debug | Step Over

A great way to examine the contents of variables is by using Visualizers. This handy feature lets you drill

down into various properties and values held in a variable or object. If we hover our mouse over the

highlighted area of code, we can see all the information held inside a Color object.

There are several other useful debugging windows:

•Locals window – shows all the variables local to the currently executing method

•Watch window – you can add any variable to the Watch window to monitor its value

Right-click ColorDialog1 | Add Watch

Immediate window this is like a scratch pad where you can perform quick calculations, print out

values and execute commands

Type “? 1+2”

To stop the debugging so that we can edit again, we can select “Stop Debugging” from the Debug menu.

Select Debug | Stop Debugging

Remove Breakpoint

29

Part 8: Project Files, Properties and Customization

=======================================================

To add more files to your project, from the Project menu, you can select Add New Item, or you can right-

click your UTM Sample1 project in the Solution Explorer and select Add New Item.

Right-click UTM Sample1 | Select Add | New Item

This will bring up the Add New Item dialog box. There are a bunch of different templates here you can

choose from with descriptions at the bottom explaining each one. Let‟s add another Windows Form.

Select Windows Form | Click Add

We see that Form2 has been added to our project. Let‟s connect Form1 and Form2 together. First, let‟s

add another button to Form1 and set the button Text to tell the user what will happen when they click the

button.

Drag button onto Form1 | Text = “Show Form2”

Now we need to actually hook them up in code. Double-click the button to go to the code view and

insert:

Form2.Show()

Now if we run our program, and click on the Show Form2 button, our second form gets displayed.

Click Play | Click Show Form2 | Close Windows

Alright. Now let‟s take a look at the properties of our UTM Sample1 project. We can do this by double-

clicking on the My Project folder in the Solution Explorer.

Double-click My Project

We can see that the properties of our project are divided into categories which are listed on these tabs to

the left. Some of the things you can do here are to define custom user or application settings, or set up

your application to be published on the Internet.

30

Let‟s set up a new icon for our application. We can do this in the Application section. Icons are simple

16 by 16 or 32 by 32 bitmaps with a .ico file extension, and some sample icons are available to you for

free as part of your

registration benefits. Let‟s browse to a sample icon.

Icon Drop-down Browse | Select MSN.ico | Open

Now when we look at our executable file, we see that it uses the new icon.

Open Windows explorer to bin\Debug

You can customize your development environment by setting configuration options found in the Tools |

Options window.

Tools | Options

Here you can specify things like window layout, font styles, keyboard shortcuts and more. For example, I

can add line numbers to my Code Editor view here under Text Editor Basic | Editor by checking the Line

Numbers box.

Text Editor | Basic | Editor | Line numbers

And you can also set things like fonts and colors.

Environment | Fonts and Colors | Set Item foreground/background colors

To see all the configuration options available to you, click the Show all settings checkbox.

How to run exe file

Shell(“Path file\File name”)

How to create Menu

MenuStrip

31

Part 9: Web Browser

==========================

Basically everyone have to navigate the Internet using commercially produced web browsers such the

Internet Explorer produced by Microsoft or those open source browsers designed by the experts such

FireFox , Opera and the latest Chrome created by Google. However, isn't it cool that if we can create our

very own web browser that we can customize to our own taste ? Yes, you can do that in VB2008, and

pretty easy too. In this chapter, I will show you how to create a simple web browser and get it running in a

few minutes.

First of all, start a new project in VB2008 and name it with any name you like. Here I am just using the

name webbrowser.

You need to add an engine so that your web browser can connect to the Internet, and this very engine is

the WebBrowser control, located on the Toolbox on the left side, set the size property to 600,400. Next,

drag a text box and place it at the top of the WebBrowser control, this will be the address bar where the

user can enter the URL. Lastly, place a command button beside the text box and label it as Go. The design

interface is shown below:

Part 9: Web Browser ========================== Basically everyone have to navigate the Internet using commercially produced web

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

32

WebBrowser1.Navigate(TextBox1.Text)

End Sub

Part 10: Data

==========================

Many applications become very useful when they can store information. And one of the best ways to

store information is in a database. This way the data can be organized just the way you need.

In this demonstration, we will create a connection to an existing sample database from Microsoft called

Northwind using SQL Server Compact Edition.

We‟ll start by getting a connection to a database. Using the “Data Sources” window, which is a tab

under the Solution Explorer window – if you don‟t see this window, go to the “Data” menu and select

“Show Data Sources” – we see that there are no data sources yet established, so we‟ll select “Add New

Data Source”. This brings up the Data Source Configuration Wizard. We see that we can connect to

several different data sources, including a Web Service or an Object. In this case, we‟ll connect to a

database file on this local computer.

WebBrowser1.Navigate(TextBox1.Text) End Sub Part 10: Data ========================== Many applications become very useful when they can store
WebBrowser1.Navigate(TextBox1.Text) End Sub Part 10: Data ========================== Many applications become very useful when they can store

Data Sources | Add New Data Source | Database | Next

33

Once we pick the database source, we need to configure a data connection, so we‟ll click

Once we pick the database source, we need to configure a data connection, so we‟ll click New

Connection. We can see that the default database type is SQL Server Compact Edition. But you could

pick another database type such as Access or SQL Server .

Once we pick the database source, we need to configure a data connection, so we‟ll click

New Connection… | Change… | Cancel

Now let‟s Browse for our Northwind database file. You can select Test Connection to make sure that we

set this up properly.

34

Browse ... | Northwind.sdf | Open | Test Connection|OK You are prompted to copy this data

Browse ...

| Northwind.sdf | Open | Test Connection|OK

You are prompted to copy this data file into your project and give it a name so that you can deploy the

database with your project to other machines, and it can be packaged up along with the rest of your

project files.

Browse ... | Northwind.sdf | Open | Test Connection|OK You are prompted to copy this data

Now we can see all the tables in this Nothwind database. Let‟s select the Employees Table, and change

the DataSet name to something more descriptive, like “EmployeesDataSet”.

DataSet name = EmployeesDataSet | Finish

We can see our new Data connection shown in the Data Sources window. Let‟s configure our Form2 to

show this data in our Employees table. All you have to do is simply drag and drop the entire Employees

table from the Data Sources window onto the Form.

Drag table onto Form2 | resize DataGrid

35

This creates a DataGridView control, as well as this neat little strip of buttons at the top called a

BindingNavigator. There is also code written automatically for us to give these controls life. There‟s

nothing else we have to do in order to work with our data – it‟s almost too easy!

This creates a DataGridView control, as well as this neat little strip of buttons at the

Let’s run the application to see how it functions.

Click Play

When we click the Show Form2 button, we can see all the data in our Employees table, and navigate

through the list using the toolbar buttons. Notice that these buttons will also allow you to add new

employees and delete employees.

Another way to access data is through a technology called „LINQ‟. LINQ stands for “Language

Integrated Query” which allows you model data constructs and work with data directly in your code. For

example, you could write something like this to pull out Employee last names:

Dim q = From e In mydb.Employees Select e.LastName

If you‟re new to data storage concepts, that may not mean much, but basically it gives you easier

accessibility to your data, and more flexibility in working with your data directly in your program.

Unfortunately we don‟t have time to cover LINQ in more detail here, but if you‟re planning on creating

an application that makes use of databases or XML data files, I encourage you to explore this method of

data access. There are many resources and tutorials on the web that will help you understand and use

LINQ in your windows applications.

Part 11: Menu

To create menu in visual basic 2008 there are some ways but the simple way is using MenuStrip object.

By dragging the MenuStrip object into the form a simple empty menu will be appeared. By click on the

each part, you can create a head menu and sub menu. Finally, by double click on each sub menu you can

see the View code and write down any code you need.

36

37

37

Part 12: PictureBox

To show a picture on the form you can use the BAckgroundImage of form or you can use a PictureBox

object. PictureBox has some properties but the most ones are:

Image: You can use this property to load a picture on the form.

SizeMode: To determine photo should be in the center or stretch or

Note: To load an Image in the View Code you can use the following code:

PictureBox1.Load (" address\Filename")

Example:

PictureBox1.Load ("c:\test\MyPhoto.jpg")

38

Part 13: Shell and EXE file

Visual basic 2008 creates EXE file automatically. You can fine the EXE file in the folder that you have

saved you project. In default case it is in the current folder:

C:\Documents and Settings\My Documents\Visual Studio 2008\Projects\WindowsApplication1

\WindowsApplication1\bin\Debug

Shell(): To run an EXE file in your project you can use Shell() function.

Shell(("address\Filename")

For example: Following code can run the Windows calculator .

Shell(C:\WINDOWS\system32\calc.exe)

Hoshang Kolivand

Ph.D Student of Computer Science

Department of Computer Graphics

Sep 2011

39