You are on page 1of 118

Copyright 2014 Pearson Education, Inc.

Chapter 2
Creating Applications with Visual Basic

Copyright 2014 Pearson Education, Inc.

Topics
Topics
2.1 Building the Directions Application 2.2 Responding to Events 2.3 Modifying a Controls Text Property with Code 2.4 AutoSize, BorderSize, and TextAlign Properties 2.5 Displaying User Messages
Copyright 2014 Pearson Education, Inc. 2

Outline (cont.)
2.6 Clickable Images 2.7 Using Visual Studio Help Debugging Your Application

Copyright 2014 Pearson Education, Inc.

2.1

Focus on Problem Solving: Building the Directions Application


Copyright 2014 Pearson Education, Inc. 4

Request for Directions Application


Request
The manager of the Highlander Hotel has asked you to build an application that displays a map to the hotel

Copyright 2014 Pearson Education, Inc.

Steps to Create an Application


Steps
Define what the program is to do Visualize application and design user interface List controls needed Define values of each control's relevant properties Create form and other controls using Visual Studio .NET
Copyright 2014 Pearson Education, Inc. 6

Steps to Create an Application (cont.)


Write code Save application Compile application Run application Test application Put into production

Copyright 2014 Pearson Education, Inc.

Application Specification
Application
Displays a map and written directions to the Highlander Hotel
Design a form with
Labels PictureBox Buttons

Write event procedures

Copyright 2014 Pearson Education, Inc.

1. Define What the Application is to Do


Purpose:
Input: Process: Output:

Display a map of the Highlander Hotel None Display a form Display on the form a graphic image showing a map

Copyright 2014 Pearson Education, Inc.

2. Visualize and Design User Interface


Sketch of form to be shown
Label

PictureBox

Form

Copyright 2014 Pearson Education, Inc.

10

3. Determine the Controls Needed

Copyright 2014 Pearson Education, Inc.

11

4. Define Values of Each Controls Relevant Properties

Copyright 2014 Pearson Education, Inc.

12

5. Use VS to Create Application


Steps
Launch Visual Studio Create a new project Create a new VB Windows Forms Application Design form Save, compile, run, and test application

Copyright 2014 Pearson Education, Inc.

13

Launching Visual Studio

Copyright 2014 Pearson Education, Inc.

14

Visual Studio - Start Page

Copyright 2014 Pearson Education, Inc.

15

Create a New Project

New Project

Copyright 2014 Pearson Education, Inc.

16

New Project: VB Windows Forms App

Copyright 2014 Pearson Education, Inc.

17

Design Window

Controls
Solution Explorer Design Window

Object Box

Toolbox
Copyright 2014 Pearson Education, Inc.

Properties Window

Values Names

18

Use VS to Create Application


Establish the Form
Set Text property Add Label control
Position and resize it on form Set Text, TextAlign, AutoSize, and Font properties

Add PictureBox control


Position and resize it on form Set Image property to HotelMap.jpg
Select Resource/Local Resource/Import
Copyright 2014 Pearson Education, Inc. 19

Use VS to Create Application (cont.)


Run the application Close and save the application

Copyright 2014 Pearson Education, Inc.

20

Directions Application GUI

Save All

Sizing Handles

Copyright 2014 Pearson Education, Inc.

21

Building the Application


Before running the application
Save all files in the application Build the solution to check for syntax errors, use menu to
Build/Build Solution - or - Build/Rebuild Solution

Copyright 2014 Pearson Education, Inc.

22

Build/Build Solution

Build Solution

Copyright 2014 Pearson Education, Inc.

23

Build Results

Build Results
Copyright 2014 Pearson Education, Inc. 24

Running the Application


To run the application, use
Debug/Start Debugging menu - or - Start Dropdown List - or - Start Icon

Copyright 2014 Pearson Education, Inc.

25

Debug/Start

Start Debugging

Copyright 2014 Pearson Education, Inc.

26

Start Icon

Start Debugging

Copyright 2014 Pearson Education, Inc.

27

Application Running

Copyright 2014 Pearson Education, Inc.

28

The Directions Application Running

Copyright 2014 Pearson Education, Inc.

29

Visual Basic Modes


Visual Basic modes
Design mode
Mode in which you create the application Also known as design time

Run mode
Executes application in the Visual Studio environment Also known as runtime

Copyright 2014 Pearson Education, Inc.

30

Visual Basic Modes (cont.)


Break mode
Momentarily suspends execution of a running application For testing and debugging purposes

Copyright 2014 Pearson Education, Inc.

31

Solution and Project Organization


Solution
Container that holds Visual Studio projects Each time you create a new project, you will also create a new solution to hold it

Copyright 2014 Pearson Education, Inc.

32

Solution and Project Organization


Solution folder
Created for each new project Contains
Project folder Solution file (.sln)
Double-clicking the solution file will load the project in Visual Studio

Copyright 2014 Pearson Education, Inc.

33

Solution and Project Organization


Project folder
Contains
Files and folders generated by Visual Studio Project file (.vbproj)
Double-clicking the project file will also load the project in Visual Studio

Copyright 2014 Pearson Education, Inc.

34

Project Organization on Disk


User creates new project in Visual Studio
Solution and folder are created at same time with same name as project
Solution file (.sln)

The project belongs to the solution


Project file (.vbproj)

Solution may contain multiple projects

Copyright 2014 Pearson Education, Inc.

35

Project Organization
Solution

Project

Copyright 2014 Pearson Education, Inc.

36

Default Locations

Tool/Options/Projects and Solutions/General


Copyright 2014 Pearson Education, Inc.

Slide 2- 37

37

To Open an Existing Project


With Visual Studio running
Use Start Page to open the project
If start page is not visible, click VIEW/Start Page Click Open Project link or Select name of project in Recent Projects list

Copyright 2014 Pearson Education, Inc.

38

Open a Project Using Start Page

Open

Copyright 2014 Pearson Education, Inc.

39

To Open an Existing Project


With Visual Studio running
Click FILE/Open Project
Locate either solution (.sln) or project (.vbproj) file

Click FILE/Recent Projects and Solutions


Select solution file (.sln) or project file (.vbproj) from list

Copyright 2014 Pearson Education, Inc.

40

Open a Project Using File Open

Open

Copyright 2014 Pearson Education, Inc.

41

Re-open Project

Copyright 2014 Pearson Education, Inc.

42

Properties Window
Use Properties Window to
Select controls on Form
Object Box (dropdown list)

View/modify property values of selected object View/modify event handlers for selected object

Copyright 2014 Pearson Education, Inc.

43

Properties Window (cont.)


Views of properties
Alphabetic (across all properties)
(Name) appears at top of list

Categorized (groups properties by logical use)

Copyright 2014 Pearson Education, Inc.

44

Properties Window (Alphabetical)

Object Box By Category Alphbetical

Copyright 2014 Pearson Education, Inc.

45

Properties Window (Categorical)

Object Box By Category Alphbetical

Copyright 2014 Pearson Education, Inc.

46

Properties Window (Events)

Copyright 2014 Pearson Education, Inc.

47

Object Box
Object Box
Shows name of selected control Clicking drop-down list displays names of all objects in form Clicking name of object selects it

Copyright 2014 Pearson Education, Inc.

48

2.2

Focus on Problem Solving: Responding to Events


Copyright 2014 Pearson Education, Inc. 49

Modifying the Directions Application


Add the following to the application:
Label containing the written directions Button to display the directions Button to exit the application

Copyright 2014 Pearson Education, Inc.

50

Controls to Add
Control Type Label Control Name lblDirections Description Displays written directions to the hotel

Button

btnDisplayDirections

When clicked, causes lblDisplayDirections text to appear on the form

Button

btnExit

Stops the application when clicked

Copyright 2014 Pearson Education, Inc.

51

Control Properties
Label
Name: lblDirections Text: Traveling on I-89,etc Visible: False

Button
Name: btnDisplayDirections Text: Display Directions

Button
Name: btnExit Text: Exit
Copyright 2014 Pearson Education, Inc. 52

Application Running

Copyright 2014 Pearson Education, Inc.

Slide 2- 53

53

Application Running with Directions

Copyright 2014 Pearson Education, Inc.

Slide 2- 54

54

Adding an Event Handler


To add an event handler
Double click on a control to get the default event handler Opens the code window Add code

Copyright 2014 Pearson Education, Inc.

55

Adding an Event Handler (cont.)

Copyright 2014 Pearson Education, Inc.

56

Click Event Handler for btnDisplayDirections

Copyright 2014 Pearson Education, Inc.

57

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' load directions (a very long string) lblDirections.Text = "From the airport: " & ControlChars.CrLf & "1: Start out going EAST on AIRPORT RD toward DUVAL RD/CR-110. - 0.1 miles" & ControlChars.CrLf & "2: Turn LEFT onto DUVAL RD. - <0.1 miles " & ControlChars.CrLf & "3: Turn RIGHT onto DUVAL RD/FL102 E. - 0.1 miles " & ControlChars.CrLf & "4: Merge onto I-95 S toward JACKSONVILLE. 1.6 miles " & ControlChars.CrLf & "5: Take the SR-9A S exit- EXIT 362A- toward BLOUNT ISLAND. - 0.2 miles " & ControlChars.CrLf & "6: Merge onto I-295 N. - <0.1 miles " & ControlChars.CrLf & "7: Stay STRAIGHT to go onto FL-9A S. - 13.8 miles " & ControlChars.CrLf & "8: Turn SLIGHT RIGHT onto ST JOHNS BLUFF RD S. - 1.9 miles " & ControlChars.CrLf & "9: Turn LEFT onto BEACH BLVD/US-90 E/FL-212 E. - 1.2 miles " & ControlChars.CrLf & "10: Turn LEFT onto HUFFMAN BLVD. - <0.1 miles " & ControlChars.CrLf & "11: End at 11901 Beach Blvd Jacksonville, FL 32246-6624, US" ' hide directions lblDirections.Visible = False

Application Code

' show Display Directions button btnDisplayDirections.Visible = True


' hide Hide Directions button btnHideDirections.Visible = False
Copyright 2014 Pearson Education, Inc. End Sub 58

Private Sub btnDisplayDirections_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayDirections.Click lblDirections.Visible = True

Application Code (cont.)

btnHideDirections.Visible = True btnDisplayDirections.Visible = False

End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click ' end application Close() End Sub Private Sub btnHideDirections_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHideDirections.Click lblDirections.Visible = False btnHideDirections.Visible = False btnDisplayDirections.Visible = True End Sub
Copyright 2014 Pearson Education, Inc. 59

Source Code (VB)

Copyright 2014 Pearson Education, Inc.

60

Syntax for Assignment Statement


To assign a value to a property
ControlName.PropertyName = value

where
ControlName.PropertyName receives value Equal sign (=) is assignment operator value is being assigned

Copyright 2014 Pearson Education, Inc.

61

Syntax for Assignment (cont.)


Example
lblDirections.Visible = True Assigns value True to Visible property of lblDirections control Causes text of lblDirections control to become visible to user

Copyright 2014 Pearson Education, Inc.

62

Switch Between Windows


Use tabs to switch to
Designer window, click Form1.vb [Design] tab Code window, click Form1.vb tab

Copyright 2014 Pearson Education, Inc.

63

Switch Between Windows (cont.)


Use Solution Explorer to switch to
Open Code window

Copyright 2014 Pearson Education, Inc.

64

Switch Between Windows (cont.)


Use View menu
Then select either Code or Designer window

Use keyboard
Shift + F7 to open Designer window Ctrl + Alt + 0 to open Code window

Copyright 2014 Pearson Education, Inc.

65

Click Event Handler for btnExit

Copyright 2014 Pearson Education, Inc.

66

Comments
Comment (or remark)
Is short notes that you can write in the applications code to explain what code does Starts with an apostrophe (') and anything appearing after the apostrophe, to the end of the line, is ignored by the compiler

Copyright 2014 Pearson Education, Inc.

67

Comments (cont.)
May be inserted at the end of a programming statement

Copyright 2014 Pearson Education, Inc.

68

Use VS to Update Application


Update
Place label and buttons on form Enter code for event handlers Test application

Copyright 2014 Pearson Education, Inc.

69

Colors
Colors
BackColor property sets background color ForeColor property sets text color

Copyright 2014 Pearson Education, Inc.

70

Changing Text Colors


In Properties window
Select color property (BackColor, ForeColor) Click down-arrow button that appears Select color from list

Copyright 2014 Pearson Education, Inc.

71

Changing Forms Appearance


Form properties
FormBorderStyle
Sizable (default)
Has Maximize, Minimize, and Close buttons May be resized by dragging edges

FixedSingle
Has single line border, Maximize, Minimize, and Close buttons May not be resized

Copyright 2014 Pearson Education, Inc.

72

Changing Forms Appearance (cont.)

Copyright 2014 Pearson Education, Inc.

73

Changing Forms Appearance (cont.)


MinimizeBox (Boolean)
Hides Minimize button when set to False
Is disabled but shown if MaximizeBox is set to True

MaximizeBox (Boolean)
Hides Maximize button when set to False
Is disabled but shown if MinimizeBox is set to True

ControlBox (Boolean)
Hides all buttons when set to False

Copyright 2014 Pearson Education, Inc.

74

Changing Forms Appearance (cont.)

Copyright 2014 Pearson Education, Inc.

75

Locking Controls
Locking controls
Prevents controls from being moved or resized during design time To lock
Right-click an empty space on form Select Lock Controls from menu

Copyright 2014 Pearson Education, Inc.

76

Printing Your Code


To print a projects source code
Open Code window Use menu
Click menu FILE/Print on menu bar

- Or - Use keyboard shortcut


Press Ctrl + P
Copyright 2014 Pearson Education, Inc. 77

Using IntelliSense
IntelliSense
Provides automatic code completion as you type programming statements Use arrow keys to scroll through entries Press Tab or Enter key to accept value Example

Copyright 2014 Pearson Education, Inc.

78

VB Default Settings

Tool/Options/Projects and Solutions/VB Defaults


Copyright 2014 Pearson Education, Inc. 79

2.3

Modifying a Controls Text Property with Code


Copyright 2014 Pearson Education, Inc. 80

Text Property
Text property
May be changed
While program is running with code Using an assignment statement

Copyright 2014 Pearson Education, Inc.

81

Modifying Text Property with Code


Suppose a form is established with a label lblMessage whose Text property is: 1 Kilometer = ?
And on a btnFeet button click, we want to change the value of the text property to: 1 Kilometer = 3,281 feet
Copyright 2014 Pearson Education, Inc. 82

Modifying Text Property with Code


Private Sub btnFeet_Click() Handles btnFeet.Click ' Display the conversion to feet. lblMessage.Text = "1 Kilometer = 3,281 feet" End Sub

Assigns the string to the right of the equal sign to the Text property of lblMessage
This replaces the previous Text property of lblMessage with the new value shown
Copyright 2014 Pearson Education, Inc. 83

2.4

AutoSize, BorderStyle, and TextAlign Properties


Copyright 2014 Pearson Education, Inc. 84

AutoSize Property
AutoSize property
Controls whether control will be resized to fit text Values
True (default)
Bounding box will automatically resize itself to fit the amount of text assigned to it

Copyright 2014 Pearson Education, Inc.

85

AutoSize Property (cont.)


False
Labels size may be changed in Designer window with its sizing handles Bounding box will remain the size it was given at design time Text that is too large to fit in the bounding box will be only partially displayed

Copyright 2014 Pearson Education, Inc.

86

BorderStyle Property
BorderStyle property
Determines appearance of a labels border Values
None (default)
Label will have no border

FixedSingle
Label will be outlined with a border one pixel wide

Fixed3D
Label will have a recessed 3D appearance

Copyright 2014 Pearson Education, Inc.

87

TextAlign Property
TextAlign property
Indicates how text is aligned in control Values
TopLeft (default) TopCenter TopRight MiddleLeft MiddleCenter MiddleRight
88

Copyright 2014 Pearson Education, Inc.

TextAlign Property (cont.)


BottomLeft BottomCenter BottomRight

Copyright 2014 Pearson Education, Inc.

89

Changing TextAlign with Code


TextAlign property
May be assigned a value in code Values
ContentAlignment.TopLeft ContentAlignment.TopCenter ContentAlignment.TopRight ContentAlignment.MiddleLeft ContentAlignment.MiddleCenter ContentAlignment.MiddleRight
90

Copyright 2014 Pearson Education, Inc.

Changing TextAlign with Code


ContentAlignment.BottomLeft ContentAlignment.BottomCenter ContentAlignment.BottomRight

Example

Copyright 2014 Pearson Education, Inc.

91

2.5

Displaying User Messages

Copyright 2014 Pearson Education, Inc.

92

Displaying Message Boxes


A message box is a small pop-up message window
Sometimes referred to as a dialog box A convenient way to display message to user Displayed by calling MessageBox.Show() User must click OK button to remove message box

Copyright 2014 Pearson Education, Inc.

93

Displaying Message Boxes (cont.)


Should include a title

MessageBox.Show("Hello World!")
MessageBox dot Show string enclosed in parentheses

Copyright 2014 Pearson Education, Inc.

94

StatusStrip Control
StatusStrip control
Uses a Label to display program status information and messages to user
Ideal way to display messages that are not system critical Does not force user to click a button to clear message

Copyright 2014 Pearson Education, Inc.

95

StatusStrip Control (cont.)

StatusStrip

Copyright 2014 Pearson Education, Inc.

96

Adding StatusStrip and Label to Form


Step 1:
Drag StatusStrip control from Menus & Toolbars section of Toolbox window onto existing form StatusStrip will attach itself to bottom of form This is docking the control
Copyright 2014 Pearson Education, Inc. 97

Adding StatusStrip and Label to Form


Step 2:
Click the down arrow on the right side of the StatusStrip and select StatusLabel from the drop-down list

Copyright 2014 Pearson Education, Inc.

98

Adding StatusStrip and Label to Form


ToolStripStatusLabel control will be added to StatusStrip
Set (Name) property with a more meaningful name Clear Text property

Copyright 2014 Pearson Education, Inc.

99

2.6

Clickable Images

Copyright 2014 Pearson Education, Inc.

100

Click Event Handlers


Click event handlers
Provide code to take whatever action is desired Controls with click event handlers
Buttons PictureBoxes Labels

Copyright 2014 Pearson Education, Inc.

101

Form1 of Flags Project

Label1

picUSA
picCanada picUK

picAustralia
picBrazil picItaly

lblMessage
btnExit

Copyright 2014 Pearson Education, Inc.

102

PictureBox Click Event Handler


When PictureBox picUSA is clicked
lblMessage Text property is set to display "United States of America"
Private Sub picUSA_Click() Handles picUSA.Click ' Display United States of America. lblMessage.Text = "United States of America" End Sub

Copyright 2014 Pearson Education, Inc.

103

2.7

Using Visual Studio Help

Copyright 2014 Pearson Education, Inc.

104

Visual Basic Help


For Help in Visual Basic, use
F1 key - context sensitive help
Displays information about feature user is currently focused on

Help menu

Copyright 2014 Pearson Education, Inc.

105

Accessing the Visual Studio Documentation

Copyright 2014 Pearson Education, Inc.

106

Context-Sensitive Help
Context-sensitive help
Help on a single topic that you are currently working on To initiate
Select an item you need help with in Visual Studio Then press F1 key on keyboard This launches a help screen in your Web browser

Copyright 2014 Pearson Education, Inc.

107

Context-Sensitive Help (cont.)


Example
To get help on = operator
Select =, then press F1

Copyright 2014 Pearson Education, Inc.

108

Context-Sensitive Help (cont.)

Copyright 2014 Pearson Education, Inc.

109

2.8

Debugging Your Application

Copyright 2014 Pearson Education, Inc.

110

Errors
Errors
Prevent application from operating properly Most applications contain errors or bugs Types
Compile errors Runtime errors

Copyright 2014 Pearson Education, Inc.

111

Compile Errors
Compile errors
Syntax (form) of code
i.e. Misspelled keywords, incorrect use of operators or punctuation

Visual Basic informs you as soon as code is entered Code in error underlined with jagged blue line Error description appears in Error List window*
*Note: Display Error List window by selecting Error List from View menu option
Copyright 2014 Pearson Education, Inc. 112

Syntax Errors
Syntax Errors

Copyright 2014 Pearson Education, Inc.

113

Compile Errors (cont.)


Compile errors
Description of error will be given in Error List window Display Error List window by selecting VIEW/Error List Double-click error message to position cursor at error in Code window

Copyright 2014 Pearson Education, Inc.

114

Compile Errors (cont.)

Copyright 2014 Pearson Education, Inc.

115

Runtime Errors
Runtime error
Occurs while program is running, when VB attempts to perform an operation that can not be executed Creates incorrect results, but do not prevent program from running VB detects some and informs you about them Others you must detect yourself
Note: Always carefully check the operation of your program to be sure that it operates as required
Copyright 2014 Pearson Education, Inc. 116

Topics Covered
Topics covered
2.1 Building the Directions Application 2.2 Responding to Events 2.3 Modifying a Controls Text Property with Code 2.4 AutoSize, BorderSize, and TextAlign Properties 2.5 Displaying User Messages
Copyright 2014 Pearson Education, Inc. 117

Topics Covered
2.6 Clickable Images 2.7 Using Visual Studio Help 2.8 Debugging Your Application

Copyright 2014 Pearson Education, Inc.

118

You might also like