1 web-enabled decision support systems visual basic.net programming language prof. name...

Post on 04-Jan-2016

222 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1

Web-Enabled Decision Support Systems

Visual Basic .NET Programming Language

Prof. Name name@email.comPosition (123) 456-7890University Name

2

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

3

Introduction

A computer program is a sequence of precise, unambiguous, and detailed instructions on how to complete a task, written in a language that can be interpreted by a computer– A programming language is language used to express these instructions

Visual Basic is an example of one such programming language – Visual Basic statements are similar to sentences in English

Have specific syntax, nouns, verbs, etc.

Grouped into subroutines, functions, and modules to enhance the readability and flow of logic of an application

4

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

5

Visual Basic Statements

A Visual Basic statement is a complete instruction written in the VB language– Language syntax are the rules and regulations that govern the composition

of VB statements

– Each statement contains one or more of the following elements: Keywords: Reserved words of the language

Variables: Containers for values

Constants: Special variables with fixed values

Operators: Symbols used to perform arithmetic and logical operations

Operands: Numerical or string values that may be parts of expressions

Expressions: Combinations of one or more of the above terms that yields a value

6

Keywords

Keywords are the reserved words of a programming language– Convey the same specific meaning every time they are used

Boolean Class Do EOF For Loop Null ByRef Const Double End Function Case ReDim ByVal Date Else Exit If Mod True Case Dim ElseIf False InputBox Month With

Visual Basic Code Example

Visual Basic Keywords

7

Variables

A variable is a temporary name given to a memory location– When writing a program, we need to store, manipulate, and reuse

intermediate data values

– Variables can temporarily store values and thus act like containers

We use the keyword Dim to declare variables in Visual Basic – Allocates or reserves the space for values to be stored

– Variable declaration syntax:

– Examples:

Dim <Variable Name> As <Data Type> [= <Initial Values (s) >]

Dim TemperatureF As Integer = 1 Dim Weather As String = “Cold” Dim Comments As String

8

Constants

A constant is a special type of variable whose value is not allowed to change once it has been assigned– We use the keyword Const to declare constants in Visual Basic

– Constant declaration syntax:

– Examples:

Visual Basic features two kinds of statements: – Declaration statements name and create variables, determine their types,

and assign initial values

– Executable statements perform an action that generates an output and can be stored in declared variables

Const <Constant Name> As <Data Type> = <Final Values>

Const factor As Integer = 32 Const PI As Integer = 3.14

9

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

10

InputBox and MessageBox

The InputBox function prompts an input dialog box and waits for the user input– When the user clicks the OK button on the input dialog box, the function

returns the input value

– Syntax:

The MessageBox function is used to display a message to the user in an output dialog box– Syntax:

Variable x = InputBox (Prompt, Title, Default Response, X-Pos, Y-Pos)

MessageBox.Show (Message, Title, Type, Icon)

11

Hands-On Tutorial: User Input/Output

How-to: Use Visual Basic InputBox and MessageBox Functions1. Create a new Visual Basic project named VisualBasicIntro.

2. Add a new Button control to the default form. Set the Text property of the button to “Temperature Conversion” and name it, cmdConvert. Use the GroupBox control with no text value around the Button control.

User Input/Output: Design Window

12

Adding Code Using the Code Window

3. Double-click the Button control to open the Code Window with the cmdConvert _Click subroutine.

4. Declare the variables TemperatureC and TemperatureF as Integers, and write conversion logic as shown below.

User Input/Output: Code Window

13

Saving and Running the Application

5. Save and run the application to view the output shown below.

User Input/Output: Application Output

14

The InputBox Function

InputBox syntax:

– Elements: Prompt: A string that appears as a text inside the dialog box that prompts the user Title: A string that appears in the title bar of the dialog box Default: The default value of the InputBox, displayed when the dialog box is shown

to the user X-Pos, Y-Pos: Integer values for X and Y co-ordinates for positioning the dialog

box on the screen

Examples:

Variable x = InputBox (Prompt, Title, Default Response, X-Pos, Y-Pos)

InputBox (“Enter Your Age”, “Age Calculator”, , 100,100) – No default value

InputBox (“Enter Your Age”, ,25) – No Title and No X-Pos and Y-Pos

InputBox (“Only Prompt”)

15

The MessageBox Function

MessageBox syntax:

– Elements: Message: The text to display (may may be a string, integer, variable, or some

combination of these) Title: A string that appears as a text in the title bar of the dialog box Type: The type of MessageBox Icon: Icon for the MessageBox

Examples:

MessageBox.Show (Message, Title, Type, Icon)

MessageBox.Show(“Your Age is :=” & Age, “Age Calculator”, _

MessageBoxButtons.OK, MessageBoxIcon.Information)

MessageBox.Show(“Your Age is :=” & Age, “Age Calculator”)

MessageBox.Show(“Your Age is :=” & Age)

16

MessageBox Options

Option Description

MessageBoxButtons.AbortRetryIgnore Allows user to abort, retry, or ignore the running operation.

MessageBoxButtons.OKCancel Allows user to either continue or cancel the operation.

MessageBoxButtons.YesNoCancel Allows user to respond in yes or no format or select cancel to

exit.

MessageBoxIcon.Warning Shows an exclamation mark on the dialog box. Used to

indicate caution.

MessageBoxIcon.Information Shows an information mark on the dialog box.

MessageBoxIcon.Error Shows an error mark on the dialog box.

MessageBoxIcon.Question Shows a question mark on the dialog box.

MessageBox Buttons and Icons

17

Visual Basic’s Online Help

The Visual Studio IDE assists us in the process of application development, making it an interactive process– Tool Tips provide help on the syntax of statements

– IntelliSense intelligently displays only the relevant methods or options

Example of Online Tool Tip

The MessageBox IntelliSense

18

Adding Comments to Visual Basic Code

Comments are text lines that begin with a single quote or apostrophe (‘) character – Used to write useful explanatory comments along with the code lines

– Ignored while the program is executing

– Examples:'This entire line is a now a VB comment.

Dim TemperatureF As Integer 'Variable Holds the Temp in F

19

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

20

Visual Basic Data Types

When we declare a new variable, we must specify its data type– Indicates the kind of data that will be stored in the variable

Data Type Size Range

Integer 4 Bytes - 2,147,483,648 to 2,147,483,648

Long 8 Bytes ~ - 9.2 x 1018 to 9.2 x 1018

Double 8 Bytes ~ - 1.79 x 10308 to 1.79 x 10308

String Variable 0 to 2 Billion Characters

Char 2 Bytes 0 to 65535

Boolean 2 Bytes True or False

Date 8 Bytes January 1, 0001 to December 31, 9999

Object 4 Bytes Anything that can be stored as a Object

Visual Basic Data Types

21

Checking and Converting Data Types

Two common operations are associated with data types: – Checking existing data types

– Converting to other data types

Visual Basic provides excellent support for data type manipulations with its dozens of built-in functions

Checking functions are also known as logical functions, as they check for a particular data type and return a logical True or False value– Examples:

IsNumeric () Returns True if numeric value; False otherwise.

IsDate () Returns True if date value; False otherwise.

IsArray () Returns True if an Array; False otherwise.

IsError () Returns True if an Error; False otherwise.

22

Conversion Functions

Examples:

There is a generic function, CType, for data type conversions:– Syntax:

CInt Converts to the Integer data type.

CLng Converts to the Long data type.

CDbl Converts to the Double data type.

CStr Converts to the String data type.

CBool Converts to the Boolean data type.

CDate Converts to the Date data type.

CObj Converts to the Object data type.

CType (ConvertMe, toThis)

23

Hands-On Tutorial: Data Type Conversion

How-to: Use Data Type Conversion Functions1. Continue with the VisualBasicIntro project and Form1 from the “Temperature

Conversion” hands-on tutorial. Add a cmdDataTypeConvert command button, and change the Text property to “Data Type Conversion”. Use the GroupBox control with no text value around the Button control.

Data Type Conversion Example: Design Window

24

Adding Code

2. Associate the code below with the newly added command button.

Data Type Conversion Example: Code Window

25

Running the Application

3. Press Ctrl+F5 to run and test the application.

Data Type Conversion Example: Application Output

26

Hands-On Tutorial: Data Type Checking

How-to: Use Data Type Checking Functions 1. Continue with Form1 from the previous hands-on tutorial. This time add a

cmdDataTypeChk command button; change its Text property to “Data Type Checking”.

Data Type Checking Example: Design View

27

Adding Code and Running

2. Associate the code below with the cmdDataTypeChk_Click event.

3. Save and run the application.

Data Type Checking Example: Code Window

Data Type Checking Example: Output Window

28

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

29

Adding Windows Forms

How-to: Add a Windows Form to the Existing Project1. Choose Project | Add Windows Form from the Main menu to open the Add

New Item dialog box.

2. Select Windows Form in the templates area of the window; accept the default form name and click the Add button.

Adding a New Windows Form

30

Setting Start-up Form

How-to: Set the Start-up Form 1. Choose Project | <Project Title> Properties from the Main menu to open the

Properties page.

2. Select the desired startup form from the “Startup form” drop down list. Press Ctrl+S to save the settings.

Setting the Startup Form

31

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

32

Control Structures

Control structures allow us to control the flow of program execution– By default, a program is executed sequentially:

Left to right Top to bottom

– Control structures allow us to skip over or loop a given section of the code

– Classified into two categories: Decision structures: Allow us to test conditions Loop structures: Allow us to execute one or more lines of code repetitively

33

If-Then

We use an If-Then structure to execute one or more statements conditionally– Syntax:

– Examples:

If (<condition>) Then Body of If End If

'Check whether the input number is greater than 100 If (x > 100) Then

MessageBox.Show(”The Input Number is greater than 100”) End If 'Check whether Num is zero If (Num = 0) Then Factorial = 1

End If

34

If-Then-Else

The Else statement allows us to specify the action to be performed if the condition of the If statement is not satisfied– Syntax:

– Example:

If (<condition>) Then Body of If Else Body of Else End If

'Check whether the input is an even or odd number If (x Mod 2) = 0 Then

MessageBox.Show(x & “is an even number”) Else MessageBox.Show(x & “is an odd number”)

End If

35

If-Then-Else – Logical Flow Chart

If-Then-Else Structure’s Logical Flow Chart

36

If-Then-ElseIf-Else

We can use an If-Then-ElseIf-Else statement to apply multi-level selections – Syntax:

– Example:

If (<condition1>) Then Body of If1 ElseIf (<condition2>) Then Body of If2 . . Else Body of Else End If

'Compare the input numbers If (a > b) Then

MessageBox.Show(“The First Number is greater than Second Number”) ElseIf (b > a) Then MessageBox.Show(“The Second Number is greater than First Number”) Else MessageBox.Show(“Both Input Numbers are Equal”) End If

37

The RadioButton Control

RadioButton controls force their users to select from a set of two or more mutually exclusive choices– Often used properties and events of a RadioButton control:

– Example:

RadioButton Control Example

Name Description

Checked Sets/gets a value indicating whether the radio button is checked.

Image Sets/gets a checkbox image.

CheckedChanged Occurs when the Checked property changes.

38

Hands-On Tutorial: Using If-Then-Else Structure

How-to: Use the If-Then-Else Control Structure and RadioButton Control1. Design Form2 as shown below. Make Form2 the start-up form. Name the

three RadioButton controls as: radBS, radMS and radPhD, and name the Button control as cmdCheckStatus.

RadioButton Control Example: Degree Selection

39

Adding Code and Running

2. Associate the code below with the command button’s Click event.

3. Save, run, and test the application.

Code Window

ApplicationOutput

40

Using Select-Case Structures

The Select-Case structure selectively executes one among multiple “cases” – A single test expression is evaluated once and compared with the values of

each case clause in the structure Only the first matching case gets executed

– Conceptually similar to the If-Then-Else structure Enhances code readability when there are several possibilities to consider

– Syntax: Select Case <TestExpression> Case <Expression 1> Body of Case1 Case <Expression 2> Body of Case2 . . Case <Expression n> Body of Case n Case Else Body of Case Else End Select

41

Select-Case Structure - Flowchart

Select-Case Structure’s Logical Flow Chart

42

Select-Case Structure - Example

Numbers a and b and operator op (+, -, *, /) are user inputs– Depending upon the input operator, we can perform the correct operation

using a case statement as follows:

Select Case op Case +

MessageBox.Show(“a + b =” & (a + b)) Case - MessageBox.Show(“a - b =” & (a - b)) Case * MessageBox.Show(“a * b =” & (a * b)) Case / MessageBox.Show(“a / b =” & (a / b)) Case Else MessageBox.Show(“Enter only (+ OR - OR * OR /) Operators”) End Select

43

The TextBox Control

A TextBox control is a box-shaped control that can display text data or allow the user to input the text data – Can have multiple lines and scroll bars

– Can be made read-only

– Most important property is Text, which allows us to access the text value

Example of a TextBox Control

44

Hands-On Tutorial: Working with Select-Case Structure

How-to: Use the Select-Case Control Structure and TextBox Control1. Add a new form, Form3, to the VisualBasicIntro project and set Form3 as the

start-up form. Add a TextBox named txtMonthAbbr and a command button, cmdCheckDays.

2. Design the form as shown below.

Select-Case Structure Example: Design View

45

Adding Code and Running

3. Use the code shown below for the Click event of the command button. Save, run, and test the application.

Select-Case Structure Example: Code Window

46

Loop Structures

Loop structures are used to execute blocks of statements multiple times– Here, we discuss four types:

Do-Loop-While, Do-While-Loop, Do-Loop-Until, and Do-Until-Loop

– Each variant evaluates a Boolean condition to determine whether or not to continue the execution of the loop

– Categorize by when the Boolean condition is checked: Prior to loop execution: Do-While-Loop and Do-Until-Loop After the loop execution: Do-Loop-While and Do-Loop-Until

– Categorize by how the Boolean condition is interpreted: Continue loop execution while the condition is true, stop once it is false: Do-While-

Loop and Do-Loop-While Continue loop execution until the condition is false, stop once it is true: Do-Until-

Loop and Do-Loop-Until

47

Logical Flow Charts

Do-Loop-While and Do-While-Loop: Logical Flow Charts

48

Do-Loop-While

Syntax:

Example:

Do Body of the loop Loop While (<condition>)

49

Do-While-Loop

Syntax:

Example:

Do While (<condition>) Body of the loop Loop

50

Do-Loop-Until

Syntax:

Example:

Do Body of the loop Loop Until (<condition>)

51

Do-Until-Loop

Syntax:

Example:

Do Until (<condition>) Body of the loop Loop

52

Hands-On Tutorial: Working with Do-Loop Structure

How-to: Use the Do-Loop Control Structure1. Add a new form, Form4, to the existing project. Set Form4 as a startup form.

2. Add three TextBox controls named txtFirstNum, txtSecondNum and txtSumStep. Also add a Button control named cmdSum.

Sum Using Do-Loop-While Structure: Design Window and Output

53

Adding Code and Running

3. Use the code below for the Click event of the cmdSum Button control.

4. Save, run, and test the application.

54

Alternative Coding

Do-While-Loop:

Do-Until-Loop:

Do-Loop-Until:

55

For-Next Structures

The Do-Loop structures works well when we do not know how many times we must execute the loop statements

For-Next is an alternative when we know the specific number of times we want to execute the loop– Syntax:

– Example:

For <counter = Start Value> To <End Value> [Step <Increment Value>] Body of the For Loop Next

56

For-Next Structure – Logical Flow Chart

For-Next Structure’s Logical Flow Chart

57

Hands-On Tutorial: Working with the For-Next Loop Structure

How-to: Use the For-Next Control Structure1. Add a new form, Form5, to the existing project. Set the Form5 as a startup

form. Set up this form and form controls as shown below.

For-Next Loop Structure Example: Design View

58

Adding Code and Running

2. Use the code below for the Click event of the command button.

3. Save, run, and test the application.

59

For-Each-Next Loop Structure

The For-Each-Next structure syntax is essentially the same as the For-Next syntax except that the loop is executed for each element of the group instead of a specific number of times– Helpful if we need to perform operations on groups such as CheckBoxes

– Syntax:

– Example:

For Each <element> In <Group> Body of the For loop Next

60

The Exit Statement

The Exit statement allows us to end the execution of a loop, subroutine, or function – Syntax:

– Examples: Exit Sub Exit Select Exit Do Exit For Exit Function

Exit <What?>

61

Exit Statement - Example

“Exit Sub” example:

62

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

63

Arithmetic Operators

Arithmetic operators operate on one or more operands to produce an output value

Operator Meaning Example

*, / Multiplication and division x * y. Multiply x with y

+, - Addition and subtraction x + y. Add x to y

^ Exponential x ^ y. x to the power of y

Mod Modulo x Mod y. x Modulo y

*=, /= Multiplication/division followed by assignment x *=y. x = x* y

+=, -= Addition/subtraction followed by assignment x +=y. x = x + y

= , <> Equal to, Not equal to x <> y. x is not equal to y

> , < Greater than, less than x > y. x is greater than y

>=, <= Greater than or equal to, Less than or equal to x >= y. x is greater than or equal to y

Arithmetic Operators (in order of precedence)

64

Logical Operators

Operator Meaning Example

And Logical And two

operands

X And Y. If both X and Y are true, return true; otherwise, return

false.

Not Reverse the logical

value of a operand

Not X. If X is true, then return false and vice versa.

Or Logical Or two

operands

X Or Y. If either X or Y is true, return true; otherwise, return false.

Xor Logical Exclusive Or

two operands

A Xor B. If A is true OR B is true, return true (Exclusive). If both

A and B have the same value (true/false), return false.

Logical Operators

65

Math Functions

Some of the functions associated with the Math collection:– Abs: Returns the absolute value of a specified

– Sin, Tan, Cos: Returns the sine, tangent, and cosine values of the angle

– Min, Max: Returns the smaller and greater of the given two numbers

– Floor: Returns the greatest integer less than or equal to its numeric argument

– Ceiling: Returns the smallest integer greater than or equal to its numeric argument

– Sqrt: Returns the square root of the specified number

– Pow: Returns the specified number raised to the specified power

66

Math Functions - Example

We illustrate the use of Pow and Sqrt math functions with an example of Pythagoras' Theorem:

– Calculate the length of the hypotenuse (output) of a right-angled triangle, given the length of its other two sides (inputs)

– Code:

Pythagoras’ Theorem Example: Code Window

67

Handling Strings

Working with the String data type is an important aspect of the application development process– VB .NET has tremendous support for string manipulation

– We can perform a variety of operations on strings: Change the string case Get part of the string Concatenate two strings Compare two strings Search a string

68

String Operations

The following table summarizes the VB .NET String operations:

What to do How

Concatenate two strings &, +, String.Concat

Compare two strings String.CompareTo(CompareMe), String.Equals(CompareMe)

Copy String =, String.Copy(CopyFrom)

Change Case UCase, LCase, String.ToUpper

Length Len, String.Length

Substring String.Substring(StartPos, Length)

String Search String.IndexOf(SearchString)

Trim Spaces LTrim, RTrim, String.Trim

String Operations

69

Hands-On Tutorial: String Operations

How-to: Use String Concat, Compare, Substring, IndexOf, and Length Functions1. Add a form, Form6, to the current project and set it as the start-up form.

2. Design the form as shown below.

3. Each of the GroupBox controls illustrates a string operation.

Illustrating String Operators: The Form in Design Window

70

Adding Code

4. Use the code below to assign code to the appropriate command buttons.

Illustrating String Operators: Code Window1

71

Adding Code (cont.)

4. Use the code below to assign code to the appropriate command buttons.

Illustrating String Operators: Code Window2

72

Save and Run

5. Save, run, and test the application.

Illustrating String Operators: Application Output

73

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

74

Arrays

An array is a basic data structure that allows us to refer to multiple variables by the same name – All the variables (or elements) in an array have the same data type

– Array declaration syntax:

– Examples:

– Indexing:

Dim <Array Name> As <Data Type> ([<Array Size>-1])

Dim IntArray (4) As Integer '5 elements Dim DobArray (14) As Date '15 elements Dim LongArray (49) As Long '50 elements

Example of an Integer Array

75

Hands-On Tutorial: Working with Arrays

How-to: Declare and Use Arrays1. Add a new form, Form7, to the existing VisualBasicIntro project. Set Form7

as the start-up form.

2. Design the form as shown below. Name the command button as, cmdPopulateArray. Set its Text property to “Populate Me”.

An Array Example: Design Window

76

Adding Code

3. For the Click event of the command button cmdPopulateArray, write the code shown below.

Array Example: Code Window

77

Saving and Running

4. Save, run, and test the application.

Array Example: Application Output

78

The ListBox Control

The ListBox control presents a list of choices to the user– By default, the choices are displayed vertically in a single column

– Some properties and methods: SelectedItem: Gets/sets the currently selected item SelectedIndex: Gets/sets the index of a currently selected item Items: Gets/sets collection of all the items Items.Clear: Clears all the items in the list ClearSelection: Sets SelectedIndex = -1 (clears any selection)

Example of a ListBox Control

79

Adding Items to a ListBox

We can add items to a list at design-time using the Properties Window– Locate the Items property in the Property Window

– Click the Build button in the property row to open the String Collection Editor

– The editor allows us to enter item values to the list

We can also add items at run-time in the VB .NET code– Employ Items.Add method:

Adding Items to a ListBox Control

80

Hands-On Tutorial: Displaying Array in a ListBox Control

How-to: Add Elements to a ListBox Control1. Add a new form, Form8, to the existing VisualBasicIntro project. Set Form8

as the start-up form.

2. Add a ListBox and Button controls as shown below. Name the Button control as cmdArray and the ListBox control as lstArray. Set the Text property of the ListBox control to “Populate Me”.

Displaying Array in a ListBox Control: Design Window

81

Adding Code and Running

3. Associate the code below with the Click event of the cmdArray command button.

4. Save and run the application by pressing Ctrl+F5.

82

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

83

Multi-Dimensional Arrays

Multi-dimensional arrays have two or more dimensions– Visualized as a grid with rows of the grid representing one of the dimensions

and columns representing the other

– Declaration syntax:

– Example:

Dim <Array Name> ([<1st D Size>]),… ([<nth D Size>]) As <Data Type>

Dim Students (3, 4) As Double '4 rows and 5 columns

84

Using Loops with Multi-Dimensional Arrays

We can efficiently process a multi-dimensional array by using nested For-Next loops– The code below initializes (lines 9-14) and displays (lines 16-21) the Student

array

85

Hands-On Tutorial: Working with Multi-Dimensional Arrays

How-to: Use Multi-Dimensional Arrays and the DataGridView Control1. Add a new form, Form9, to the existing VisualBasicIntro project. Set Form9

as the start-up form.

2. Drag and drop a DataGridView control from the Toolbox on Form9. Name the DataGridView control dgvArray.

3. Add a Button control named cmdMultDArray to the form and set its Text property to “Enter Grades”.

Displaying a Two-Dimensional Array in the DataGridView Control: Design Window

86

Adding Code

4. Associate the code below with the Click event of the command button.

An Example of Dynamic Arrays: Code Window

87

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

88

Dynamic Arrays

Dynamic arrays are arrays whose size can be changed at run-time– As opposed to static arrays which always remain the same size

– Useful when we do not know the exact number of elements to be stored

– Visual Basic lets us assign or change the array size at run time using the ReDim (re-declare) keyword

– Re-declaration syntax:ReDim <Array Name> (<Array Size>)

89

Dynamic Array - Example

Dynamic Array Example:Form Design

Dynamic Array Example:Code Window

90

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

91

Code Debugging

Debugging is the process of finding and fixing syntax and logical errors

Syntax errors occur because of incorrect syntax use or human errors – Visual Studio .NET assists us in detecting syntax errors as we write the code

Underlines the construct where there is a syntax error

Syntax Error in the Outer For-Next Loop Structure

92

Logical Errors

Logical errors arise due to flaws in the logical reasoning of an application design – Detecting and handling logical errors can be very challenging

– Often result in run-time exceptions when executed

Logical Error: Run-Time Error Message for IndexOutOfRange Exception

93

Using Breakpoints

With breakpoints we can specify a line in the code where we want to break the execution of a program – Helps when debugging logical errors

– Program execution pauses at the breakpoint so that we can observe the values of various variables at that point in time

– To add/remove a breakpoint, click in the selector area of the code line

Adding Breakpoints to the Code

94

Breakpoint Features

Breakpoints offer many interesting features:– Break on a breakpoint conditionally

– Skip a breakpoint based on how many times it was hit

Breakpoint ConditionDialog Box

Breakpoint Hit CountDialog Box

95

Using the Watch Window

The Watch Window is used to watch the values of different variables during the execution of a program – To open a Watch Window, we must be in debug mode

We can open a Watch Window by choosing the Debug | Windows | Watch | Watch1 option form the Main menu

Opening a Watch Window

96

Using the Watch Window (cont.)

In a Watch Window, we can add the names of the variables we would like to watch – The corresponding values are displayed in the Value column

– Every time we break (or pause) the execution using a breakpoint, we can watch the values of variables

Adding Variables to the Watch Window

97

Using Debug Toolbar and Menu

As we break program execution and watch variables, we have many options available in the Debug toolbar and Debug menu:– Continue (F5)

– Stop Debugging (Ctrl+Alt+Break)

– Step Into (F8)

– Step Over (Shift+F8)

– Step Out (Ctrl+Shift+F8)

The Debug Menu

98

Debug Menu Options

Option Description

Continue Continues the execution until next break point.

Stop Debugging Stops the execution. Gets us out of debugging mode.

Step Into Steps into a procedure. If the current line of the program is not a

procedure call, we move to the next line of the code.

Step Over Executes the procedure without stepping into it. The procedure will be

executed and we move to the next code line. Again, if the current line is

not a procedure call, we move to the next line of the code.

Step Out Executing remaining statements of the procedure and gets out of the

procedure.

Debug Menu Options

99

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

100

In-Class Assignment

Create a Windows application that will compute the sum of squares of a series of numbers, given:– Starting number (SN)

– Ending number (EN)

– Step value (SV)

– Example: Given SN=1, EN=5, and SV=1 The series is 1,2,3,4, and 5 The sum of squares is 1+2+9+16+25=53

– Directions: Use either a Do-While loop or a For-Next loop to compute the sum, and display it

in a MessageBox to the user. Also display a series and square values in two ListBox controls.

Use a Double variable to hold the sum of squares. Also, if the value entered for EN is larger than 100,000, we exit the program without computing the sum.

101

Overview

11.1 Introduction 11.2 Visual Basic Statements 11.3 InputBox and MessageBox 11.4 Visual Basic Data Types 11.5 Adding Windows Forms and Setting Start-up Form 11.6 Control Structures 11.7 Arithmetic, Logical, and String Operators 11.8 Arrays 11.9 Multi-Dimensional Arrays 11.10 Dynamic Arrays 11.11 Code Debugging 11.12 In-Class Assignment 11.13 Summary

102

Summary

A computer program is a sequence of precise, unambiguous, and detailed instructions on how to complete a task, written in a language that can be interpreted by a computer. – A language used to express these instructions is referred as a programming

language.

A complete instruction written in Visual Basic language is known as a Visual Basic statement. – The rules and regulations that govern the composition of VB statements are

known as language syntax.

– A Visual Basic statement contains one or more of the following elements: Keywords: Reserved words for Visual Basic’s use Variables: Containers for values; temporary names given to memory locations Constants: Special variables with fixed values Operators: Symbols used to perform arithmetic and logical operations on operands Operands: Numerical or string values to operate on

103

Summary (cont.)

We use the keyword Dim to declare a variable in Visual Basic. – The type of a variable (data type) indicates the kind of data that will be stored

in the variable.

InputBox controls helps us obtain data from a user using a dialog box. MessageBox controls take a value as an input parameter and display it

to the user in a dialog box.

Control structures allow us to control the flow of program execution; they consist of two categories, which are based on the behavior they create:– Decision structures

Allow us to test conditions (If-Then, Select-Case)

– Loop structures Allow us to execute one or more lines of code repetitively (Do-Loops, For-Next

Loops)

104

Summary (cont.)

An array is a basic data structure that allows us to refer to multiple variables by the same name. – Visual Basic features two types of arrays:

A static array whose size always remains the same A dynamic array whose size can be changed at run-time

There are two kinds of errors that can occur in a program: – Syntax errors

Occur because of incorrect syntax use or human errors

– Logical (semantic) errors Arise due to flaws in the logical reasoning of an application design

Debugging is the process of finding and fixing syntax and logical errors – Detecting and handling logical errors can be very challenging

– Breakpoints and Watch Windows help detect logical errors

top related