You are on page 1of 31

Fundamentals of Programming in Visual Basic Part 1

Robert Burtch Surveying Engineering Department Ferris State University

VISUAL BASIC OBJECTS


VB programs display Windows style screen called a form
Contains boxes and buttons called controls Forms and controls called objects

VISUAL BASIC OBJECTS


To start click on Microsoft Visual Studio.NET option
Opens Visual Studio start page

VB.Net also known as application, solution or project


Each project saved as series of files and subfolders in it own folder

START PROJECT

Start project:
click on File|New|Project Alternatively, click New Project icon

START PROJECT
Opens New Project dialog
Select Visual Basic Projects as Project Type Windows Application as Template Select name default WindowsApplication with number Select Location recommend special folder

Click OK this will open the initial VB.NET screen

INITIAL VB SCREEN

INITIAL VB SCREEN
Menu bar
Displays commands used with VB File, Edit, Project, Format, Debug, etc. Like other windows programs, but some specific to VB

Toolbar
Collection of icons that carry out standard operations Little information rectangle that pops up called a tooltip

Main Area
Holds Windows Form Designer Large stippled Form Window, or Form, becomes Window on execution

Solution Explorer Window


Sometimes used to open programs stored on hard drive

Properties Window
Used to change how objects look and read

Toolbox
Controls that can be placed on Form

TEXT BOX CAPABILITIES


Double click text box icon
Opens rectangle with sizing handles in center of form
If handles are displayed object is said to be selected

Rectangle can be resized by moving mouse to one of the handles Rectangle can be moved by holding down the left mouse key anywhere within the object

CREATING TEXT BOX


Alternative approach
Click on text box icon Move mouse to any place in form Hold down left mouse button and drag a diagonal to create rectangle

Textbox Cursor

TEXT BOX
To access Properties window, click on Properties window icon in Toolbar or click on the Properties window or press F4

Alphabetic tab display

Categorized tab display

TEXT BOX
Click on Text option in Properties menu In right column, add desired text

Text changes in both the Settings box and text box

TEXT BOX
Highlight property ForeColor to change color of text (alternatively,press ShiftCtrl+F to go to first property beginning with F)

TEXT BOX
Highlight Font property with single click of mouse Click on ellipsis () to open Font dialog box

PROGRAM EXECUTION
To execute program, click on Start icon Example of executed form

Text displayed in single line to right hides text to left

TEXT BOX
In Properties window, turn on Multiline option Result is that words wrap Can make Text box read only:
Properties|Read Only Property|True

TEXT BOX
Can create multiple text boxes in the form
One with cursor is the active box and this is called the focus

COMMAND BUTTON
Double click on Button icon in Toolbox
Creates a Button on form

Button Cursor Can be manipulated, like the text box

COMMAND BUTTON
Click on Caption in Properties window and type in a new caption for the command button
Text added to button at same time added to Properties window

COMMAND BUTTON
Command button look at execution
Button appears to move in and out

Can underline parts of command button text by adding ampersand to text Here, P is called the access key pressing Alt+P activates program like clicking on command button

Will add code to button

LABELS
Double click on label icon Places label at center of form

Label Cursor

10

LABELS
Alignment can be changed by double clicking Alignment property in Properties window

Executing program does nothing to label


Just sits there User cannot change what a label displays

LISTBOX
Click ListBox icon Click and drag location of listbox ListBox displayed on Form

11

NAME PROPERTY
Every control has name property
Used in code to refer to control Name must start with letter
Max of 215 characters Can include numbers and underscore Cannot include punctuation or spaces

SUGGESTED NAMING CONVENTION


Hungarian notation: 3-letter prefix identifying the type of control

CONTROL Button Label List box Text box Form

PREFI EXAMPLE X btn btnComputeTotal lbl lst txt frm lblInstructions lstOutput txtAddress FrmProgram1

12

HELP WALKTHROUGH
Dynamic help
Displays list of topics appropriate for what you are working on To Invoke: Alt | H | H

Help Index
Alphabetized list of all help topics To Invoke: Alt | H | I

FONTS
Default Microsoft Sans Serif

13

FONTS
Courier New
Fixed-width font Useful to arrange columns

Wingdings
Assorted small pictures and symbols

AUTOHIDE
Pushpin vertical AutoHide disabled
Allows you to make more room for Main area of screen by minimizing tool windows

Pushpin horizontal AutoHide enabled

14

When opening/closing programs use Open Solution and Close solution from File Menu
Do not use Open and Close

USEFUL PROPERTIES
BackColor
Specified background color for form or control

Visible
When False, causes objects to disappear when program is run Can be made to reappear with code

Enabled
When False, restricts its use Appears grayed and cannot receive focus

15

VISUAL BASIC EVENTS


Event
Action by user such as clicking a control or pressing a key Programmer writes code to do something when event occurs

3 steps in creating a VB program


1. Create interface generate, position, size objects 2. Set properties configure appearance of objects 3. Write code that executes an event

VB.NET EVENTS
Properties of controls changed using following form controlName.property = setting
controlName = name of control Property = one of controls properties Setting = any valid setting for control property

Examples
txtBox.ForeColor=Color.Red
Changes characters in text box to red

txtBox.Text = Hello
Words Hello displayed in text box

btnButton.Visible=True
Makes button visible

16

EVENT PROCEDURE
Statements executed when even occurs written in block of code called event procedure First line of Event Procedure has form (sometimes called Procedure-Declaration Statement)
Private Sub objectName_event (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles objectName.event

Often simplified as
Private Sub ojbectName_event() Handles objectName.event statements End Sub

KEYWORDS
Words like Private, ByVal, As, Handles and End keywords or reserved words
VB.NET automatically capitalizes first letters of keywords and displays it in blue

17

EVENT PROCEDURE WALKTHROUGH


Create a Form with 2 text boxes and one button Change the properties of the controls

OBJECT Form1 txtFirst txtSecond btnRed

PROPERTY Text Text Text Text

SETTING Demonstratio n (blank) (blank) Red

EVENT PROCEDURE WALKTHROUGH

18

EVENT PROCEDURE WALKTHROUGH


Code window
Right click anywhere on Main area and select View Code from pop-up
Page tabs between Code window and Form Design window

Method Name Box Class Name Box

EVENT PROCEDURE WALKTHROUGH


Rectangular area corresponds to collapsed block of code
Hover cursor to see information about it

19

To enter code, double click on control


Program will automatically take you to Code window and will enter the first and last line for the event procedure
First line: Private Sub Last line: End Sub

EVENT PROCEDURE WALKTHROUGH

Will write code between these two lines

Alternatively, click on Class Name box and select control

EVENT PROCEDURE WALKTHROUGH


Class Name Box

Then select desired option in Method Name Box

20

When typing code, feature called Member Listing will display properties after typing a period after the control One proper method highlighted, press Tab key to select

EVENT PROCEDURE WALKTHROUGH

Line of code where typing is occurring

Demonstration code

EVENT PROCEDURE WALKTHROUGH


Run program Type Hello in first box Typed characters appear in Blue

21

EVENT PROCEDURE WALKTHROUGH


Press Tab key to change focus to second text box changes text to black

Click on button to change text to red

EVENT PROCEDURE WALKTHROUGH


Click back to first text box and add text
Changes color back to blue

22

EVENT PROCEDURE WALKTHROUGH


Adding a Quit button

VB.NET EVENTS
Name of event procedure can be changed since the Handles objectName.event identifies the event triggering the procedure

23

NUMBERS
Numbers called numeric literals One method of displaying number is with list box lstBox.Items.Add(n)
Number n is displayed Add is called a method carries out operation and displays result

Another important method is Clear lstBox.Items.Clear()


Erases all items displayed in lstBox

NUMBERS
Example showing different arithmetic operations to numbers 3 and 2

24

NUMBERS
101 = 10 102 = 100 103 = 1,000 10 = 10000 n zeros
1.4*10^9 3*10^-7 1.4E+9 3E-7
n

10-1 = 1/10 = 0.1 10-2 = 0.01 10-3 = 0.001

M 10-n = 0.00001 n digits


1.4E9 0.0000003 140000000

Following forms of number all equivalent

NUMBERS
Example use of scientific notation

25

WITH BLOCK
Reduces repetitive typing and makes program less cluttered

Expression starting with period evaluated as if lstResults.Items preceded it

NUMBERS
Variables quantities identified by name Can assign a number to a variable in the general form: var = n Example: if a car travels at 50 miles per hour, how far will it travel in 14 hours? Also how many hours are required to travel 410 miles? Solution uses formula:

distance = speed * time elapsed

26

NUMBERS
Example solution
Variables: speed, timeElapsed, distance

DECLARING A VARIABLE
Dim statement declares the type of variable Dim varName As Double
Declares the variable varName as a double precision real number

Can declare a variable and assign an initial value at same time Dim varName As Double = 50
Declares varName as double precision and assigns it a value of 50

Can display the current value of a variable and display it in list box using: lstBox.Items.Add(varName)

27

NUMBERS
Example using default value of variable and value of an expression

BUILT-IN MATH FUNCTIONS


VB has some built in math functions that take one or more input values and returns a single output Example:
Math.Sqrt(9) is 3. Int(2.7) is 2. Math.Round(2.7) is 3

Math.Sqrt(0) is 0.

Int(3) is 3.

Math.Round(2.317,2) is 2.32 Math.Round(2.317,1) is 2.3

Math.Sqrt(2) is 1.414214

Int(-2.7) is 3

28

BUILT-IN MATH FUNCTIONS


Example of built-in functions in Member listing

BUILT-IN MATH FUNCTIONS


When typing, instruction box is displayed describing the variables needing input

29

NUMBERS
Example evaluates each function for n

NUMBERS
Example evaluates functions at an expression

30

NUMBERS
Integers are declared using the following form Dim varName As Integer A single Dim statement can be used to declare multiple variables Dim a, b As Double Dim a As Double, b As Integer Dim c As Double = 2, b As Integer = 5

TYPES OF ERRORS
Syntax errors
Due to misspellings, omissions, or incorrect punctuations Mostly spotted by editor

Runtime errors
Errors occurring while program is running Green triangle will appear at left side of line of code causing the error

Logical errors
Program does not perform in way it was intended

31

You might also like