324
8 March 2013 Introduction to VB.Net 2012 Page 1 Contact Stuffucanuse.com for more resources and files for this manual Visual Basic.Net training 2013 Contents Cheat Sheet for VB.net ....................................................................................................... 6 Microsoft Exam 98-361: Software Development Fundamentals ........................................ 8 Microsoft Exam 98-362: Windows Development Fundamentals ...................................... 11 1. Structure Diagrams - Processes, Decisions and Loops ...............................................14 Introduction to VB.net ....................................................................................................... 15 Variables ....................................................................................................................... 19 Data Types .................................................................................................................... 20 Detecting Keypress events ............................................................................................... 22 Structure Diagram for part of lesson 1 .......................................................................... 22 Operators .......................................................................................................................... 22 Advanced math with System.Math ............................................................................... 23 Code Snippets tool ............................................................................................................ 25 Learning to code defensively - Refactoring your code...................................................... 25 Using My ........................................................................................................................... 25 Learning to code defensively - Some coding ideas .......................................................... 26 2. If Statements ...............................................................................................................27 Grades Project .................................................................................................................. 27 Learning to code defensively -Use Try / Catch for error Checking ................................... 29 3. Select Case Statement ................................................................................................31 Finding out the average of grades entered. ...................................................................... 31 Max and Min using IF ........................................................................................................ 32 Learning to code defensively - Catching if just Numeric or Text entered ......................... 34 Using Keypress to allow only numbers ............................................................................. 34 4. IF with AND and OR Does the car run? ....................................................................36 Calculator Project .............................................................................................................. 38 Temperature Converter program ...................................................................................... 39 5. Sender ........................................................................................................................40 Using Sender exercises .................................................................................................... 40 Using Sender to determine what type of control you clicked ............................................ 42 Calculator part 2 using Sender ......................................................................................... 44 Order a sandwich program ............................................................................................... 46 Rock Scissors Paper ......................................................................................................... 47 Adding a new Form or Dialog Box to show images .......................................................... 49 6. Adding images to a Resource file ................................................................................51 Guess The Correct Answer game..................................................................................... 53 Employee wages ............................................................................................................... 53 Better Brains College If, And, and Or ............................................................................ 53 Lucky Guess Project ......................................................................................................... 54 7. Subroutines and Functions ..........................................................................................56 Subroutines that don’t return data – (Subs) ...................................................................... 56 Subroutines that accept data ............................................................................................ 57 Subroutines that accept data and return it- Functions ...................................................... 58 Coding goals for Subs and Functions ........................................................................... 59 8. Byref and Byval - Functions - overview........................................................................60 ByVal (pass a copy of the data) and ByRef (change the original data) ............................ 60 ByRef or ByVal Example............................................................................................... 61 Times Table tester ............................................................................................................ 63 9. Picture Viewer using containers ..................................................................................66 10. Changing Control Panel setting using the SystemParametersInfo ...............................70 Changing the desktop wallpaper in the Picture viewer ..................................................... 70

Intro to VB 7 March 2013

Embed Size (px)

Citation preview

Page 1: Intro to VB 7 March 2013

8 March 2013 Introduction to VB.Net 2012

Page 1 Contact Stuffucanuse.com for more resources and files for this manual

Visual Basic.Net training 2013 Contents

Cheat Sheet for VB.net ....................................................................................................... 6

Microsoft Exam 98-361: Software Development Fundamentals ........................................ 8

Microsoft Exam 98-362: Windows Development Fundamentals ...................................... 11

1. Structure Diagrams - Processes, Decisions and Loops ...............................................14 Introduction to VB.net ....................................................................................................... 15

Variables ....................................................................................................................... 19 Data Types .................................................................................................................... 20

Detecting Keypress events ............................................................................................... 22

Structure Diagram for part of lesson 1 .......................................................................... 22 Operators .......................................................................................................................... 22

Advanced math with System.Math ............................................................................... 23 Code Snippets tool ............................................................................................................ 25

Learning to code defensively - Refactoring your code...................................................... 25

Using My ........................................................................................................................... 25

Learning to code defensively - Some coding ideas .......................................................... 26

2. If Statements ...............................................................................................................27 Grades Project .................................................................................................................. 27

Learning to code defensively -Use Try / Catch for error Checking ................................... 29

3. Select Case Statement ................................................................................................31

Finding out the average of grades entered. ...................................................................... 31

Max and Min using IF ........................................................................................................ 32

Learning to code defensively - Catching if just Numeric or Text entered ......................... 34

Using Keypress to allow only numbers ............................................................................. 34

4. IF with AND and OR – Does the car run? ....................................................................36 Calculator Project .............................................................................................................. 38

Temperature Converter program ...................................................................................... 39

5. Sender ........................................................................................................................40 Using Sender exercises .................................................................................................... 40

Using Sender to determine what type of control you clicked ............................................ 42

Calculator part 2 using Sender ......................................................................................... 44

Order a sandwich program ............................................................................................... 46

Rock Scissors Paper ......................................................................................................... 47

Adding a new Form or Dialog Box to show images .......................................................... 49

6. Adding images to a Resource file ................................................................................51

Guess The Correct Answer game..................................................................................... 53

Employee wages ............................................................................................................... 53

Better Brains College – If, And, and Or ............................................................................ 53

Lucky Guess Project ......................................................................................................... 54

7. Subroutines and Functions ..........................................................................................56

Subroutines that don’t return data – (Subs) ...................................................................... 56

Subroutines that accept data ............................................................................................ 57

Subroutines that accept data and return it- Functions ...................................................... 58

Coding goals for Subs and Functions ........................................................................... 59 8. Byref and Byval - Functions - overview ........................................................................60

ByVal (pass a copy of the data) and ByRef (change the original data) ............................ 60

ByRef or ByVal Example............................................................................................... 61 Times Table tester ............................................................................................................ 63

9. Picture Viewer using containers ..................................................................................66

10. Changing Control Panel setting using the SystemParametersInfo ...............................70 Changing the desktop wallpaper in the Picture viewer ..................................................... 70

Page 2: Intro to VB 7 March 2013

8 March 2013 Introduction to VB.Net 2012

Page 2 Contact Stuffucanuse.com for more resources and files for this manual

Telecom Smart Phone Bill Project .................................................................................... 72

11. Multichoice test ...........................................................................................................76 Adding a Splash Screen ................................................................................................... 79

12. Transparent background and automatic shutdown program ........................................81 Creating an Icon ............................................................................................................ 82 Getting an Exe .............................................................................................................. 82 Changing the Startup Form .......................................................................................... 83 Create a fading closing form ......................................................................................... 84 Another way to shut down …… .................................................................................... 85

13. Loops In VB.Net ..........................................................................................................86 For…Next Loop ................................................................................................................. 86

The Leap Year Program – For loop .................................................................................. 88

Using Mod ..................................................................................................................... 88 14. Do While…Loop ..........................................................................................................89

The Leap Year Program – part 2 Do While loop ............................................................... 89

Do While – Fibonacci Sequence ....................................................................................... 91

Find the even Fibonacci numbers only ......................................................................... 92 What is the first Fibonacci number to contain 1000 digits? .......................................... 92

Do…Loop While ................................................................................................................ 93

Do…Loop Until .................................................................................................................. 93

15. For Each Loop .............................................................................................................94 Find the multiples of 3 and 5 ............................................................................................. 95

Times Table calculator ...................................................................................................... 95

Dice Rolls with Loops ........................................................................................................ 97

Identify the appropriate method for handling repetition .................................................... 99

Depreciation Rate calculator ........................................................................................... 100

Compounding Interest Calculator ................................................................................... 102

Calculate the change for a shop ..................................................................................... 104

Times Table tester with Loop .......................................................................................... 107

16. Password CraCker with loops ................................................................................... 109 DoEvents – a curse or a solution? .............................................................................. 110 Standard Progress Bar ............................................................................................... 111 Simple Custom Progress Bar ..................................................................................... 111 Nested Loops to create logical selection .................................................................... 113

17. Background Workers ................................................................................................. 115

Overview ..................................................................................................................... 115 18. Text to Speech .......................................................................................................... 118

Speech to text ................................................................................................................. 118

19. Structures .................................................................................................................. 120 Heap and Stack Performance ..................................................................................... 121

Structures- Customer Exercise ....................................................................................... 122

Cheque processing using Structure ................................................................................ 125

20. Using Snippets for VB.net to auto create the Class properties .................................. 129

21. Introduction to Classes .............................................................................................. 131 OOP terms .................................................................................................................. 132

Creating a simple class ................................................................................................... 133

Temperature Converter with a Class .............................................................................. 134

Fields, Properties, Methods, and Events ........................................................................ 136

Naming Classes and Methods .................................................................................... 137 22. Encapsulation ............................................................................................................ 137

Dice program with Classes - revisited............................................................................. 139

23. Inheritance – “Is a” .................................................................................................... 141 Weapons Practice – Class, Inheritance, Constructor ..................................................... 142

24. Inheritance based Polymorphism .............................................................................. 147

Depreciation Rate calculator with Class ......................................................................... 148

Class Diagram Practice Assignments using noun analysis ............................................ 148

Page 3: Intro to VB 7 March 2013

8 March 2013 Introduction to VB.Net 2012

Page 3 Contact Stuffucanuse.com for more resources and files for this manual

The Coffee machine– Class Inheritance and Constructor .............................................. 150

Create the drink from the ingredients Classes ................................................................ 154

25. Importing Text into your Program .............................................................................. 155

The File class – simple read and write data to text files ................................................. 156

StreamReader - importing to a ListBox ........................................................................... 157

Saving with StreamWriter ............................................................................................... 158

26. Using OpenFile Dialog and SaveFile Dialog .............................................................. 159 Creating a shopping List ................................................................................................. 161

27. Add Menus and Tool Strip to your project .................................................................. 162

World’s greatest bands ................................................................................................... 162

28. Common String Methods ........................................................................................... 165 Instantiating String Objects ............................................................................................. 165

Iterate a String ............................................................................................................ 167 Split a String ................................................................................................................ 167 Split text to an array .................................................................................................... 167 Extract SubStrings from a String ................................................................................ 168 Reverse a String ......................................................................................................... 168 Compare Two Strings ................................................................................................. 168 Test if String is null or Zero Length ............................................................................. 168 Convert the Case of a String ...................................................................................... 168 Count the occurrence of letters (not spaces) in a string ............................................. 169 Count the occurrences of words in a String ................................................................ 169 Insert Characters inside a String ................................................................................ 170 Replace characters in a String .................................................................................... 170 Create Date and Time from String .............................................................................. 170 Trimming a String ........................................................................................................ 170 Convert String To Integer ........................................................................................... 170

String Functions Exercise ............................................................................................... 171

Char and Chars = Characters ........................................................................................ 175

Starts With and Ends With methods ............................................................................... 176

The Like Operator ........................................................................................................... 177

Check a valid email address ........................................................................................... 179

Check a valid email address – using classes ............................................................. 181 Check domain via the internet .................................................................................... 183 Get the DNS IP addresses from the domain name .................................................... 184

Create a Document Statistics counter ............................................................................ 185

Filter words by length – using class ................................................................................ 186

29. Stringbuilder .............................................................................................................. 190

30. Web interface projects ............................................................................................... 192 Metservice temperature program .................................................................................... 192

Getting through the proxy server ................................................................................ 194 Whitepages Phone book ................................................................................................. 196

DuckDuckGo interface using Json .................................................................................. 197

31. The DateTime and TimeSpan Types ......................................................................... 200 Useful DateTime Members ......................................................................................... 201 Useful TimeSpan Members......................................................................................... 202

32. Arrays and Collections .............................................................................................. 203 Arrays Exercise ............................................................................................................... 204

Arrays .......................................................................................................................... 204 Collections - ArrayList ................................................................................................ 205 Generic List – preferred .............................................................................................. 206

Working with ArrayList .................................................................................................... 207

Arraylist and random numbers ........................................................................................ 209

Work out General Depreciation rates on computers....................................................... 210

Calculator using words – simple array ............................................................................ 211

Scrabble Dictionary – using lists ..................................................................................... 213

Advanced Scrabble Incremental Search ........................................................................ 216

Scrabble Exercise - using a Hash table .......................................................................... 218

Page 4: Intro to VB 7 March 2013

8 March 2013 Introduction to VB.Net 2012

Page 4 Contact Stuffucanuse.com for more resources and files for this manual

Permutations and Scrabble finder - incomplete .............................................................. 221

33. Sorting Socks project ................................................................................................ 222

34. The T shirt algorithm ................................................................................................. 223

35. Search and Sort Algorithms ....................................................................................... 225 Bubble Sort ..................................................................................................................... 225

Sort a list of words using Bubble sort ......................................................................... 227 Selection Sort .................................................................................................................. 228

Sequential Searching ...................................................................................................... 231

36. Advanced Search and Sort Algorithms ...................................................................... 233 Making a sequential search faster: self-organizing data ................................................ 233

QuickSort Algorithm – Divide and conquer ..................................................................... 237

37. Stack and the Heap ................................................................................................... 242

38. Stack and Queue – not done ..................................................................................... 243

39. Delegates – to do ...................................................................................................... 243

40. Func and Lambda ..................................................................................................... 243

41. Unit Testing – to do ................................................................................................... 244

42. Recursion - incomplete .............................................................................................. 244

43. Overloaded Methods ................................................................................................. 246

ADO.Net 4 and SQL ........................................................................................................... 251

44. TSQL Cheat Sheet .................................................................................................... 251

String Functions .......................................................................................................... 251 Common Functions ..................................................................................................... 251 Date Functions ............................................................................................................ 251 Operators Allowed in the WHERE Clause .................................................................. 251 Logical processing order of select .............................................................................. 251 CTES - Common Table Expressions .......................................................................... 252 Recursive CTEs .......................................................................................................... 252 Over and partition by................................................................................................... 252 Create a Stored Procedure ......................................................................................... 252 Create a Trigger .......................................................................................................... 252

Introduction ..................................................................................................................... 253

How it works ................................................................................................................ 255 DataReader ................................................................................................................. 256

Accessing Data using ADO.NET overview ..................................................................... 256

DataSet ....................................................................................................................... 257 DataGridView .............................................................................................................. 257 BindingSource ............................................................................................................. 257 BindingNavigator ......................................................................................................... 257 TableAdapter .............................................................................................................. 258 Data Binding ............................................................................................................... 258 ADO.NET Namespaces .............................................................................................. 258

Creating a Data Connection using the Wizard ................................................................ 259

The code behind the program to date......................................................................... 262 How to use the Dataset Designer ................................................................................... 263

Text Boxes - Formatting and Advanced Binding ............................................................ 264

Using a DataGrid to create a Master/Detail form ............................................................ 265

Creating a Parameterized Query .................................................................................... 267

Creating Queries in the Table Adapter ........................................................................... 270

Return a single value from the Database ....................................................................... 273

Using the Query Builder .................................................................................................. 275

45. Practical – Creating queries with the Cars Database ................................................. 278

46. Using manual Connections ........................................................................................ 280

Setting up SQL Server .................................................................................................... 280

When you cannot add a Database.................................................................................. 282

How to restore administrator access to a SQL server .................................................... 282

Loading in your Golf Database ....................................................................................... 284

Run a Query in SQL Express .......................................................................................... 287

Page 5: Intro to VB 7 March 2013

8 March 2013 Introduction to VB.Net 2012

Page 5 Contact Stuffucanuse.com for more resources and files for this manual

Creating an SQL Connection .......................................................................................... 288

Connect using SqlConnection Class .......................................................................... 288 Opening and Closing the Connection ......................................................................... 289

Display data in a ListView ............................................................................................... 291

Returning Scalar (single) value ...................................................................................... 292

Insert Command.............................................................................................................. 293

Optimising your code by using Sub Routines ................................................................. 294

Update Command ........................................................................................................... 297

Delete Command ............................................................................................................ 298

Inserting Data into your database ................................................................................... 299

47. Using Parameters ..................................................................................................... 300 Golf using parameters................................................................................................. 301

48. Golf Exercise using SQL ........................................................................................... 302

49. The SQL Data Adapter .............................................................................................. 303

The SelectCommand Property – SQL String .................................................................. 303

The SelectCommand Property – Stored Procedure ....................................................... 304

Calling the Stored procedure from your code ................................................................. 305

50. Music Database in SQL Management Studio -Relational Database .......................... 306 Primary Key / Foreign Key relationships ......................................................................... 307

Setting the Primary key / Foreign Key Relationships...................................................... 308

Creating Database Views – Queries ............................................................................... 311

51. Music Database in Visual Studio ............................................................................... 315 Using a Datagridview ...................................................................................................... 315

Using Views in the Form ................................................................................................. 316

Fill the Listbox from the Database .................................................................................. 316

52. Linking DataGridViews to each other ........................................................................ 317

DataGridView Click Event ............................................................................................... 318

Resizing Columns to fit contents ................................................................................ 320 Passing data from a DataTable to text boxes for Updating ............................................ 321

INSERT new Data using Parameters ......................................................................... 322 DELETE Data using Parameters ................................................................................ 323

Page 6: Intro to VB 7 March 2013

8 March 2013 Introduction to VB.Net 2012

Page 6 Contact Stuffucanuse.com for more resources and files for this manual

Cheat Sheet for VB.net

Namespace

Imports Namespace

Data Types

Boolean,Byte,Char,DateTime,Decimal,Double,Int16,Int32,Int64,Integer, Long, Object, Short,Single,String,IntPtr,UInteger,UintPtr

Variable Declaration

Dim | Public | Private <variable_name> As <type>

Type Declaration

Dim | Public <variable><suffix>

Suffixes

% -Integer. $ - String, @ - Decimal, & - Long, # - Double, ! - Single

Arrays

Dim <arrayname>(<MaxIndexVal>) As <type> Dim <arrayname>(<LowerBound> To <UpperBound>) As <type>

Initialize Array

Dim <arrayname>() As <type> = {<value1>, <value2>, ... , <valueN>}

Change Size of Array

ReDim <arrayname>(<MaxIndexVal>)

Comments

'Comment text 'No multi-line comments at this time

XML Comments

Press the ' (apostrophe) key thrice. Line Continuation strtext = “To break a long string across multiple lines, “ & _ “end the string, add the line continuation character “ & _ “and continue the string on the next line.”

Arithmetic Operators

+ (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus)

String Concatenation

+, &

Relational Operators

< (Less Than), <= (Less Than or Equal To),> (Greater Than),>= (Greater Than or Equal To),= (Equal To),<> (Not Equal To)

Logical Operators

OR, NOT, AND, AndAlso, OrElse, Xor

String Manipulation

.Substring(<start>,[<length>])

.Trim() <trims from beginning & end of string> .TrimEnd([<char array>]) .TrimStart([char array]) .ToLower() <to lower case> .ToUpper() <to upper case> .Replace(<find>,<replace>) .Equals(<expression>) <6 available overloads> .EndsWith .Concat .Contains(<string>) .Clone .Join(<seperator>,<value>,[<count>]) .Compare(<string1>,<string2>,[<ignore case>]) <7 overloads available> .Copy(<string>) .Split .IndexOf .Substring

VB6 to VB.net

Len = .Length Mid = .SubString Replace = .Replace InStr = .IndexOf UCase = .ToUpper LCase = .ToLower Split = .Split Join = .Join

Page 7: Intro to VB 7 March 2013

8 March 2013 Introduction to VB.Net 2012

Page 7 Contact Stuffucanuse.com for more resources and files for this manual

If Else If(<expression>) Then <statement 1> Else <statement 2> End If Inline If variable = IIf( condition, value_if_false, value_if_true )

For Loop For <initialize> (Relational Operator) <condition> <statement> Next

For Each Loop

For Each <variable> In <object> [Exit For] <statements> [Continue For] <statements> Next

While Loop While <expression> <statement> End While

Do-While Loop

Do <statement> Loop While <expression>

Select Case Statement Select Case <expression> Case <expression1>: <statement sequence 1> Case <expression2>

<statement sequence 2> Case <expressionN> <statement sequence N-1> Case Else <statement sequence N> End Select

Function Structure <Private, Public> <Function_Name>([Parameters]) body of the function End Function

Class Structure Public Class <Class_Name> body of class End Class

Public 'method_prototypes 'data_attributes Private 'method_prototypes 'data_attributes Friend 'method_prototypes Shared 'method_prototypes 'data_attributes

Error Handling

Try <statements that may cause an error> Catch <statements to use when an error occurs> Finally <statements to use no matter what happens> End Try

Links to interesting sites and articles http://www.reddit.com/r/learnprogramming/comments/17mwsb/can_a_professional_programmer_explain_the_tho

ught/

http://www.reddit.com/r/learnprogramming/comments/17t5g9/what_skills_do_you_think_all_beginner_programme

rs/

http://www.theatlantic.com/technology/print/2011/06/how-i-failed-failed-and-finally-succeeded-at-learning-how-to-

code/239855/

http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-

and-programming-fall-2008/video-lectures/

Computer Science Teaching videos - http://teachingtree.co/

Page 8: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 8 2012

Microsoft Exam 98-361: Software Development

Fundamentals This exam measures your ability to accomplish the technical tasks listed below. The

percentages indicate the relative weight of each major topic area on the exam. The higher the

percentage, the more questions you are likely to see on that content area on the exam.

The information after “This objective may include but is not limited to” is intended to further

define or scope the objective by describing the types of skills and topics that may be tested for

the objective. However, it is not an exhaustive list of skills and topics that could be included

on the exam for a given skill area. You may be tested on other skills and topics related to the

objective that are not explicitly listed here.

Understanding Core Programming (18 percent)

Understand computer storage and data types.

This objective may include but is not limited to: how a computer stores programs and the

instructions in computer memory; memory stacks and heaps; memory size requirements

for the various data storage types; numeric data and textual data

Understand computer decision structures.

This objective may include but is not limited to: various decision structures used in all

computer programming languages; If decision structures; multiple decision structures

such as If…Else and switch/Select Case; reading flowcharts; decision tables; evaluating

expressions

Identify the appropriate method for handling repetition.

This objective may include but is not limited to: For loops, While loops, Do..While loops,

and recursion

Understand error handling.

This objective may include but is not limited to: structured exception handling

Understanding Object-Oriented Programming (19 percent)

Understand the fundamentals of classes.

This objective may include but is not limited to: properties, methods, events, and

constructors; how to create a class; how to use classes in code

Understand inheritance.

This objective may include but is not limited to: inheriting the functionality of a base class

into a derived class

Understand polymorphism.

This objective may include but is not limited to: extending the functionality in a class after

inheriting from a base class; overriding methods in the derived class.

Page 9: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 9 2012

Understand encapsulation.

This objective may include but is not limited to: creating classes that hide their

implementation details while still allowing access to the required functionality through the

interface; access modifiers

Understanding General Software Development (14 percent)

Understand application life cycle management.

This objective may include but is not limited to: phases of application life cycle

management; software testing

Interpret application specifications.

This objective may include but is not limited to: reading application specifications and

translating them into prototypes, code, and components

Understand algorithms and data structures.

This objective may include but is not limited to: arrays, stacks, queues, linked lists, and

sorting algorithms; performance implications of various data structures; choosing the right

data structure

Understanding Web Applications (20 percent)

Understand Web page development.

This objective may include but is not limited to: HTML, Cascading Style Sheets (CSS),

JavaScript

Understand Microsoft ASP.NET Web application development.

This objective may include but is not limited to: page life cycle; event model; state

management; client-side vs. server-side programming

Understand Web hosting.

This objective may include but is not limited to: creating virtual directories and Web sites;

deploying Web applications; understanding the role of Internet Information Services

Understand Web services.

This objective may include but is not limited to: Web services that will be consumed by

client applications; accessing Web services from a client application; SOAP and Web

Service Definition Language (WSDL)

Understanding Desktop Applications (12 percent)

Understand Windows Forms applications.

This objective may include but is not limited to: Windows Forms event model; visual

inheritance; UI design; use of Multiple Document Interface (MDI) and Single Document

Interface [and here] (SDI) applications

Page 10: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 10 2012

Understand console-based applications.

This objective may include but is not limited to: characteristics and capabilities of

console-based applications

Understand Windows Services.

This objective may include but is not limited to: characteristics and capabilities of

Windows Services

Understanding Databases (17 percent)

Understand relational database management systems.

o This objective may include but is not limited to: characteristics and capabilities

of database products; database design; Entity Relationship Diagrams (ERDs);

normalization concepts

Understand database query methods.

This objective may include but is not limited to: structured query language (SQL),

creating and accessing stored procedures, updating data and selecting data

Understand database connection methods.

This objective may include but is not limited to: connecting to various types of data stores

such as flat file; XML file; in-memory object; resource optimization

Learning Plan for Software Development Fundamentals (Exam 98-361)

This learning plan is intended to help students gain the foundational knowledge they need to

begin building a software development career. By following the steps in this learning plan,

students will gain an understanding of:

- Core programming concepts, such as computer storage and data types, decision structures,

and error handling

- Object oriented programming, including classes, inheritance, polymorphism, and

encapsulation

- General Software Development, including application life cycle management, application

specifications, algorithms and data structures

- Web Applications, including Web page development (HTML, JavaScript, and CSS),

Microsoft ASP.NET Web application development, Web hosting, and Web services

- Desktop Applications, including Windows® Forms applications, console-based applications,

and Windows Services

- Databases, including relational database management systems, database query methods, and

database connection methods

This learning plan also helps students prepare for Microsoft Exam 98-361: Software

Development Fundamentals.

Page 11: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 11 2012

Microsoft Exam 98-362: Windows Development

Fundamentals This exam measures your ability to accomplish the technical tasks listed below.The

percentages indicate the relative weight of each major topic area on the exam.The higher the

percentage, the more questions you are likely to see on that content area on the exam.

The information after “This objective may include but is not limited to” is intended to further

define or scope the objective by describing the types of skills and topics that may be tested for

the objective. However, it is not an exhaustive list of skills and topics that could be included

on the exam for a given skill area. You may be tested on other skills and topics related to the

objective that are not explicitly listed here.

Understanding Windows Programming Basics

Identify Windows application types.

This objective may include but is not limited to: Windows Forms, Windows Presentation

Foundation (WPF), Windows Services, and Win32 applications

Implement user interface design.

This objective may include but is not limited to: core user interface design principles for

creating graphical-based applications

Create Windows-based applications by using Visual Studio.

This objective may include but is not limited to: project types, importance of the various

aspects of a Windows Application project

Creating Windows Forms Applications

Create and handle events.

This objective may include but is not limited to: methods for creating events in an application;

handling events raised in an application

Understand Windows Forms inheritance.

This objective may include but is not limited to: implementing forms inheritance in

applications for visual inheritance

Understand how to create new controls and extend existing controls.

This objective may include but is not limited to: creating a new GUI control or inheriting

functionality from an existing control

Validate and implement user input.

Page 12: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 12 2012

This objective may include but is not limited to: implementing the correct user input model

based on application design and requirements; accepting keyboard and mouse input;

validating user input through GUI controls such as text boxes and dialog controls

Debug a Windows-based application.

This objective may include but is not limited to: using breakpoints and debugging

techniques to identify issues in code; debugging a Windows Services application.

Creating Windows Services Applications

Create a Windows Services application.

This objective may include but is not limited to: inheriting the ServiceBase class; writing code

in the Main method; overriding the OnStart and OnStop procedures

Install a Windows Services application.

This objective may include but is not limited to: creating installers for Windows Services;

installing services on a target computer

Accessing Data in a Windows Forms Application

Understand data access methods for a Windows Application.

This objective may include but is not limited to: connecting to a database

Understand data bound controls.

This objective may include but is not limited to: how data is bound to controls; how to display

the data in the appropriate manner; forms and WPF binding; validating databound items

Deploying a Windows Application

Understand Windows application deployment methods.

This objective may include but is not limited to: different methods of deploying Windows

applications; choosing the appropriate method for deployment

Create Windows setup and deployment projects.

This objective may include but is not limited to: creating setup projects for applications;

specifying custom actions; creating special folders; security requirements; x64 deployment

and program files location

This learning plan is intended to help students gain the foundational knowledge they need to

begin building a Windows development career by using Microsoft technologies. By following

the steps in this learning plan, students will gain the knowledge and skills required to:

- Create graphical user interface (GUI) applications that run on Windows by using Windows

Forms or Windows Presentation Foundation (WPF)

- Program and host Windows Services on a computer that runs Windows

Page 13: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 13 2012

- Access data from various sources for use in a Windows-based application and

- Deploy a Windows application to target computers

This learning plan also helps students prepare for Microsoft Exam 98-362: Windows

Development Fundamentals.

Page 14: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 14 2012

1. Structure Diagrams - Processes, Decisions and

Loops Structure Diagrams are a method of modelling and testing your code before writing it.

It provides a paper version of the processes your code will go through from Inputs to

Processes to Outputs.

Structure diagrams are used as design tools for functionally decomposing structured

programs.

Any programming structure can be reduced to combinations of three fundamental

operations: Processes, Decisions and Loops.

These combinations can be used to reduce a complicated task to smaller less

complicated ones. The smaller tasks can be divided even further into smaller groups

until they reach a level where you can proceed to create the code.

IF or Case Statement Loop, While, For Statement

Page 15: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 15 2012

Introduction to VB.net Open a new VB project

Save it with a name Lesson1, and to

a new folder on your desktop, or

wherever you want, as lesson1.

Always save a new project in a

new folder as multiple files are

saved for each project and chaos

will ensue unless you are clear

about your saving.

Set up your workspace to look like this, When you open the Toolbox press the pin to

pin it to the side. As we have a good sized screen we have the space available to

leave it open. Resize the Form window to make it easier to see.

The following list introduces the most common windows:

➤ Toolbox: The Toolbox contains reusable controls and components that

can be added to your application. These range from buttons to data connectors to customized controls that you have either purchased or developed.

➤ Design window: The Design window is where a lot of the action takes

place. This is where you will draw your user interface on your forms. This window is sometimes referred to as the Designer.

➤ Solution Explorer: The Solution Explorer window contains a

hierarchical view of your solution. A solution can contain many projects, whereas a project contains forms, classes, modules, and components that solve a particular problem.

➤ Properties: The Properties window shows what properties the selected

object makes available. Although you can set these properties in your code, sometimes it is much easier to set them while you are designing

Page 16: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 16 2012

your application (for example, drawing the controls on your form). You will notice that the File Name property has the value Form1.vb. This is the physical filename for the form’s code and layout information.

From the ToolBox in Common Controls drag on ..

1 Button - named btngo btn = button Set Text field to GO 1 listbox – named lboutput lb = listbox Set Multicolumn to true 1 label named lbloutput lbl = label Set Text field to empty – clear it Set Autosize to false Set Backcolor to your choice 1 text box – named txtinput txt = textbox Set Text field to empty Double click on the button to open the code

window.

Although this only shows the code for the Button

at present all code (at this level at least) will go in

this window.

Next we will add text, use the autocomplete every time you make an entry, then you know you won’t have any errors. So start to type below and when the word lbloutput appears press Tab. Then choose a property from the pulldown list and press tab again. IF YOU DON’T GET THE INTELLISENCE YOU ARE DOING IT WRONG Type in lbloutput.Text = "hello world" Click the green run button to see it working, then click on your button.

Things to note: The green bar down the left shows your code is working OK, the

output at the bottom gives information as to how well it runs.

Page 17: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 17 2012

Now alter it to look like this...

The first line has been commented out with a ‘ Its better to comment out code than

delete it, you never know when you need it again.

Note that lboutput.Items.Add(txtinput.Text) has two separate intellisence

selections.

Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click

' lbloutput.Text = "hello world"

lbloutput.Text = txtinput.Text

lboutput.Items.Add(txtinput.Text)

MsgBox("This is a test " & txtinput.Text) ' comment out when it gets annoying

End Sub

Run it.

Add more entries to the text box and see them list in the listbox. Listboxes are fun,

and really handy tools to use for debugging as well.

Double click on the listbox and then in the code window enter

lboutput.Items.Clear() This will clear the listbox when you click on it when it is

running

Private Sub lboutput_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lboutput.SelectedIndexChanged

lboutput.Items.Clear()

End Sub

Now for something different. We want to get the click event on the textbox, when you

first click into it with the mouse. We want this so that the existing text can be

highlighted so you don’t have to delete it out each time you want to add new text.

So click in the pulldown list at the top of the code and select txtinput

Then click in the second list and select Click. This will be the click event.

Page 18: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 18 2012

Then add in the following code with the beside it. The green text are comments.

Comments are your way to teach the future you what you are going to forget.

Private Sub txtinput_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtinput.Click

txtinput.SelectionStart = 0 ' puts the cursor at the start

txtinput.SelectionLength = txtinput.Text.Length ' selects the entire length of the text

End Sub

Run it and see what happens........

If you comment your code then you can easily find it again at a later time when you

want to use it in another program.

To this stage we have really just been setting up the program. We now have a

working form that you can enter data in on, and see results, now we can turn this into

a real program by getting into some coding.

Page 19: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 19 2012

Variables

It’s not enough to have data moving from textboxes to labels and out of the program.

You need to be able to work with data in the program. To do this you need to create

variables, storage places to hold information that you want to use.

Variables can store numbers, text, dates, and times, and they can even point to full-

fledged objects. When you declare a variable, you give it a name, and you specify

the type of data it will store.

To use a variable you first have to tell the program that it exists. This happens

automatically when you put an object, such as button on a form, but you have to do it

manually when you create a variable.

The DIM name harks back to the original versions of the BASIC language. BASIC

has always needed to know how much space to reserve for an array so it had a

command to indicate the dimensions of the array— Dim for short. Visual Basic

extends that command to all other kinds of variables as well to mean ‘‘make some

space for’’ in general.

To do this it follows the following format

Dimension Variable Name as Variable Type and give it a value

Dim myVariable As String = "StringValue"

This means that myVariable will hold StringValue. But you can change what is in

myVariable to be something completely different as long as its just a string.

You can make variables that don’t change, for when you want to add a value into

your program that is constant.

Const cnstMyConstant As String = "The very long string"

Visual Basic is kind enough to let you use simple data types without initializing them.

Numbers are automatically initialized to 0, and strings are initialized to an empty

string ("").

Page 20: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 20 2012

Data Types

Data Types define the type of data that a variable can store. Some variables store

numbers, others store names.

Every .NET language uses the same variable data types. Different languages may

provide slightly different names (for example, a VB Integer is the same as a C# int),

but the CLR makes no distinction—in fact, they are just two different names for the

same base data type (in this case, it’s System.Int32).

This design allows for deep language integration. Because languages share the

same core data types, you can easily use objects written in one .NET language in an

application written in another .NET language. No data type conversions are required.

All .NET languages have the same data types because they all adhere to the

common type system (CTS), a Microsoft-designed ECMA standard that sets the

ground rules that all .NET languages must follow when dealing with data.

The built-in VB.NET type aliases and their equivalent .NET Framework types follow:

.NET Type Name

VB Name

C# Name

Contains

Byte

Byte

byte

An integer from 0 to 255.

Int16 Short short An integer from −32,768 to 32,767.

Int32 Integer int An integer from −2,147,483,648 to 2,147,483,647.

Int64 Long long An integer from about −9.2e18 to 9.2e18.

Single Single float A single-precision floating-point number from approximately −3.4e38 to

3.4e38 (for big numbers) or −1.5e-45 to 1.5e-45 (for small fractional

numbers).

Double Double double A double-precision floating-point number from approximately −1.8e308 to

1.8e308 (for big numbers) or −5.0e-324 to 5.0e-324 (for small fractional

numbers).

Decimal Decimal decimal A 128-bit fixed-point fractional number that supports up to 28 significant

digits.

Char Char char A single Unicode character.

String String string A variable-length series of Unicode characters.

Boolean Boolean bool A True or False value.

DateTime Date * Represents any date and time from 12:00:00 AM on January 1 of year

1 in the Gregorian calendar, to

11:59:59 PM on December 31 of the year 9999. Time values can resolve

values to 100-nanosecond increments. Internally, this data type is stored as a

64-bit integer.

TimeSpan * * Represents a period of time, as in ten seconds or three days. The

smallest possible interval is 1 tick (100 nanoseconds).

Object Object object The ultimate base class of all .NET types. Can contain any data type or

object. (You’ll take a much closer look at objects in Chapter 3.)

Page 21: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 21 2012

Try it in your project, just use your name. Variables can be defined anywhere but in

this case defining it at the top means it can be used everywhere. shows the

changed lines.

Under Public Class Form1 add the following. Use your OWN NAME!

Public Class Form1

Dim strmyname As String = "Gary"

Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click

' lbloutput.Text = "hello world"

' lbloutput.Text = txtinput.Text

lboutput.Items.Add(txtinput.Text)

lbloutput.Text = strmyname

MsgBox("Hello " & strmyname & " boy are you lucky to learn VB.net") ' comment out when it gets annoying

End Sub

Add and change the following – use your age.

Dim myage As Integer = 47

MsgBox("Hello " & myname & " your age is " & myage) ' comment out when it gets annoying

Variables can be changed easily do this

Dim strmyname As String = "Gary"

Dim intmyage As Integer = 47

Dim intyear As Integer = 2012

intmyage = intmyage + 1

intyear = intyear + 1

lboutput.Items.Add(intmyage & " in " & intyear)

Your code to date:

Public Class Form1

Dim strmyname As String = "Gary"

Dim intmyage As Integer = 47

Dim intyear As Integer = 2012

Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click

' lbloutput.Text = "hello world"

' lbloutput.Text = txtinput.Text

intmyage = intmyage + 1

intyear = intyear + 1

lboutput.Items.Add(intmyage & " in " & intyear)

lbloutput.Text = strmyname

MsgBox("Hello " & strmyname & " your age is " & intmyage) ' comment out when it gets annoying

End Sub

Page 22: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 22 2012

Detecting Keypress events Choose a KeyDown event and add the following

Private Sub txtinput_KeyDown(sender As Object, e As KeyEventArgs) Handles txtinput.KeyDown

If e.KeyCode = Keys.Return Then

lblOutput.Text = txtinput.Text

MsgBox("This is some text")

'Put whatever you want here.

End If

End Sub

Structure Diagram for part of lesson 1

Operators There are various types of operators in Visual Basic. Here are the Arithmetic

operators (for example, the expression 5 + 4 yields a value of 9):

Operator Description Example Result

+ Addition 1 + 1 2

− Subtraction 5 − 2 3

* Multiplication 2 * 5 10

/ Division 5 / 2 2.5

Mod Gets the remainder left after integer

division

7 Mod 3 1

Here are the Comparison operators (these values yield true or false values—for

example, 5 > 4 yields a value of True):

< (Less than) True if operand1 is less than operand2

<= (Less than or equal to)

True if operand1 is less than or equal to operand2

> (Greater than) True if operand1 is greater than operand2

Page 23: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 23 2012

>= (Greater than or equal to)

True if operand1 is greater than or equal to operand2

= (Equal to) True if operand1 equals operand2

<> (Not equal to) True if operand1 is not equal to operand2

Is True if two object references refer to the same object

Like Performs string pattern matching

When dealing with strings, you can use the concatenation operator (&), which joins

two strings.

MyName = FirstName & " " & LastName

The addition operator (+) can also be used to join strings, but it’s generally clearer

and safer to use the concatenation operator. The concatenation operator (&)

automatically attempts to convert both variables in the expression to the string data

type, if they are not already strings.

In addition, VB also provides special shorthand assignment operators. Here are a

few examples:

Add 10 to MyValue (the same as MyValue = MyValue + 10). MyValue += 10

Multiply MyValue by 3 (the same as MyValue = MyValue * 3). MyValue *= 3

Divide MyValue by 12 (the same as MyValue = MyValue / 12). MyValue /= 12

Advanced math with System.Math

In the past, every language has had its own set of keywords for common math operations such

as rounding and trigonometry. In .NET languages, many of these keywords remain.

However, you can also use a centralized System.Math class that’s part of the .NET

Framework.

This has the pleasant side effect of ensuring that the code you use to perform mathematical

operations can easily be translated into equivalent statements in any .NET language with

minimal fuss.

To use the math operations, you invoke the methods of the Math class. These methods are

shared, which means they are always available and ready to use.

The following table shows some sample calculations that you can perform with the Math

class:

Dim MyValue As Double

MyValue = Math.Sqrt(81) MyValue = 9.0

MyValue = Math.Round(42.889, 2) MyValue = 42.89

MyValue = Math.Abs(−10) MyValue = 10.0 Absolute makes a

Page 24: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 24 2012

negative a positive

MyValue = Math.Log(24.212) MyValue = 3.18.. (and so on)

MyValue = Math.PI MyValue = 3.14.. (and so on)

The features of the Math class are too numerous to list here in their entirety. The preceding

examples show some common numeric operations. For more information about the

trigonometric and logarithmic functions that are available, refer to the reference information

for the Math class on Microsoft’s MSDN website

These are the Logical/Bitwise operators, where bitwise means working bit by bit with

numerical values.

These types of operators can work on logical values (for example, if blnValue1 is set

to True and blnValue2 is set to False, then blnValue1 Or blnValue2 returns a value

of True) or numbers for bitwise operations, which work on their operands bit by bit

(for example, if intValue1 is set to 2 and intValue2 is set to 1, then intValue1 Or

intValue2 yields 3):

And Performs an And operation (for logical operations: True if both operands are True, False otherwise; the same for bit-by-bit operations where you treat 0 as False and 1 as True).

Not Reverses the logical value of its operand, from True to False and False to True, for bitwise operations, turns 0 into 1 and 1 into 0.

Or Operator performs an Or operation (for logical operations: True if either operand is True, False otherwise; the same for bit-by-bit operations where you treat 0 as False and 1 as True).

Xor Operator performs an exclusive-Or operation (for logical operations: True if either operand, but not both, is True, and False otherwise; the same for bit-by-bit operations where you treat 0 as False and 1 as True).

AndAlso Operator A "short circuited" And operator; if the first operand is False, the second operand is not tested.

OrElse Operator A "short circuited" Or operator, if the first operand is True, the second is not tested.

AddressOf

Gets the address of a procedure

GetType Gets information about a type

Following the lead of languages like Java, VB .NET supports these combination

operators.

For example, += is a combination of + and =, which means that you can write intValue1 = intValue1 + 1 as intValue1 += 1.

In a similar way, you can write intValue1 = intValue1 * 5 asintValue1 *= 5, providing an easy shortcut.

Page 25: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 25 2012

Also, in Visual Basic .NET, if the first operand of an And operator evaluates to False,

the remainder of the logical expression is not evaluated. Similarly, if the first operand

of an Or operator evaluates to True, the remainder of the logical expression is not

evaluated. This is called short-circuiting.

We will use these in the future.

Close your project.

Code Snippets tool To enter code that you will be using repetitively use the Code Snippets tool.

(However at this level it’s better for you to enter it by hand, but here is how you do it.)

In your code window click where you want the code entered, then right click and

choose Insert Snippet. Then double click on the group you want such as Code

Patterns and search for the code you want to enter.

You can also save code to the Snippets to use later.

Learning to code defensively - Refactoring your code If you want to rename (refactor) your code, such as your variables, you can do it all at

once. When you change the name click on the small icon that appears on the bottom

right and choose the option shown. This seems to bork at changing the same name

multiple times however. This is a really good tool for your programming.

Using My My is the speed dial of the dot net framework. It’s a quick way to access distinct

classes which organize a variety of functions into one of seven general areas:

My.Application, My.Computer, My.Forms, My.Resources, My.Settings, My.User, and

My.WebServices.

Eg: The name of the current user of the application

lblname.text = My.User.Name

A statement that checks if the directory exists

If My.Computer.FileSystem.DirectoryExists.("C:\files") then

A statement that creates an instance of a form and displays it. (Form1 being the

form, but your form name will show if you have one)

My.Forms.Form1.Show()

Page 26: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 26 2012

Reading a text file into the program

contents = My.Computer.FileSystem.ReadAllText("c:\mytextfile.txt")

My isn’t used much in the exercises as its platform dependant, but many exercises

could be rewritten to incorporate it. It’s a good tool that is so far unexploited. Maybe

we need to get a book on it.

Learning to code defensively - Some coding ideas

Write code for clarity, not brevity

Whenever you can choose between concise (but potentially confusing) code and

clear (but potentially tedious) code, use code that reads as intended, even if it’s less

elegant. For example, split complex arithmetic operations into a series of separate

statements to make the logic clearer.

Think about who might read your code. It might require maintenance work by a junior

coder, and if he can’t understand the logic, then he’s bound to make mistakes.

Complicated constructs or unusual language tricks might prove your encyclopaedic

knowledge of operator precedence, but it really butchers code maintainability. Keep it

simple.

Don’t let anyone tinker with stuff they shouldn’t

Things that are internal should stay on the inside. Things that are private should be

kept under lock and key. Don’t display your code’s dirty laundry in public. In object-

oriented languages, prevent access to internal class data by making it private.

Keep all variables in the tightest scope necessary; don’t declare variables globally

when you don’t have to. Don’t put them at file scope when they can be function-local.

Don’t place them at function scope when they can be loop-local.

Check every return value

If a function returns a value, it does so for a reason. Check that return value. If it is an

error code, you must inspect it and handle any failure. Don’t let errors silently invade

your program; swallowing an error can lead to unpredictable behaviour.

Initialize all variables at their points of declaration

This is a clarity issue. The intent of each variable is explicit if you initialize it. It’s not

safe to rely on rules of thumb like if I don’t initialize it, I don’t care about the initial

value. The code will evolve. The uninitialized value may turn into a problem further

down the line.

Declare variables as late as possible

By doing this, you place the variable as close as possible to its use; preventing it

from confusing other parts of the code. It also clarifies the code using the variable.

You don’t have to hunt around to find the variable’s type and initialization; a nearby

declaration makes it obvious.

Don’t reuse the same temporary variable in a number of places, even if each use is

in a logically separate area. It makes later reworking of the code awfully complicated.

Create a new variable each time—the compiler will sort out any efficiency concerns.

Page 27: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 27 2012

2. If Statements

Grades Project If Statements are one of the fundamental tools of programming, something you will

use in every project. The If block is the powerhouse of conditional logic, able to

evaluate any combination of conditions and deal with multiple and different pieces of

data. Here’s an example of an If block that features two conditions:

If MyNumber > 10 Then

' Do something.

ElseIf MyString = "hello" Then

' Do something.

Else

' Do something.

End If

An If block can have any number of conditions. If you test only a single condition, you

don’t need to include any other ElseIf or Else blocks.

Create a new project, call it Grades – IF, and remember to make a new folder.

Create a ....

Button- name btncalculate, Text Calculate

Textbox name txtgrade

Listbox name lbgrade

Label name lblgrade text = nothing

We want to calculate the grade of a mark when entered into the text box. Double

click on the button to open the code window, and then enter the following code.

REMEMBER NOT TO TYPE BUT USE THE TAB KEY

If txtgrade.Text < 50 Then

lblgrade.Text = "Fail"

lbgrade.Items.Add(txtgrade.Text & " Fail")

Else

lblgrade.Text = "Pass"

lbgrade.Items.Add(txtgrade.Text & " Pass")

End If

When you get that working add these modifications

If txtgrade.Text < 50 Then

lblgrade.Text = "Fail"

' lbgrade.Items.Add(txtgrade.Text & " Fail")

ElseIf txtgrade.Text < 60 Then

lblgrade.Text = "C"

Page 28: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 28 2012

' lbgrade.Items.Add(txtgrade.Text & " Pass")

ElseIf txtgrade.Text < 70 Then

lblgrade.Text = "B"

End If

I know this isn’t a full program we will finish it later.

Lets create a variable to hold the grade and use that instead of txtgrade.text. It’s far

tidier. Note that we can add the listbox to the very end instead of after each IF

statement.

Dim grade As Integer

Private Sub btncaclulate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncaclulate.Click

grade = txtgrade.Text

If grade < 50 Then

lblgrade.Text = "Fail"

ElseIf grade < 60 Then

lblgrade.Text = "C"

ElseIf grade < 70 Then

lblgrade.Text = "B"

End If

lbgrade.Items.Add(grade & " " & lblgrade.Text)

End Sub

End Class

Now finish the Grade calculator off with E D C B A

rankings to 100.

Exercise: Add a way so that the person’s name appears in the list box beside their grade ie: John Smith 72 B. That would be a practical way to show results.

Error checking exercises - build these into your program.

How can you stop people from entering a number over 100 with an IF?

How can you stop people clicking the button without any number in the field with an IF?

Page 29: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 29 2012

Learning to code defensively -Use Try / Catch for error

Checking Defensive programming is careful, guarded programming. To construct reliable

software, we design every component in the system so that it protects itself as much

as possible. In this case Try catch will halt any errors, but it’s not ideal. Sometimes

you WANT to see the errors that are generated so that you can fix them properly by

using techniques such as limiting input to text or numbers (as seen later)

Use Try / Catch to prevent errors (its a pretty rough but practical tool that I always

use). It’s also great for bug checking as well.

Anything between TRY and CATCH is run

and if it returns an error you can show it in

a message box after the CATCH and

before the END TRY. Put whatever error

message you want between the Catch

and End Try You can break up your code

with Try/Catch all through it checking

each part. Try it and see.

Private Sub btncaclulate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncaclulate.Click

Try

grade = txtgrade.Text

If grade < 50 Then

lblgrade.Text = "Fail"

ElseIf grade < 60 Then

lblgrade.Text = "C"

ElseIf grade < 70 Then

lblgrade.Text = "B"

End If

lbgrade.Items.Add(grade & " " & lblgrade.Text)

Catch

MsgBox("Please use a number " & txtgrade.Text & " is wrong")

txtgrade.Text = ""

End Try

End Sub

Catching with error messages – just for reference

Dim Friendly As Boolean = True

Dim myVariable As Form

Try

myVariable.Show()

Catch ex As NullReferenceException When Friendly = False

MsgBox("Are you stupid? myVariable can't be empty")

Catch ex As NullReferenceException

MsgBox("myVariable mustn't be empty")

Page 30: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 30 2012

Catch ex As Exception

MsgBox(ex.Message)

Finally

MsgBox("We're done")

End Try

Page 31: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 31 2012

3. Select Case Statement Hate making heaps of IF statements?

Tied in with an IF statement is this totally practical way of using multiple IF’s called

Select Case. With Case you can more finely set the parameters you want. In this

case all numbers between 0 and 50 and then 51 to 100.

Create another button call it btncase and use the Case statement to rebuild your IF

statements in a much tidier format. A simple example of Case is below.

Private Sub btncase_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncase.Click

grade = txtgrade.Text

Select Case grade

Case 0 To 50

lblgrade.Text = "Fail"

Case 51 To 100

lblgrade.Text = "Pass"

End Select

End Sub

When you get that working use Case to make the full ABCDE grading system.

Case is one of those really handy tools that you can easily use. We will return to this

button later.

Finding out the average of grades entered. Using some simple calculations we can generate an average score of the numbers

entered into your program.

Create a new label called lblaverage. Create two variables gradeaverage and count

as Integers. Give count a start number of 0.

Dim intgrade As Integer

Dim snggradeaverage As Single

Dim intcount As Integer = 0

Private Sub btncaclulate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncaclulate.Click

Try

intgrade = txtgrade.Text

snggradeaverage += intgrade ' add grade to the total

intcount += 1 ' count up by 1 each time the button pressed

lblaverage.Text = "Average " & snggradeaverage / intcount

This line gradeaverage += grade adds the score in the grade to the grade average

variable each time you click the button.

It can also be written as gradeaverage = gradeaverage + grade

Page 32: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 32 2012

This line count += 1 makes the counter increase by 1 each time the button is

clicked. This is a really practical piece of code that you use often to count stuff, such

as in loops.

You can also use count = count + 1 which is the old way of writing it

This next line divides the gradeaverage by how many clicks to work out an average

and is then passed to the label lblaverage.Text = "Average " & gradeaverage /

count

Exercise: In your listbox, add a count so that you can see how many entries you have made, such as the pic shows on the right.

Max and Min using IF We can calculate the max and the min of the data being entered easily with if

statements.

Create 2 labels lblmax and lblmin then add the

code below to your other variables

Dim intmax As Integer

Dim intmin As Integer

Private Sub btncaclulate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncaclulate.Click

Try

If count = 1 Then

intmax = grade ' only the first time

Page 33: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 33 2012

intmin = grade

End If

If grade > intmax Then ' if the grade is bigger than the number

intmax = grade ' make the number the grade

End If

lblmax.Text = "Max number " & intmax ' show

Exercise: Once you have made that then create the code for the min number and pass it to the label.

Page 34: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 34 2012

Learning to code defensively - Catching if just Numeric or

Text entered There are a number of ways to catch if text or numbers are entered, but this is by far

the easiest. IsNumeric returns True or False, So put it in an IF statement to check

your input as you type into the text box. Use it in txtgrade.TextChanged which you

open by just double clicking on the Text box.

Private Sub txtgrade_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtgrade.TextChanged

If Not IsNumeric(txtgrade.Text) Then

MessageBox.Show("Please enter a Number")

End If

End Sub

Close your program

Using Keypress to allow only numbers (Advanced) This is a great way to isolate numbers so they only enter the text box and

also to use string operations with e.KeyChar. There are two ways to achieve this, the

first shows more ways of coding, the second, is more condensed. Both are good to

use to add to your projects.

Private Sub txtdatain_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtdatain.KeyPress

Dim strthis_ch As String ' holds the current character

Dim strtxtcopy As String ' a copy of the textbox text

Dim strbackspace As String = Chr(8) ' backspace character for comparison in case block

strtxtcopy = txtdatain.Text' get the current text

strthis_ch = e.KeyChar' get the current char

e.KeyChar = ""' eliminate the character from the keychar buffer

Select Case strthis_ch ' make sure it is digit or dot

Page 35: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 35 2012

Case "0" To "9", "."

strtxtcopy &= strthis_ch' concatenate the character to text

txtdatain.Text = strtxtcopy' replace old with new

txtdatain.SelectionStart = txtdatain.Text.Length' ensure cursor positioned correctly

e.Handled = True' stop keychar being processed by system

Case strbackspace Then' backspace detected so remove last character

If strtxtcopy <> ""

strtxtcopy = strtxtcopy.Substring(0, strtxtcopy.Length - 1)

txtdatain.Text = strtxtcopy' replace text

txtdatain.SelectionStart = txtdatain.Text.Length' move cursor

e.Handled = True' stop beep by stopping keychar handler

End If

Case Else

' any other key just process in the normal way because there's nothing to process, we'll get a beep which is what we want!

e.KeyChar = ""

End Select

End Sub

Here is the same code at a smaller scale which is nicer but harder to follow.

If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> ControlChars.Back AndAlso e.KeyChar <> "." Then

'cancel keys

e.Handled = True

End If

Page 36: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 36 2012

4. IF with AND and OR – Does the car run? We can have multiple criteria in the IF statement by using AND and OR in the

Condition. For example: To make a car run you need a battery and petrol and a key.

This can be seen in one If statement as the following code If strbattery = "battery"

And strkey = "key" And strpetrol = "petrol" Then …

Private Sub btnstart_Click(sender As Object, e As EventArgs) Handles btnstart.Click

'Define 3 variables to hold the conditions

Dim strbattery, strkey, strpetrol As String

'Pass the data in the textboxes to the variables

strbattery = txtbattery.Text

strkey = txtkey.Text

strpetrol = txtpetrol.Text

'If statement with AND to make the car go

If strbattery = "battery" And strkey = "key" And strpetrol = "petrol" Then

MsgBox("Varoom! Off we go!")

Else

MsgBox("Not going anywhere ...")

End If

End Sub

However if the person types in Petrol

instead of petrol or Yes, then it doesn’t

work

So add some OR statements in to meet

the criteria for other options.

The battery field is already completed

for you.

If (strbattery = "battery" Or strbattery = "Battery" Or strbattery = "yes") And (strkey = "key" And strpetrol = "petrol") Then

Page 37: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 37 2012

This is pretty tedious having to type in the words all the time lets just use a Checkbox

for each of the three conditions.

Add three checkboxes and name them chkbattery, chkfuel, chkkey.

If they are ticked then their checked value is true chkfuel.Checked = True

Create a new start button to hold the code below.

Private Sub btnStartCheck_Click(sender As Object, e As EventArgs) Handles btnStartCheck.Click

If chkfuel.Checked = True And chkbattery.Checked = True And chkKey.Checked = True Then

MsgBox("Varoom! Off we go!")

Else

MsgBox("Not going anywhere ...")

End If

End Sub

Page 38: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 38 2012

Calculator Project Create a new project. Call it calculator.

Buttons = Btnplus, btnminus, btndivide,

btnsubtract, btnequals Use your intelligence to

work out the text on them

Text Boxes = txtnum1, txtnum2

Listbox – lbanswer

Label = lblanswer

Create 3 variables to hold the numbers. We will use Long as it gives longer numbers

and decimals.

Dim lngnum1 as long

Dim lngnum2 as long

Dim lnganswer as long

Add the following code under the Multiple button (Double click on the Multiple button

to add the code)

(Note these should be Double, not Long, Long only holds whole numbers not fractions. So change your variables to dblnum1 as Double)

Public Class Form1

Dim lngnum1 As Long

Dim lngnum2 As Long

Dim lnganswer As Long

Private Sub btnmultiply_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnmultiply.Click

lngnum1 = txtnum1.Text

lngnum2 = txtnum2.Text

lnganswer = lngnum1 * lngnum2

lblanswer.Text = lnganswer

lbanswer.Items.Add(lngnum1 & " X " & lngnum2 & " = " & lnganswer)

End Sub

End Class

Try and see if it works.

If so, then use the code to make the next 3 buttons as well.

Create a new label, don’t worry about the name and in it Put the title of your

calculator and format it to look nice. Look at the properties of FONT and

FORECOLOR to make it look nice.

Page 39: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 39 2012

Temperature Converter program Create a temperature converter. You enter a number as either Celsius or Fahrenheit

and the program converts from one to the other.

Centigrade = (5.0/9.0) * (Fahrenheit – 32.0) Fahrenheit = Centigrade * (9 / 5) + 32

Create images that appear when the water is boiling, or freezing.

Here is the simple code I created with a couple of radio buttons However use your

own style and code.

Private Sub btnsubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsubmit.Click

Dim sngfah As Single

Dim sngcel As Single

sngfah = (txttemp.Text - 32) * 5 / 9

sngcel = txttemp.Text * (9 / 5) + 32

If RadioButton1.Checked Then

lbloutput.Text = txttemp.Text & " Fahrenheit is equal to " & sngfah & " Celsius"

ElseIf RadioButton2.Checked Then

lbloutput.Text = txttemp.Text & " Celsius is equal to " & sngcel & " Fahrenheit"

End If

End Sub

Page 40: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 40 2012

5. Sender

Using Sender exercises

In VB.NET, there are two major upgrades that make VB.NET more advanced

1. The "Handles" clause controls whether the system calls the subroutine, not the name.

2. The sender and e parameters are passed to the subroutine.

Let's look at a simple example to see the difference that parameters make in VB.NET.

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

End Sub

Event subroutines always receive a "sender" object and a system EventArgs parameter "e".

EventArgs is the base class for classes containing event data.

What can you do with these parameters? Suppose you want to find whether a string, perhaps

something you entered into a Textbox, exists in any one of a collection of other Textboxes

when you click on one.

First you have to make a ‘fake’ text box to hold the data

Dim myTextbox As TextBox

Then send the data from which ever text box you clicked to it

myTextbox = sender

The sender parameter will reveal which Textbox was clicked. This code works on the data

entry into the text box itself.

Txtinput

Txtinput2

Public Class Form1

Dim strtext As String = "test"

Private Sub FindIt(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtinput.Enter, txtinput2.Enter

Dim myTextbox As TextBox

myTextbox = sender

Dim IndexChar As Integer = myTextbox.Text.IndexOf(strtext)

If IndexChar = -1 Then

Me.Text = "Not Found"

Else

Me.Text = "Found it!"

Page 41: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 41 2012

End If

Here is a way to delete a line that was clicked in any of six specified lists. Using sender, it

was really quite simple:

Listbox1

Listbox2

Private Sub ListBox_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.Click, ListBox2.Click

Dim myListBox As New ListBox

myListBox = sender

myListBox.Items.RemoveAt(myListBox.SelectedIndex)

End Sub

To test whether Button1 or Button2 has been clicked, you have to turn sender into an actual

Button object and then test a property of that object. Text is usually used, but you could test a

value in Tag or even the Location property.

Btnrun

Btnfind

Private Sub Button_check(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnrun.Click, btnfind.Click

Dim button_check As Button

Button_check = sender

If button_check.Text = "Find" Then

Me.Text = "Found it!"

Else

Me.Text = "Not that one"

End If

End Sub

Project: Open the Calculator Project and rewrite it so that all events run from a single Button Click Sub. Use Sender.Tag, or Sender.Text, Ifs, and Select Case If you make the Tag the symbol and you can use it in the output as well.

Page 42: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 42 2012

Using Sender to determine what type of control you clicked Often in your code procedures, you may need to determine what type of control your

code has accessed.

For instance, you may want to alter the text on every command button on a form. Or

you may want to change the properties for several different controls. In such

instances, you have several ways to test for a control type.

So what does this do?

You can have multiple buttons running from the same click event and using the

SENDER you can differentiate which button you are accessing.

In this case its looking for the text that is on the button you click - sender.Text. Many

times you could use sender.Tag and put a value in that to be used later.

The Control gives you control over the properties of the control. EG: if you want to

make all the text boxes invisible then you can just set the properties of the textbox to

false using c.Visible = False

Using c you can change many parts of the control, its a really good trick. Add the

below into the main code.

If TypeOf c Is TextBox Then

'and add their text to the listbox

c.Visible = False

The most efficient and fastest method of identifying the control used is with the

TypeOf operator.

This keyword must appear in an If...Then statement, like so:

If TypeOf ctl Is CommandButton Then

'Do something

End If

Create the form and the code below under the first button (Button1).

Page 43: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 43 2012

The main code to add to your form.

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

'all three buttons run off the same click event just separated by a comma

Dim c As Control

ListBox1.Items.Clear() 'clear the list box

For Each c In Me.Controls 'looping through each control

'what is the text of the sender - in this case the button

Select Case sender.Text

Case "Text Contents" 'if the button text is

'then look for controls which are text boxes

If TypeOf c Is TextBox Then

'and add their text to the listbox

ListBox1.Items.Add(c.Text)

End If

Case "Names" 'if the button has names on it

'list all the names of all the controls

ListBox1.Items.Add(c.Name)

Case "Buttons"'if the button has Buttons on it

'list all the names on just the buttons

If TypeOf c Is Button Then

ListBox1.Items.Add(c.Name)

End If

End Select

Next

End Sub

Page 44: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 44 2012

Calculator part 2 using Sender (Advanced if you want to try it – we will do this later as well) Here is another way,

which uses techniques that we will come across later such as Sender with one event

holding all radiobutton events.

Sender As System.Object holds all of the information of the radiobutton that you

click on. That can be passed to a fake radiobutton which is used in the code. Find

out more about Sender later in the manual.

Public Class Form1

Dim dblNum1 As Double = 0.0

Dim dblNum2 As Double = 0.0

Dim dblAnswer As Double = 0.0

'This passes the data from the first text box to the variable and catches if there is an error.

Private Sub txtNum1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtNum1.TextChanged

Try

dblNum1 = txtNum1.Text

Catch ex As Exception

dblNum1 = 0.0

End Try

End Sub

'This passes the data from the second text box to the variable and catches if there is an error.

Private Sub txtNum2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtNum2.TextChanged

Try

dblNum2 = txtNum2.Text

Catch ex As Exception

dblNum2 = 0.0

End Try

End Sub

'This sub holds all of the radio button code, just click on one RB and use its code to hold all the details for the other rbs.

Private Sub AllRBs(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbnAddition.CheckedChanged,

Page 45: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 45 2012

rbnDivision.CheckedChanged, rbnMultiplication.CheckedChanged, rbnSubtraction.CheckedChanged

If there is something in both text boxes then run the rest of the code

If txtNum2.Text <> "" And txtNum2.Text <> "" Then

'first make a fake radio button to hold the properties from the radiobutton you have clicked on

Dim fakeradiobutton As RadioButton

'Then pass all the properties from the rb you clicked on to the new fakerb by the Sender

fakeradiobutton = sender

'Then look at the fakerb.text to see what is on the text of the rb, it will be either + - * /

Select Case fakeradiobutton.Text

Case "+"

dblAnswer = dblNum1 + dblNum2

Case "-"

dblAnswer = dblNum1 - dblNum2

Case "/"

'There is the potential for an error here with division so wrap it in a try catch

Try

dblAnswer = dblNum1 / dblNum2

Catch ex As Exception

MessageBox.Show("Cannot divide by zero")

End Try

Case "*"

dblAnswer = dblNum1 * dblNum2

End Select

'Finally show the output on the screen

lblAnswerDisplay.Text = dblAnswer

End If

End Sub

Page 46: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 46 2012

Order a sandwich program Create the following program that allows you to select your order for a sandwich.

Page 47: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 47 2012

Rock Scissors Paper

Create a program in which you compete against the computer in a game of Rock

Scissors paper.

The heart of this program is a Select case statement that compares your choice

(Rock, Paper, Scissors) to the second persons choice.

If rbnRock.Checked Then

'Checks if the user has the "Rock" choice selected

Select Case intComputerChoice

'Selects the variable "intComputerChoice" to match cases against

Case 1 'Rock

MessageBox.Show("Your choice: Rock, Computer choice: Rock, You tied.")

Case 2 'Paper

MessageBox.Show("Your choice: Rock, Computer choice: Paper, You lost.")

Case 3 'Scissors

MessageBox.Show("Your choice: Rock, Computer choice: Scissors, You win!")

Case Else

MessageBox.Show("Error, something went wrong with the computer generated choice") 'Not nessesarily needed, just here to catch errors

End Select

You will need a random number generator to create the computers guess. Best

would be to make a manual selection where you choose both sides. Then when you

perfect the code for that replace the computer side with the random number.

'Needed for the use of Generate.Next(1, 4) to generate a random number for the computer's choice.

Dim ComputerGuess As New Random()

'This code generates a random integer between 1 and 4, but 4 is not inclusive, meaning the only possibilities are 1, 2 and 3

'1 represents Rock, 2 represents Paper, 3 represents Scissors

intComputerChoice = ComputerGuess.Next(1, 4)

Page 48: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 48 2012

Using the instructions that follow, add 3 images to your program to show the choices

of the players.

Page 49: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 49 2012

Adding a new Form or Dialog Box to show images As you can’t show images in a message box, you can instead build a custom form

and use that as a messagebox instead. Here is how…

In your project add a new form as below and name it DialogBox.vb (you can name

your form anything its just a name)

Set the Form Border Style property to Fixed

Dialog

Set the ControlBox, MinimizeBox, and MaximizeBox properties to false.

Add a label to your form as a test, name it lblMessage

Add a Button to your form, name it btnClose

In your main form you need to call the form in the following way.

First we have to create an instance of the DialogBox form that we have made so the

program know which form we are talking about, think of it as a link to that form on

your main form

Dim A New form Name as a new Form that you have already made

Dim dialogform As New DialogBox

If we have called the new form Form2 then it would be

Dim dialogform As New Form2

Or

Dim ThisCopyOfTheForm As New Form2

Now we have instantiated a copy of the form it will hold all the objects on that form

and you can easily pass data to it. This passes the words Test to the

lblmessage.text

dialogform.lblmessage.text = "Test"

Page 50: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 50 2012

To show the dialogform we use the easy .Show()

dialogform.Show()

Add a picturebox to your dialog form name it pbImageComp

Select Case intComputerChoice 'Selects the variable "intComputerChoice" to match cases against

Case 1 'Rock

pbImageComp.BackgroundImage = My.Resources.Resource1.rock

dialogform.pbImageComp.BackgroundImage = My.Resources.Resource1.rock

Case 2 'Paper

pbImageComp.BackgroundImage = My.Resources.Resource1.paper

dialogform.pbImageComp.BackgroundImage = My.Resources.Resource1.paper

Case 3 'Scissors

pbImageComp.BackgroundImage = My.Resources.Resource1.scissors

dialogform.pbImageComp.BackgroundImage = My.Resources.Resource1.scissors

End Select

dialogform.Show()

MessageBox text moved to the new forms label

Mydialogform.lblMessage.Text = "Your choice: Rock, Computer choice: Rock, You tied."

You might want to move the dialogform.Show() around so that it only runs once at

the end of your code

Your Close button just has Close() in the click event for it.

All the code in one place

Dim Mydialogform As New DialogBox

Mydialogform.pbImageComp.BackgroundImage = My.Resources.Resource1.rock

Mydialogform.lblMessage.Text = "Your choice: Rock, Computer choice: Rock, You tied."

Mydialogform.Show()

Page 51: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 51 2012

6. Adding images to a Resource file We can add images to our program, and use them on our buttons, and elsewhere.

Adding images is an important tool in creating a good looking program.

Right click on your project, go Add then New Item. Then choose Resource File. The

resource file will be where you keep all your images.

Double click on your new Resouce.resx, then select Images, and click Add Resource

Choose Add Existing File, and then find it.

You might have to choose the All Files option from the bottom right, if you have an

icon or other image type however these might not be allowed on the program.

Find and add images for your buttons, either using the internet or existing and add

them to your resource file.

To add it to your Button, click on your button to bring up the Properties on the right,

then click on Image to select a resource, and then choose resource1 (or whatever

yours is called) from the pull down menu.

Page 52: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 52 2012

The images will appear in the list below and you can choose whichever one you

want.

Then run your calculator

Use the earlier examples to create the following

in your calculator – Count, Maximums,

Minimums, Averages of the numbers you are

using.

Here is an interesting use of four images called test 1 – 4 cycling every 15 seconds.

Try it.

Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Select Case Now.Minute Case Is < 15 Me.BackgroundImage = My.Resources.test1 Case Is < 30 Me.BackgroundImage = My.Resources.test2 Case Is < 45 Me.BackgroundImage = My.Resources.test3 Case Is < 60 Me.BackgroundImage = My.Resources.test4 End Select End Sub

Page 53: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 53 2012

Guess The Correct Answer game Make a new project, someone enters 2 numbers, which are multiplied, added or

subtracted (you choose) and you have to guess what the answer is. It’s an adaption

of the calculator with user input

If you are correct you get a happy face image, if you are wrong in this PC world you

don’t get a frowning image, but instead you get a banana. A list box will show you

which ones you got right and wrong. (This leads to the Times Table tester later on)

Employee wages Calculate employee wages based on hours. Use tax rates, and overtime rates

Better Brains College – If, And, and Or Better Brains College want a program to determine how many of their students

pass all modules, pass at least one module and pass exactly three modules.

Here is the spreadsheet they use at the moment,

Create a program that determines if they have passed one, three or all the modules

when you enter the marks. The pass mark can be set to whatever the school wants,

so it not always 50. You need to enter this feature as well.

An example below (may be quite sophisticated for this level) for a solution.

Page 54: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 54 2012

Lucky Guess Project The Lucky Guess program selects a random number between 1 and 10 and gives

the user three chances to “guess” the number.

− Hints such as “Too low” and “Too high” are displayed after each guess if the user is

unsuccessful.

Random number generator the same as earlier (actually there are a number of ways

you can make a random number)

Instantiate a new random

Dim rndNumber As New Random()

Generate a number between 1 and 10

randomNumber = rndNumber.Next(1, 11)

Use this when you get it working to create a program that:

Counts and shows you how many tries you have made.

Stops you from having more than 5 tries

Stops errors of no data added

Works from the Keypress event of the txtguess instead of the button

Page 55: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 55 2012

Public Class Form1

Dim rndNumber As New Random()

Dim randomNumber As Integer

Dim intGuess As Integer = 0

Private Sub btnnew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnnew.Click

'clear the listbox

lbguess.Items.Clear()

'generate a new random number

randomNumber = rndNumber.Next(1, 11)

'uncomment this and use it to check your random number is being generated OK

lbguess.Items.Add("Random Number " & randomNumber)

End Sub

Private Sub btnguess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnguess.Click

If IsNumeric(txtGuessNumber.Text) Then'is it a number?

'if so then pass it to the variable

intGuess = txtGuessNumber.Text

'check that its working (can comment out)

Me.Text = "My Guess is " & intGuess

'clear the text box and put the cursor back into the box ready for the next guess

txtGuessNumber.Text = ""

txtGuessNumber.Focus()

End If

' if the number equals the random number

If intGuess = randomNumber Then

lbguess.Items.Add("Congratulations! You found it!")

lbguess.Items.Add("The number was " & randomNumber)

'if the number is less than the random number

ElseIf intGuess < randomNumber Then

lbguess.Items.Add("Too low!")

Else

'if the number is greater then the random number

lbguess.Items.Add("Too high!")

End If

End Sub

End Class

Page 56: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 56 2012

7. Subroutines and Functions Subroutines and functions enable you to break an otherwise unwieldy chunk of code

into manageable pieces. They allow you to extract code that you may need to use

under more than one circumstance and place it in one location where you can call it

as needed. This not only reduces repetition within your code but also enables you to

maintain and update the code in a single location.

A subroutine performs a task for the code that invokes it.

A function performs a task and then returns some value. The value may be the

result of a calculation or a status code indicating whether the function succeeded or

failed.

Together, subroutines and functions are sometimes called routines or procedures. They are also sometimes called methods, particularly when they are subroutines or functions belonging to a class. Subroutines are also occasionally called sub procedures or less formally Subs. (Whew!!!)

So far, the code you have been writing in these tutorials has mostly been lumped

together under one button.

The problem with this approach is that your code can get quite long and complex,

making it difficult to read, and difficult to put right if something goes wrong. Another

approach is to separate some of this code into its own blocks. This is where functions

and subroutines come in

You use methods to break your code into easily read blocks that can be used

repeatedly.

Subroutines that don’t return data – (Subs) This is simply taking a block of code and running it from a command. Note our Sub is

named Message and it is private which means can only be used on this form.

This sub takes the number in the intcounter variable and shows it on the label.

Page 57: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 57 2012

Subroutines that accept data We can make a tidier type of code by using parameters. Think of the variables in

one sub passing data to the variables in another sub, like data changing hands at the

door of an office.

In this example the intcounter and strtext is defined and used in one sub like below.

intcounter += 1

make some text and pass it to a variable

Dim strtext As String = "this is some text"

Then they are included in the brackets of the message method

message(intcounter, strtext)

Then in the message method that data is passed to counter and sometext and then

shown in the messagebox.

Private Sub message(counter As Integer, sometext As String)

'run this mesagebox

MsgBox(counter & " " & sometext)

End Sub

How does it know which variable to pass

the data to?

By the order of the new parameters in the statements, so the first one goes to the

first one, as long as they are compatible types.

Public Class Form1

'declare variable globally make a variable that is used as a counter

Dim intcounter As Integer = 0

Private Sub Click_the_button_BTNGO(sender As Object, e As EventArgs) Handles btnGo.Click

'increment the counter each time you click

intcounter += 1

‘make some text and pass it to a variable

Dim strtext As String = "this is some text"

'call to the message method here intcounter and strtext gets passed to the method

message(intcounter, strtext)

End Sub

Private Sub message(counter As Integer, sometext As String)

'run this mesagebox

MsgBox(counter & " " & sometext)

End Sub

Page 58: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 58 2012

As you can see from the example below data can be passed through to the

subroutine by making parameters in the braces. This means that you don’t have to

make a global variable to have it appear in both subs.

As the code below shows only the intcounter is global, Strtext is only local and still

passes through to the Message sub

Subroutines that accept data and return it- Functions This type of method takes two numbers (num1 and num2) then multiplies them

together and returns an answer to the sub it was called from. There is more on

functions here

If you have more than one variable, like we do, you separate each one with a

comma. You can name the variables virtually anything, it doesn’t need to be the

same is the variables in your main sub. The important thing is that you keep the

same order.

From now on use Subs and Functions in every exercise

Page 59: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 59 2012

Subs and Functions are very important they keep your code tidy and allow it to be

easily scanned.

Coding goals for Subs and Functions

Replace global variables by passing them as parameters in Subs or Functions. You

can also replace them with Class Properties (still to cover)

Have nothing under Click Events except calls to Subs and Functions. This creates

plug and play code for easier reuse.

Functions should be small and encompass only one job. Functions should do one

thing. They should do it well. They should do it only. So, another way to know that a

function is doing more than “one thing” is if you can extract another function from it

with a name that is not merely a restatement of its implementation.

We want the code to read like a top-down narrative. We want every function to be

followed by those at the next level of abstraction so that we can read the program,

descending one level of abstraction at a time as we read down the list of functions.

I.e.: Ideally you can scan your program from top to bottom and see what it does

instead of having to jump around.

The ideal number of arguments (parameters) for a function is zero. Next comes one,

followed closely by two. Three arguments should be avoided where possible. More

than three requires very special justification—and then shouldn’t be used anyway.

Arguments are hard. They take a lot of conceptual power.

Arguments (parameters) are even harder from a testing point of view. Imagine the

difficulty of writing all the test cases to ensure that all the various combinations of

arguments work properly. If there are no arguments, this is trivial. If there’s one

argument, it’s not too hard.

With two arguments (parameters) the problem gets a bit more challenging. With more

than two arguments, testing every combination of appropriate values can be

daunting.

Subs and Functions should have verb or verb phrase names like postPayment,

deletePage, or save.

Page 60: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 60 2012

8. Byref and Byval - Functions - overview We have already looked at Subs, and Functions are like subs except they return a

value to the code that called it.

The difference between Sub and Function revision

Methods contain the executable statements of a program. There are two types of

methods: subroutines and functions.

In Subs we just called them with Sub and a name like Sub selectplan() and just put

selectplan() in the code where we wanted it to run. We used subs to avoid having to

write the same code more than once.

A Sub is some code or job that you want VB to get on with and execute. An example

is closing a form down and unloading it with Me.Close(). You don't need to return a

value, here; you just want VB to close your form down. Also a Sub is a way code in

blocks that are used just in your program. They are not made to be used in other

programs.

Functions are another way to create drag and drop code. You can import functions

and use them in your folder and store them in another place for later use.

A Function is used because you want some sort of answer back, and an answer that

you can then use elsewhere. You should never use a Function without a return

type, it won’t give you a compilation error but it hinders the performance.

A Function can return a value from itself. For example …

Public Function Sum(ByVal a As Integer, ByVal b As Integer) As Integer

Return a + b

End Function

Then you can use this Function as follows

Dim result As Integer = Sum(2, 4)

ByVal (pass a copy of the data) and ByRef (change the original

data) The word ByVal is short for "By Value". What it means is that you are passing a

copy of a variable to your Subroutine, or in other words creating a new instance of

the variable.

You can make changes to the copy and the original will not be altered. Any changes

made to the value of this variable have no effect on the value of the original variable

that was passed in. By Val (by value) means that the called routine uses the value

purely for input, to start a "one way" conversation.

ByRef is the alternative. This is short for By Reference. This means that you are not

handing over a copy of the original variable but pointing to the original variable. Its

not a copy, this is it! Any changes you make to this variable also change its value

outside the routine

Let's see a coding example….

Page 61: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 61 2012

ByRef or ByVal Example

Create this little example to see the difference between Byref and ByVal. To run …

1. Enter two numbers in the text boxes,

2. Load the numbers to the variables,

3. Pass them to functions that just add 10 using the Byref and ByVal buttons.

4. Check your original variable values that are outside the functions with the

Check Variables button.

In this example the variables used are defined initially as

Dim intOne, IntTwo As Integer

The Functions that are used below name their variables differently sngone and

sngtwo BUT STILL CHANGE THE FIRST VARIABLES. intOne and intTwo

Private Sub ByValue(ByVal sngone As Integer)

Private Sub ByReference(ByRef sngtwo As Single)

What is important is that SngOne, which has been operated on with By Value has not changed, while SngTwo has taken the value from the ByRef Function.

When would you use byref? http://stackoverflow.com/questions/290189/best-

practice-byref-or-byval-in-net

MSDN http://msdn.microsoft.com/en-us/library/ddck1z30%28v=vs.110%29.aspx

Code over the page …..

Public Class Form1

Dim intOne, IntTwo As Integer

Private Sub btnload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnload.Click

intOne = txtval.Text

Page 62: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 62 2012

IntTwo = txtref.Text

btnload.Text = "Variables Loaded IntOne, and IntTwo"

End Sub

Private Sub btnByvalue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnByvalue.Click

ByValue(intOne) 'runs the ByValue function

btnByvalue.Text = "10 added"

End Sub

Private Sub btnByRef_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnByRef.Click

ByReference(IntTwo) 'runs the ByRef function

btnByRef.Text = "10 added"

End Sub

Private Sub ByValue(ByVal sngone As Single)

'the Byval function

sngone = sngone + 10

lblbyvalue.Text = "Byval sngone = " & sngone

End Sub

Private Sub ByReference(ByRef sngtwo As Single)

'the Byref Function

sngtwo = sngtwo + 10

lblbyref.Text = "ByRef sngtwo = " & sngtwo

End Sub

Private Sub btncheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncheck.Click

'what are the variables actually holding?

'Byval will not change, while ByRef will change

lblOriginalvariables.Text = "By Value intOne not changed " & intOne & vbCrLf & "By Reference intTwo has changed" & IntTwo

End Sub

End Class

Page 63: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 63 2012

Times Table tester Make a program that will test your times tables. You give it a number and then have it

give the answer.

The output in the listbox shows the correct or wrong answers and shows how many

are correct.

Extra: Show a % correct and give an award image when you get 100%. Also electrocute the user when you get 100% wrong.

Output shown below 1 X 10 = 10 CORRECT 2 X 10 = 12 WRONG 3 X 10 = 29 WRONG

lboutput.Items.Add(intcounter & " X " & sngTestNumber & " = " & sngCorrectAnswer & " : " & sngYourAnswer & " is " & strcorrect)

You scored 6 correct.

lboutput.Items.Add("You scored " & intcorrectcount & " correct")

After you have chosen your start number and the number you want to test to, you click the Test button. This starts the program and you type your answer into the text box. The code that checks the answer only runs on the KeyUp event of that text box,

Public Class Form1

Dim intcounter As Integer = 0

Dim sngTestNumber, sngYourAnswer, sngCorrectAnswer As Single

Dim strcorrect As String

Dim intEndNumber As Integer

Dim intcorrectcount As Integer = 0

Code that runs when you click on the button

Private Sub btnrun_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnrun.Click

lboutput.Items.Clear()

intcounter = 1

btnrun.Text = "Begin Test"

Page 64: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 64 2012

'move data to variables from the textboxes

sngTestNumber = txtTestNumber.Text

intEndNumber = txtEndNumber.Text

txtanswer.Visible = True

‘big blue number in the label 12 X 2 in screenshot

lblformula.Text = intcounter + 1 & " X " & sngTestNumber

End Sub

Code that run on the KeyUp event of the text box when you are entering data. This

only runs when you type your answer in and press the Enter key.

Private Sub txtanswer_KeyUp(ByVal sender As Object, ByVal e As KeyEventArgs) Handles txtanswer.KeyUp

'if you hit the Enter key

If e.KeyCode = Keys.Enter Then

intcounter += 1 'add 1 to the counter

sngYourAnswer = txtanswer.Text 'pass the answer to the variable

sngCorrectAnswer = intcounter * sngTestNumber 'calculate the correct answer

'does your answer equal the correct answer?

CorrectAnswerCheck()

'show the output in the listbox

lboutput.Items.Add(intcounter & " X " & sngTestNumber & " = " & sngCorrectAnswer & " : " & sngYourAnswer & " is " & strcorrect)

'if the counter reaches the end number

If intcounter = intEndNumber Then

EndandFinish()

End If

'this just resets the focus into the answer box and highlights the existing answer, so that it can be automatically overwrittenw ehn you type the next answer

txtanswer.Focus()

txtanswer.SelectAll()

lblformula.Text = intcounter + 1 & " X " & sngTestNumber

End If

End Sub

Sub CorrectAnswerCheck()

If sngCorrectAnswer = sngYourAnswer Then

strcorrect = " correct" 'make the string equal correct

intcorrectcount += 1 'make the correct counter increase by 1

Else

strcorrect = " wrong" 'make the string equal wrong

End If

End Sub

Page 65: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 65 2012

Sub EndandFinish()'code that runs when the end has been reached

'show the amount you got correct

lboutput.Items.Add("You scored " & intcorrectcount & " correct")

'hide the answer text box (stops people from triggering the KeyUp event again)

txtanswer.Visible = False

'reset the button text and the counter and clear the txtAnswer box

btnrun.Text = "Test"

intcounter = 0

txtanswer.Text = ""

End Sub

'code that runs when the end has been reached

Sub EndandFinish()

'show the amount you got correct

lboutput.Items.Add("You scored " & intcorrectcount & " correct")

'hide the answer text box (stops people from triggering the KeyUp event again)

txtanswer.Visible = False

'reset the button text and the counter and clear the txtAnswer box

btnrun.Text = "Test"

intcounter = 0

txtanswer.Text = ""

End Sub

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

End

End Sub

End Class

Page 66: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 66 2012

9. Picture Viewer using containers This lesson looks more at layout and containers, design that I tend to overlook, yet is

very important. The actual coding is dead simple.

Create a new project and on the form add a TablelayoutPanel, this container allows

other objects to snap into it and resize to the cell sizes.

Set the Dock Property to Fill by choosing the

middle section

This expands the Table to the full size of the

form.

Click on the small tag on the Table and close

Edit Rows and Columns

Page 67: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 67 2012

Set the Columns and the Rows as below

That gives you a layout that looks like this

Drag a PictureBox into the first square

Well that looks stupid, we need to span it across both cells. In the

properties set Dock to Fill and ColumnSpan to 2

Drag a Checkbox into the Bottom left square.

Rename the text property to Stretch

Then drag a FlowLayoutPanel to

the bottom right

A FlowLayoutPanel is a container that arranges other controls in neat rows in order.

Page 68: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 68 2012

When you resize a FlowLayoutPanel, if it has room to lay out all of its controls in a

single row, it does that. Otherwise, it arranges them in lines, one on top of the other.

We will use a FlowLayoutPanel to hold four buttons So set Dock to Fill.

Drag 4 buttons into the FlowlayoutPanel and change their text as shown

Name them btnShow, btnClear, btnColor and btnClose and set their Autosize to

True

Now we need to create the ability to open files and change colors

Drag an OpenFileDialog and ColorDialog to the bottom of the Form window, it will

dock there happily.

Set the properties of the OpenFileDialog Filter to JPEG Files (*.jpg)|*.jpg|PNG

Files (*.png)|*.png|BMP Files (*.bmp)|*.bmp|All files (*.*)|*.* (just cut and paste it

across)

Set Title to Choose a Picture File

Page 69: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 69 2012

At last the code!

btnShow click event shows the Open File dialog. If the user clicks OK, load the

picture that the user choses.

If OpenFileDialog1.ShowDialog() = DialogResult.OK Then

PictureBox1.Load(OpenFileDialog1.FileName)

End If

btnClear click event just clears the picturebox

PictureBox1.Image = Nothing

Btncolor click event shows the color dialog box. If the user clicks OK, change the

PictureBox control's background to the color the user chose.

If ColorDialog1.ShowDialog() = DialogResult.OK Then

PictureBox1.BackColor = ColorDialog1.Color

End If

Btnclose just closes the form.

Close()

Finally double click on the Checkbox to get the CheckChanged event, this just

changes the sizemode of the image to fill the PictureBox when you clck on the

Checkbox.

Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged

'If the user selects the Stretch check box, change the PictureBox's SizeMode property to "Stretch". If the user clears the check box, change it to "Normal".

If CheckBox1.Checked Then

PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage

Else

PictureBox1.SizeMode = PictureBoxSizeMode.Normal

End If

End Sub

Page 70: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 70 2012

10. Changing Control Panel setting using the

SystemParametersInfo

Changing the desktop wallpaper in the Picture viewer support.microsoft.com/kb/97142

The SystemParametersInfo API call can be used to get and set Windows settings

that are normally set from the Desktop by using the Control Panel.

In your picture viewer program add the following code to the top to access the API

(this is not the only version of this there appear to be multiple ways to access the

API)

<DllImport("user32.dll", EntryPoint:="SystemParametersInfo")>

Shared Function SystemParametersInfo(uiAction As UInteger, uiParam As UInteger, pvParam As String, fWinIni As UInteger) As Boolean

End Function

Here are the formal arguments to the function:

uAction system parameter to query or set

uParam depends on system parameter

lpvParam depends on system parameter

fuWinIni WIN.INI update flag

The uAction argument we want is CONST SPI_SETDESKWALLPAPER=20 so we

want to pass 20 to the uAction. See the link for the 36 other actions.

support.microsoft.com/kb/97142

The uParam should be 0 when used with a Get constant, and the new value when

used with a Set constant. So we want it as 0.

The lpvParam is used in this case as the path to save the wallpaper

The fuWinIni updates the system with the new settings.

Add the following code to your project as well as a button to save the wallpaper

'new save as desktop wallpaper code

Private Sub btnSetWallpaper_Click(sender As Object, e As EventArgs) Handles btnSetWallpaper.Click

SetWallpaper(Me.PictureBox1.Image)

MessageBox.Show("Wallpaper has been changed", "Set Wallpaper", MessageBoxButtons.OK, MessageBoxIcon.Information)

End Sub

'pass through the image location to the sub

Sub SetWallpaper(ByVal img As Image)

Dim imageLocation As String

Page 71: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 71 2012

'combines two paths and returns a properly formatted path the image is saved as text.bmp

imageLocation = My.Computer.FileSystem.CombinePath(My.Computer.FileSystem.SpecialDirectories.MyPictures, "c:\test.bmp")

Try

'save it to location made above as a bmp file format

img.Save(imageLocation, System.Drawing.Imaging.ImageFormat.Bmp)

Const SPI_SETDESKWALLPAPER As Integer = 20

Const SPIF_UPDATEINIFILE As Integer = 1 'Writes the new system-wide parameter setting to the user profile.

Const SPIF_SENDWININICHANGE As Integer = 2 'Broadcasts the WM_SETTINGCHANGE message after updating the user profile.

'run the function thats above

SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, imageLocation, SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE)

Catch Ex As Exception

MsgBox("There was an error setting the wallpaper: " & Ex.Message)

End Try

End Sub

Page 72: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 72 2012

Telecom Smart Phone Bill Project Create a program to work out the best Smart Phone plan

No fixed term, no cancellation fees and the freedom to move plans whenever you want. You

can even choose to get a new phone and pay it off in instalments. Just select a plan to see

which of our phones you can match it with.

http://www.telecom.co.nz/mobile/mobile/plansandpricing/paymonthly/

Plan A B C D E F strPlan

Monthly

cost $29 $39 $59 $89 $119 $139 sngMonthlycharge

Anytime

min 150 250 500 700 1000

All you

need min sngIncminutes

TXTs Non-stop text

Data 500MB 500MB 1GB 1GB 2GB 2GB SngIncdata

Additional

Minutes 59c/min 59c/min 59c/min 59c/min 59c/min 0 sngAddminutes

Additional

Data 20c/MB 20c/MB 20c/MB 20c/MB 20c/MB 20c/MB sngAdddata

Voicemail 20c per call

20c per call

20c per call

0 0 0 sngvoicemail

You need to use

TablelayoutPanels, Flowlayoutpanels – to group stuff

3 text boxes to input your data

How many minutes you talked txtMinutesUsed How many Voice messages you received txtvoice How much data you used txtDataUsed A label to show what your cost will be lblplancost A Combo Box to make your choice CbxPlan 3 labels to show the data, Minutes, and Voicemail used. (at the bottom of the form)

Page 73: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 73 2012

A bunch of unnamed labels to hold the text on the form

This is the basic code, you will need to control errors when people don’t enter the correct, or any, data in the text boxes.

So what sort of code do we need and how do we make it? We first start with 8 global variables to hold our data

' Global variables create variables to hold the plan data

Dim sngMonthlycharge As Single

Dim sngIncminutes As Single

Dim sngIncdata As Single

Dim sngAddminutes As Single

Dim sngAdddata As Single

Dim SngVoice As Single

Dim sngFinalCost As Single

Dim strplan As String

Next we add some new features.

Sub Routines selectplan() and calculate()

Regions. #Region "Select the Plan" to #End Region

Using ME Me.Text puts data in the Form title

Combo Boxes. CBOplan This is the click event for the Button, it run two subroutines

Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click

selectplan()

calculate()

End Sub

#Region to #End Region allows you to bracket code that you want to minimise

down to get out of the way.

#Region "Select the Plan"

Sub selectplan()

'put the text in the title bar - easier than a messagebox

Me.Text = "You chose the " & strplan & " Plan"

Select Case strplan

Case "A"

sngMonthlycharge = 29

sngIncminutes = 150

SngIncdata = 500

sngAddminutes = 0.59

sngAdddata = 0.2

SngVoice = 0.2

Page 74: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 74 2012

REPEAT FOR THE OTHER OPTIONS B C D E F

Case "B"

Case "C"

Case "D"

Case "E"

Case "F"

End Select

End Sub

#End Region

Sub calculate()

'create the variables to show the inputted data

Dim sngminutesused As Single = 0

Dim sngdataused As Single = 0

Dim sngVoiceused As Single = 0

'create the variables to hold the excess usage

Dim sngExtraMinutes As Single = 0

Dim sngExtraData As Single = 0

Dim sngVoiceCost As Single = 0

Move the data from the text boxes to the variables

sngminutesused = txtMinutesused.Text

sngdataused = txtDataUsed.Text

sngVoiceused = txtVoice.Text

'work out extra charges for talking minutes

sngminutesused = sngminutesused - sngIncminutes

'if you havn't used your minutes you don't get charged with negatives. Otherwise if you use more than your plan allows then work out the additional minutes penality

If sngminutesused > 0 Then

sngExtraMinutes = (sngminutesused * sngAddminutes)

Else 'there is no extra charge if you used less than your plan sets

sngExtraMinutes = 0

End If

'work out extra charge for data

sngdataused = sngdataused - sngIncdata

'if you havn't used your all your data you don't get charged with negatives

If sngdataused > 0 Then

sngExtraData = (sngdataused * sngAdddata)

Page 75: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 75 2012

Else 'there is no extra charge

sngExtraData = 0

End If 'monthly charge doesn't change

'work out the charge for the voicemesage

sngVoiceCost = SngVoice * sngVoiceused

'Final cost is the monthly charge but extra minutes used plus additional data plus Voicemail costs

sngFinalCost = FormatCurrency(sngMonthlycharge + sngExtraMinutes + sngExtraData + sngVoiceCost)

lbplans.Items.Add("The $" & sngMonthlycharge & " Plan " & strplan & " costs you $" & sngFinalCost)

lblPlanCost.Text = sngFinalCost

'Add 3 more labels under your 3 text boxes for the following data

lblminutesused.Text = FormatCurrency(sngExtraMinutes)

lbldataused.Text = "$" & FormatCurrency(sngExtraData)

lblVoiceUsed.Text = FormatCurrency(sngVoiceCost)

End Sub

Private Sub lbplans_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lbplans.SelectedIndexChanged

'clear the list box

lbplans.Items.Clear()

End Sub

Private Sub cbxPlan_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxPlan.SelectedIndexChanged

strplan = cbxPlan.SelectedItem()

End Sub

Page 76: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 76 2012

11. Multichoice test This exercise will be an on-going one with modification of the questions and their importing later in the course. The screen is made with a TableLayoutPanel and FlowLayoutPanels. Visual Studio 2012 shows in the Solution Explorer all the elements of the program in a list that you can use as a reference to make your own program. Dispose and Initialise are built in methods so just ignore them. Form1_Load, Questions, and AnswerButtons are methods that you make. AnswerButtons started out as the click event of the first answer button and was then renamed.

Public Class Form1

'how many correct

Dim intcorrect As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

Questions()

End Sub

Sub Questions()

'static means its only used once, and not redimmed each time the method is called

Static QuestionCounter As Integer

'motor that moves the question counter on by 1 each time it runs.

QuestionCounter += 1

Page 77: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 77 2012

'just an output so you can see its working

Me.Text = "Question " & QuestionCounter

'questions loaded here, for this exercise will come from a datafile and DB later.

Select Case QuestionCounter

Case 1

lblQuestion.Text = QuestionCounter & " Which of these is a Variable?"

btn1.Text = "Button"

btn2.Text = "Label"

btn3.Text = "Double"

btn4.Text = "Form"

btn3.Tag = "yes"

Case 2

lblQuestion.Text = QuestionCounter & " Which of these is NOT a Variable?"

btn1.Text = "Single"

btn2.Text = "Label"

btn3.Text = "Double"

btn4.Text = "String"

'the correct answer has a yes added to its tag event, later when we check the answer it just looks for that tag.

btn2.Tag = "yes"

Case 3

lblQuestion.Text = QuestionCounter & " String is used to ....?"

btn1.Text = "Calculate formulas"

btn2.Text = "Remind you of something"

btn3.Text = "Hold numbers"

btn4.Text = "Hold non numbers"

btn4.Tag = "yes"

Case 4

lblQuestion.Text = QuestionCounter & " The Tag property is used to..."

btn1.Text = "Play games with"

btn2.Text = "Hold information"

btn3.Text = "Create a variable"

btn4.Text = "Load a form"

btn2.Tag = "yes"

Case 5

lblQuestion.Text = QuestionCounter & " Which formula is wrong?"

btn1.Text = "stranswer = intnum1 ""&"" intnum2"

btn2.Text = "dblanswer = intnum1 * intnum2"

btn3.Text = "intanswer = intnum1 + intnum2"

btn4.Text = "stranswer = intnum1 + intnum2"

Page 78: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 78 2012

btn4.Tag = "yes"

Case 6

lblQuestion.Text = QuestionCounter & " Select Case is used to"

btn1.Text = "Calculate formulas"

btn2.Text = "Remind you of something"

btn3.Text = "Replace multiple If's"

btn4.Text = "Hold non numbers"

btn3.Tag = "yes"

Case 7

lblQuestion.Text = QuestionCounter & " What control are the Answers made from (we have used it lots)"

btn1.Text = "ComboBoxs"

btn2.Text = "labels"

btn3.Text = "Buttons"

btn4.Text = "RadioButtons"

btn3.Tag = "yes"

Case 8

lblQuestion.Text = QuestionCounter & " The best TV show for Geeks is"

btn1.Text = "Big Bang Theory"

btn2.Text = "Man Vrs Wild"

btn3.Text = "Downton Abbey"

btn4.Text = "Shortland Street"

btn1.Tag = "yes"

Case 9

lblQuestion.Text = QuestionCounter & " What does Form Load do?"

btn1.Text = "Formally Loads the program"

btn2.Text = "Allows code to run before load"

btn3.Text = "Checks for errors"

btn4.Text = "Rolling in the Deep"

btn1.Tag = "yes"

Case 10

lblQuestion.Text = QuestionCounter & " What does Sender do?"

btn1.Text = "Nothing, it just sits there"

btn2.Text = "Holds all the properties of the control"

btn3.Text = "Instantiates the Object as a radiobutton"

btn4.Text = "Used on Form Load to load properties"

btn2.Tag = "yes"

'this is a messy ending note the exit sub to close out of the method, we could also use Return

Case 11

lblQuestion.Text = "Congratulations you got " & intcorrect & " correct"

btn1.Text = ""

btn2.Text = ""

btn3.Text = ""

btn4.Text = ""

Exit Sub

End Select

End Sub

Page 79: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 79 2012

Private Sub AnswerButtons(sender As Object, e As EventArgs) Handles btn1.Click, btn2.Click, btn3.Click, btn4.Click

'all 4 answer buttons use the same code in their click event. All we want to look for is which answer button has yes in its tag, the rest isn't important

Dim fakebutton As Button

fakebutton = sender

'if the tag event of the answer is Yes then

If fakebutton.Tag = "yes" Then

intcorrect += 1

LBOutcome.Items.Add(intcorrect & " " & fakebutton.Text & " is Correct")

Else

'there is nothing on the tag

LBOutcome.Items.Add(fakebutton.Text & " is Not Correct")

End If

'reset the tag to nothing

fakebutton.Tag = ""

'run the next question

Questions()

End Sub

End Class

Adding a Splash Screen Right Click on your project go Add – New Item, and choose a Splash Screen. Go Project from the Menu, choose the last entry Multichoice Property, scroll to the bottom and choose your splash screen

Click on View Application Events and add a time to wait for, otherwise it’s too fast.

'splash screen events

Protected Overrides Function OnInitialize(commandLineArgs As ReadOnlyCollection(Of String)) As Boolean

Me.MinimumSplashScreenDisplayTime = 5000

Return MyBase.OnInitialize(commandLineArgs)

End Function

Page 80: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 80 2012

Change your Splash Screen to suit. All code in ApplicationEvents.vb

Imports System.Collections.ObjectModel

Namespace My

Partial Friend Class MyApplication

'splash screen events

Protected Overrides Function OnInitialize(commandLineArgs As ReadOnlyCollection(Of String)) As Boolean

Me.MinimumSplashScreenDisplayTime = 5000

Return MyBase.OnInitialize(commandLineArgs)

End Function

End Class

End Namespace

Page 81: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 81 2012

12. Transparent background and automatic shutdown

program This program is an easy bit of code to show how to make a form with a transparent

background and the beginning of a system to shut down your computer without

having to jump through the Windows 8 hoops.

Instead of making an entire form transparent, the TransparencyKey property enables

you to specify a color that will become transparent on the form. This enables you to

make some sections of a form transparent, while other sections are unchanged.

For example, if TransparencyKey is set to a green color and some areas of the form

are that exact shade of green, then they will be transparent. Whatever is behind the

form shows through in those areas; and if you click in one of those areas, you are

actually clicking the object behind the form.

TransparencyKey can be used to create irregularly shaped “skin” forms. A form can

have its BackgroundImage property set with an image, and by just painting a part of

the image with the TransparencyKey color, you can make parts of the form

disappear.

Here is the entire code for the project the shutdown code has been commented out

for testing and replaced with Close()

Public Class Form1

Private Sub Form1_Click(sender As Object, e As EventArgs) Handles Me.Click

Dim ComputerName As String = My.Computer.Name

Close()

'Shell("shutdown -s -f -m \\" & ComputerName)

End Sub

End Class

There is only one graphic on a form. The

graphic is a png with a transparent

background.

The image is added as a resource and added as a background image on the form.

(see over the page)

Page 82: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 82 2012

Other settings are shown right and

below.

Set the transparency key color to one that is the same as your background which

isn’t found in your image, otherwise part of your image may become transparent as

well.

Set the start position to Centre Screen

Creating an Icon

Convert your image to an icon file using http://convertico.com/

Move the icon to your folder and go Project / Properties and choose it from the Icon:

option.

Getting an Exe

After you have run the program look in your debug folder and pull out the exe.

Add in a Message Box and confirmation to be sure you REALLY want to shut your

machine down.

Page 83: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 83 2012

Dim shutdown As DialogResult = MessageBox.Show("Do you REALLY want to shut down?", "Shut Down", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)

If shutdown = DialogResult.No Then

Close()

ElseIf shutdown = DialogResult.Yes Then

Shell("shutdown -s -f -m \\" & ComputerName)

End If

Create a new form (I named mine ShutDownMessage) in the same project and add

two buttons (Yes and No) and some graphics like mine below and a label with the

message.

Change the Startup form in the properties to show the second form

Changing the Startup Form

Rebuild the code so it runs off the two buttons

Private Sub btnshutdown_Click(sender As Object, e As EventArgs) Handles btnshutdown.Click, btnNo.Click

Dim fakebutton As Button

fakebutton = sender

If fakebutton.Text = "Yes" Then

Dim ComputerName As String = My.Computer.Name

Shell("shutdown -s -f -m \\" & ComputerName)

ElseIf fakebutton.Text = "No" Then

Page 84: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 84 2012

Close()

End If

End Sub

To be honest I actually like the red button with the message box best even though its

one more click to shut down. You can easily return to that form by changing the

Startup form property back to the name of your first form.

If you want to access the second form, shutDownMessage, from the first form just

instantiate a form and use ShowDialog on the first form.

Dim shutdownform As New shutdownMessage

shutdownform.ShowDialog()

Create a fading closing form

This stand alone code allows the form to fade out when closing. It looks really good.

Add a timer to your project and insert the code from here into your project.

Public Class Form1

Dim blncancelClose As Boolean = True

‘Look for the FormClosing event from Forms at the top of the code screen pulldown menu

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing

Timer1.Enabled = True ‘turn on the timer

e.Cancel = blncancelClose ‘stop the form from closing (until its faded out. Later in the code Me.Close() closes the form

End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

Me.AllowTransparency = True ‘allow the form to be transparent when it loads

End Sub

‘Timer runs through the following code when Timer1.Enabled = True

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

Me.Opacity -= 0.05 'make it more transparent

If Me.Opacity = 0 Then ‘When its totally transparent …

blncancelClose = False

Me.Close() 'this actually closes the form

End If

End Sub

End Class

Page 85: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 85 2012

Another way to shut down ……

This may be a safer method than the brutal shell command.

To make it shutdown: we write after the comma “-s”

To make it restart we write after the comma “-r”

To make it logoff we write after the comma “-l”

So the code will be for example:

System.diagnostics.Process.Start(“shutdown”, “-s”)

Will cause the computer to shutdown. When you order it to shutdown like this it will

give you about 20 sec to shutdown but there is a way to manage that.

System.Diagnostics.Process.Start(“shutdown”, “-s -t 00″)

The -t will control the time after -t we write the number of sec (Note: max sec = 99)

From: http://developerlogic.wordpress.com/2011/03/03/shutdown-restart-or-log-off-

your-computer-using-vb-net/

Process.Start has some very interesting options, you can use it to start programs and

set them up .

http://msdn.microsoft.com/en-us/library/53ezey2s.aspx?cs-save-lang=1&cs-

lang=vb#code-snippet-1

Page 86: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 86 2012

13. Loops In VB.Net Loops are used for iteration purposes, i.e., performing a task multiple times (usually

until a termination condition is met)

There are two basic types of loops.

− A pre-test loop tests the condition before the body of the loop is executed. It is

possible, using a pre-test loop, that the body of the loop might never be executed.

− A post-test loop tests the condition after the body of the loop is executed. The

number of iterations in a post-test loop is at least one.

When writing a program, you might have to make a decision regarding which loop

structure to use.

For...Next loops and For Each loops are best when the number of repetitions is

fixed.

Do loops are best when the condition to enter or exit the loop needs to be re-

evaluated continually.

When deciding which loop to use, keep the following considerations in mind:

1. Use a Do loop if the number of repetitions is unknown and is based on a condition

changing; a For...Next loop is best if the exact number of repetitions is fixed.

2. If a loop condition must be tested before the body of the loop is executed, use a

top-controlled Do While or Do Until loop. If the instructions within a loop must be

executed one time regardless of the status of a condition, use a bottom-controlled Do

While or Do Until loop.

3. Use the keyword While if you want to continue execution of the loop while the

condition is true.

4. Use the keyword Until if you want to continue execution until the condition is

true.

For…Next Loop The most common type of loop in VB.Net is the For...Next loop. The basic structure

of the For...Next loop is like so:

For variable = startingValue To lastValue statement or block of statements

Next

Lets see a For...Next loop that will write integers from 1 to 10

Dim i As Integer

For i = 1 to 10

Output to a listbox(i)

Next

Page 87: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 87 2012

At the start, an integer variable i is initialized with the value of 1, then the statements

under the For are executed until the value of i does not equal 10. Each time i is

incremented by 1.

The important points about for loop are:

• You can use an Exit For statement in a For...Next loop or any other loop to change

the normal execution flow. • An Exit For statement terminates the loop and

transfers the execution point outside the for loop as below:

For i=1 to 10

If i>5 Then

Exit For

End If

Output to a listbox

Next

The loop will terminate once the value of i gets greater than 5.

You can define the increment/decrement (change) in each iteration of a For...Next

Loop using the Step statement. The code below will increment by 2 in the value of i in

each cycle of the loop

For i = 1 To 10 Step 2

Output to a listbox

Next

Giving 1 3 5 7 9

Note that the increment starts after the first iteration. You can also specify the

negative increment (i.e., decrement) in a Step.

Page 88: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 88 2012

The Leap Year Program – For loop For this exercise The LeapYear program calculates whether a given year is a leap

year.

Any year evenly divisible by 4 is a leap year except those years that are also evenly

divisible by 100.

One exception: If the year is evenly divisible by 400, it is a leap year.

Create a: Button = btncheck and a Listbox = lbyear

Using Mod

The Mod operator divides number1 by number2 and returns only the remainder

as result.

For example, A (result) equals 2 in A = 8 Mod 3.

Its a really handy tool that you will see a lot in programming. In this case year Mod 4

= 0 divides the year by 4 and if it equals 0 does something.

Note the AND and OR in the IF Statement

Private Sub btncheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncheck.Click

Dim year As Integer = txtyearenter.Text

For i = 1 To 10

If year Mod 4 = 0 And (year Mod 100 <> 0 Or year Mod 400 = 0) Then

lbyear.Items.Add(year & " is a Leap Year")

Else

lbyear.Items.Add(year & " is a not Leap Year")

End If

year += 1

Next

End Sub

Page 89: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 89 2012

14. Do While…Loop The general structure of the Do While...Loop is

Do While Boolean expression

Statement or block of statements

Loop

The statements under Do While will run continuously as long as the Boolean

expression evaluates to true. The similar code for printing integers 1 to 10 using the

Do While...Loop is

Dim i As Integer =1

Do While i<=10

Output to a listbox

i = i + 1

Loop

The Leap Year Program – part 2 Do While loop Change the Code to add the Do While. Note that you have to manually make the

calculator i +=1 for this type of loop. By placing it when there is a leap year it shows

the next 10 leap years.

Private Sub btncheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncheck.Click

Dim year As Integer= txtyearenter.Text

Dim i As Integer = 1

‘Do while i is less than or equal to 10

Do While i <= 10

If year Mod 4 = 0 And (year Mod 100 <> 0 _

Or year Mod 400 = 0) Then

lbyear.Items.Add(year & " is a Leap Year")

i += 1

Else

' lbyear.Items.Add(year & " is a not Leap Year")

End If

year += 1

Loop

End Sub

Page 90: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 90 2012

Do some error checking. Put a Try Catch around your code,

Add an Exit DO in an IF statement to get out of a bad loop.

Private Sub btncheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncheck.Click

Try

Dim year As Integer = txtyearenter.Text

Dim i As Integer = 1

Do While i <= 10

If year < 0 Then

lbyear.Items.Add(year & " Invalid year... terminating!")

Exit Do

End If

If year Mod 4 = 0 And (year Mod 100 <> 0 Or year Mod 400 = 0) Then

lbyear.Items.Add(year & " is a Leap Year")

i += 1

Else

lbyear.Items.Add(year & " is a not Leap Year")

End If

year += 1

Loop

Catch

MsgBox("At least put a number in")

End Try

End Sub

Page 91: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 91 2012

Do While – Fibonacci Sequence Mathematician Leonardo Fibonacci posed the following problem in his treatise Liber

Abaci:

Assuming that a newly born pair of rabbits, one male, one female, are put in a field the rabbits are able to mate at the age of one month. So that at the end of its second month a female can produce another pair of rabbits.

If the rabbits never die and a mating pair always produces one new pair (one male, one female) every month from the second month on.

The puzzle that Fibonacci posed was: How many pairs will there be in one year?

At the end of the first month, they mate, but there is still only 1 pair.

At the end of the second month the female produces a new pair, so now there are 2 pairs of rabbits in the field.

At the end of the third month, the original female produces a second pair, making 3 pairs in all in the field.

At the end of the fourth month, the original female has produced yet another new pair, the female born two months ago produces her first pair also, making 5 pairs.

At the end of the nth month, the number of pairs of rabbits is equal to the number of new pairs

(which is the number of pairs in month n − 2) plus the number of pairs alive last month (n −

1). This is the nth Fibonacci number

.

Fibonacci is found naturally in nature and also used by Stock traders

http://www.babypips.com/school/summary-of-fibonacci.html .

All about Fibonacci http://en.wikipedia.org/wiki/Fibonacci_number

Page 92: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 92 2012

This code

doesn’t show the first two given numbers 0 and 1. Fix it.

Private Sub btnrun_Click(sender As Object, e As EventArgs) Handles btnrun.Click

Dim Num1 As Integer = 0 'First number

Dim Num2 As Integer = 1 'Second Number

Dim NumSum As Integer = 0 'Sum of First and Second Number

Dim FibEnd As Integer = Val(txtFibIn.Text)

Do While NumSum <= FibEnd

'add the first two numbers together (0 and 1)

NumSum = Num1 + Num2

'pass Num2 to Num1 to make a new Num1

Num1 = Num2

'Pass the total (NumSum) to Num2 to make a new Num2

Num2 = NumSum

lbxFibOut.Items.Add(NumSum.ToString)

Loop

End Sub

Find the even Fibonacci numbers only

Each new term in the Fibonacci sequence is generated by adding the previous two

terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed

four million, find the sum of the even-valued terms.

From: http://projecteuler.net/problem=2

What is the first Fibonacci number to contain 1000 digits?

What is the first term in the Fibonacci sequence to contain 1000 digits?

http://projecteuler.net/problem=25

Page 93: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 93 2012

Do…Loop While A Do...Loop While is similar to a Do While...Loop, except that it does not check the

condition before entering the first iteration (execution of code inside the body of loop).

The general form of the a Do...Loop While is:

Do

statement or block of statements

Loop While Boolean expression

The statements under the Do will be executed first and then the Boolean condition is

checked. The loop will continue until the condition remains true. The code which

prints integers 1 to 10 using Do...Loop While is

Dim i As Integer = 1

Do

Output to a listbox

i = i + 1

Loop While i<=10

The important point is that the statements in a Do...Loop While execute at least once.

Do…Loop Until A Do...Loop Until is similar to the Do...Loop While, except that it continues to execute

the containing statements until the condition against the Until part evaluates to True

or the condition against the Until remains False. The general form of the Do...Loop

Until is as follows:

Do

statement or block of statements

Loop Until Boolean expression

The statements under the Do will execute first and then the condition is checked. The

loop will continue until the condition remains false. The following code will print

integers from 1 to 10 using the Do...Loop Until.

Dim i As Integer = 1

Do

Output to a listbox

i = i + 1

Loop Until i=10

Again the statements in Do...Loop Until execute at least once.

Page 94: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 94 2012

15. For Each Loop The For Each loop is also very handy especially when extracting out individual

characters inside of a string or larger number. In this case the word you enter is

broken up into letters and passed to a character (Char) variable then displayed in a

listbox. This is the beginning of string operations.

Add the pens array to the list as well, it’s a great way to add a quick array.

Private Sub btngo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btngo.Click

Dim strword As String

Dim chrletter As Char

strword = txtword.Text

For Each chrletter In strword

lbwordout.Items.Add(chrletter)

Next

'The brackets() tell the program its an array

Dim Pens() As String = {"Red pen", "Blue Pen", "Black Pen"}

' Loop over each element with For Each.

For Each pen As String In Pens

lbwordout.Items.Add(pen)

Next

End Sub

Page 95: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 95 2012

Find the multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6

and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

http://projecteuler.net/problem=1

Times Table calculator Using a Loop, a Listbox, a Textbox and a Button create a program that asks you for a

times table number and then displays it in the list box as

1 X 10 = 10 2 X 10 = 20 etc.

Page 96: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 96 2012

Private Sub btnrun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnrun.Click

lboutput.Items.Clear()

Dim sngyournumber, sngmultiplier, runningsum As Single

sngyournumber = txtyournumber.Text

sngmultiplier = txtmultiplier.Text

Dim i As Integer

For i = 1 To sngmultiplier

Dim snganswer As Single

snganswer = i * sngyournumber

lboutput.Items.Add(i & " X " & sngyournumber & " = " & snganswer)

runningsum = runningsum + snganswer

Next

lboutput.Items.Add(" Total " & runningsum)

End Sub

Page 97: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 97 2012

Dice Rolls with Loops Create a new project; use a ListBox, and a ComboBox and a Button for this exercise

The program asks for a number and displays the numbers that divide equally into it.

The program throws a pair of dice, stopping when the number of doubles you have

specified has been reached. It also displays each throw and puts the word DOUBLE

beside the doubles and tells you how many times it took you to throw to reach your

total.

Eg:

Double total = 3 2 6 3 3 DOUBLE 6 6 DOUBLE 3 1 1 1 DOUBLE You took 5 turns to throw 3 doubles.

Expand the program to work with Triples. Same as below with three dice.

This loads the combo box with 1 to 6 at startup of the form (its nice )

Private Sub Form1_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated

Dim i As Integer

For i = 1 To 6

cbStopOn.Items.Add(i)

Next

End Sub

Private Sub btnroll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnroll.Click

Dim randomnumberD1 As Integer

Dim randomnumberD2 As Integer

' Initialize the random number generator

Randomize()

Page 98: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 98 2012

' Calculate a random number between 1 and 6

randomnumberD1 = Int(1 + 6 * Rnd())

randomnumberD2 = Int(1 + 6 * Rnd())

Dim storage As String

Dim stopValue As Integer

Dim dblCount As Integer

' empty the listbox

lbDiceRolls.Items.Clear()

' get the stop value

stopValue = cbStopOn.SelectedItem

' now roll the dice until we get the correct double

Do

' Calculate a random number between 1 and 6

randomnumberD1 = Int(1 + 6 * Rnd())

randomnumberD2 = Int(1 + 6 * Rnd())

' make a string to add to the listbox

storage = randomnumberD1.ToString & " " & randomnumberD2.ToString

' check if it's a double and modify the string

' if it is, also count this for later

If randomnumberD1 = randomnumberD2 Then

storage &= " Double!"

dblCount += 1

End If

' store it in the listbox

lbDiceRolls.Items.Add(storage)

Loop Until (randomnumberD1 = randomnumberD2) And (dblCount = stopValue)

End Sub

Stop the program from crashing when you forget to choose a selection in the

ComboBox.

Page 99: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 99 2012

Identify the appropriate method for handling repetition SCENARIO: Adriana is creating a point-of-sale (cash register) application for Fourth

Coffee. Her responsibility is to create a password-protected login system to ensure

security of the system.

She has finished the login window and password check, but she is having trouble

implementing it correctly.

Adriana’s project manager wants the system to give the user three attempts to login

correctly before locking the system. In Adriana’s most recent version, the system

prompts the user for a name and password three times— even if the user correctly

logs in on the first try.

After the third attempt, the system always locks—even if the input is correct.

1. Adriana is using a for loop, which works best when:

a. the number of iterations is known and is unlikely to change during execution

b. the number of iterations is known but is likely to change during execution

c. the number of iterations is unknown

2. What control structure would be best for Adriana’s login system?

a. for loop

b. while loop

c. a recursive method

3. How many times does a do..while loop execute?

a. at least zero times

b. at least one time

c. at least two times

Create her login system.

From: Microsoft training 361.pdf in Goodies folder.

Page 100: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 100 2012

Depreciation Rate calculator Create a program that works out the depreciation for tax purposes on a range of

items.

Develop a program that:

Accepts as input the purchase price of a car;

Accepts as input how long in years the car is to be depreciated.

Accepts the amount of depreciation per year.

Outputs the value of the car (currency format) after it has depreciated.

Test Case:

Input: Purchase Price $18,500 and 3 Years to Depreciate the Car

After 1 year the value is $14,800 (80% of 18,500)

After 2 years the value is $11,840 (80% of 14,800)

After 3 years the value is $9,472 (80% of 11,840)

Output: $9,472

The example above uses a Date and Time Picker set to show only year.

A list box (named lstTotals) with the year data and depreciation formula looped into it,

and styled with a TableLayoutPanel and a FlowlayoutPanel.

Depreciation formula is simple – Car price = Car price –(Car price * percent

deduction)

The Date and Time Picker Properties has

ShowUpDown set to True.

Format set to Custom.

CustomFormat set to yyyy

In the code returns the year in the code with dblYear =

dtpPurchaseYear.Value.Year

Page 101: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 101 2012

The Dog and lemon guide suggest the following deprecation rates for a new car

The Dog & Lemon Guide rough & ready depreciation formula:

http://www.dogandlemon.com/articles/depreciation-new-zealand

New: $100,000

2nd year: (less 40%) $60,000

3rd year: (less 20%) $48,000

4th year: (less 20%) $38,400

5th year: (less 20%) $30,720

Modify your program to use these new depreciation rates.

This exercise is modified later for use with Classes.

What If … we input the depreciation rates from a data file, and store it in an array, then we can build a full blown program that allows us to work out depreciation and sell it to IRD!

Page 102: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 102 2012

Compounding Interest Calculator This is more interesting that it first seems. Create a calculator that calculates the

interest on your money compounding. That is when you earn the interest it is added

back on to the principal and interest is calculated on the new amount.

There are 4 main areas

How much the Principal is – the money you are investing

How much the interest rate is – in % which has to be converted to decimal by

dividing by 100

How many years you are investing for

How often your interest is calculated, daily, weekly, monthly, yearly.

In the tag properties of the 4 radio buttons set them to 1, 12, 52, 365 the radiobuttons

are in a Groupbox but that’s just for style and ease of movement.

Public Class Form1

'how many times a year its paid

Dim int_interest_period As Integer

Private Sub btncalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncalculate.Click

lboutput.Items.Clear()

Dim sng_principal As Single = Val(txtprincipal.Text)

'whats your interest rate

Dim sng_interest_rate As Single = Val(txtInterestRate.Text)

'how many years its in for

Dim int_years As Integer = Val(txtYears.Text)

'total number of periods that the paymnets are made

Dim int_payment_period As Integer = int_years * int_interest_period

'interest rate per payment period

Dim sng_interest_per_period As Single

sng_interest_per_period = (sng_interest_rate / 100) / int_interest_period

Page 103: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 103 2012

For i As Integer = 1 To int_payment_period

Dim sng_current_value As Single

sng_current_value = sng_principal * sng_interest_per_period

sng_principal = sng_principal + sng_current_value

lboutput.Items.Add(i & ": " & FormatCurrency(sng_principal))

Next i

lbltotal.Text = "You will earn " & FormatCurrency(sng_principal)

End Sub

Private Sub rbyear_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbyear.CheckedChanged, rbmonthly.CheckedChanged, rbweekly.CheckedChanged, rbdaily.CheckedChanged

'all the radio buttons come to this sub then they are passed to the fake button and the tag is sent to the variable

Dim fakeradiobutton As New RadioButton

fakeradiobutton = sender

int_interest_period = fakeradiobutton.Tag

End Sub

End Class

Page 104: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 104 2012

Calculate the change for a shop Back in the past before EFTPOS people had to actually pay cash for goods (really!).

When someone buys goods the till automatically calculates the change that they get

back. It’s basically the amount of money handed over minus the price of the goods.

Then however the magic begins, the scared kid behind the counter had to translate

that amount into coins and notes. Thankfully the machine did that as well and this

program replicates that operation with a loop.

This project uses 2 text boxes, a button and a label for data.

Page 105: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 105 2012

Private Sub btncalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncalculate.Click

Dim sngproductcost As Single

Dim sngmoneypaid As Single

Dim sngchangegiven As Single

Dim tendollar As Integer

Dim fivedollar As Integer

Dim dollar As Integer

Dim fiftycent As Integer

Dim twentycent As Integer

Dim tencent As Integer

Dim fivecent As Integer

sngproductcost = txtproductcost.Text * 100

sngmoneypaid = txtmoneypaid.Text * 100

sngchangegiven = sngmoneypaid - sngproductcost

If sngchangegiven < 0 Then

MsgBox("Pay more cheapskate")

End If

Do Until sngchangegiven < 5

If sngchangegiven > 999 Then

tendollar += 1

sngchangegiven = sngchangegiven - 1000

ElseIf sngchangegiven > 499 Then

fivedollar += 1

sngchangegiven = sngchangegiven - 500

ElseIf sngchangegiven > 99 Then

dollar += 1

sngchangegiven = sngchangegiven - 100

ElseIf sngchangegiven > 49 Then

fiftycent += 1

sngchangegiven = sngchangegiven - 50

ElseIf sngchangegiven > 19 Then

twentycent += 1

sngchangegiven = sngchangegiven - 20

ElseIf sngchangegiven > 9 Then

tencent += 1

Page 106: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 106 2012

sngchangegiven = sngchangegiven - 10

ElseIf sngchangegiven > 4 Then

fivecent += 1

sngchangegiven = sngchangegiven - 5

End If

Loop

lblchange.Text = tendollar & " Ten Dollars " & vbCrLf & fivedollar & " Five Dollars " & vbCrLf & dollar & " Dollars " & vbCrLf & fiftycent & " 50c " & vbCrLf & twentycent & " 20c " & vbCrLf & tencent & " 10c " & vbCrLf & fivecent & " 5c "

End Sub

Page 107: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 107 2012

Times Table tester with Loop This is a simpler code than before, with the Do Loop running until it matches the

number you want to test to.

Modify the existing timetable program to run off a Do until loop and an input box.

Public Class Form1

Dim intcounter As Integer

Dim sngyournumber, sngyouranswer, snganswer As Single

Dim strcorrect As String

Dim intmultiplier As Integer

Dim intcorrectcount As Integer = 0

Dim questiontext As String

Private Sub btnrun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnrun.Click

lboutput.Items.Clear()

intcounter = 1

btnrun.Text = "Test"

'move data to variables

sngyournumber = txtyournumber.Text

intmultiplier = txtmultiplier.Text

answercode()

End Sub

Sub answercode() 'renamed keyup sub to answercode and added it to the button click

Dim intcounter As Integer

Dim stryouranswer As String

'loop until the counter equals your number

Do Until intcounter = sngyournumber

intcounter += 1

questiontext = intcounter & " X " & sngyournumber

‘use an Input box to break into the loop

stryouranswer = InputBox("Enter your answer " & questiontext, "")

Page 108: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 108 2012

sngyouranswer = stryouranswer

'calculate the correct answer

snganswer = intcounter * sngyournumber

'if your answer = correct answer

If snganswer = sngyouranswer Then

strcorrect = " correct"

intcorrectcount += 1

Else

strcorrect = " wrong"

End If

lboutput.Items.Add(intcounter & " X " & sngyournumber & " = " & snganswer & " : " & sngyouranswer & " is " & strcorrect)

Loop

lboutput.Items.Add("You scored " & intcorrectcount & " correct")

btnrun.Text = "Test"

intcounter = 0

End Sub

Page 109: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 109 2012

16. Password CraCker with loops This fun program creates two ways to hack passwords. The first is by making random

guesses as to the answer, and the second is to logically move through every option

to find the answer.

The form has only a few important controls.

2 Buttons, - btnGuessAnswer and btnloop

2 textboxes, txtinput and txtMASKinput. txtMASKinput has the PasswordChar set to *

1 Listbox lbxoutput

The random generator is wrapped in a function for ease of use. The function takes in

the length of the password you are trying to find and returns back a random number

of letters of that same length PWcrackerWithRandom(strPW.Length)

Public Function PWcrackerWithRandom(ByVal strLength As Integer)

Dim strletters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

Dim rndletters As New Random()

'use string builder as its better with longer text and you can use Append

Dim strresult As New System.Text.StringBuilder()

'for the length of the word you are trying to find

For i = 1 To strLength

'join the letters together using the range of the letters from 1 to the length of strletters

strresult.Append(strletters(rndletters.Next(1, strletters.Length)))

Next i

'return back the answer to the program

Return strresult.ToString()

End Function

Page 110: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 110 2012

The click event of the generator matches the random word with the password. If the

two are the same it ends, otherwise it asks for another random work and keeps on

until a match is made.

Private Sub btnGuessAnswer_Click(sender As Object, e As EventArgs) Handles btnGuessAnswer.Click

Dim strPW As String = txtinput.Text

Dim strguess As String

Dim intcount As Integer

Do

strguess = PWcrackerWithRandom(strPW.Length)

intcount += 1

Me.Text = intcount & " " & strPW

'slows down the program but shows the update

Application.DoEvents()

'loop until the guess = the password

Loop Until strPW = strguess

lbxOutput.Items.Add("It took " & intcount & " guesses to match " & strPW & " with " & strguess)

End Sub

DoEvents – a curse or a solution?

Usually the program works too fast to see but if you want to see the words that are

created by the random generator you can output them to the form with Me.Text =

intcount & " " & strPW

However to do this you need to add Application.DoEvents() to your code to tell the

program to stop in the loop and run any events that are waiting. This has the side

effect of slowing down the program but it gives you something to look at.

Me.Text = intcount & " " & strPW

'slows down the program but shows the update

Application.DoEvents()

DoEvents however has very bad press … just read this thread

http://stackoverflow.com/questions/5181777/use-of-application-doevents

The next versions of C# and VB.NET will provide a different gun with the new await and async keywords. Inspired in small part by the trouble caused by DoEvents and threads, but in large part by WinRT's api design that requires you to keep your UI updated while an asynchronous operation is taking place, like reading from a file.

Why don’t people like to use DoEvents? MS give an answer:

Calling this method causes the current thread to be suspended while all waiting window messages are processed. If a message causes an event to be triggered, then other areas of your application code may execute. This can cause your application to exhibit unexpected behaviours that are difficult to debug.

Page 111: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 111 2012

So if you use DoEvents make sure there are no other events waiting to run that are

not meant to be part of your program at that time. (for us it’s OK, this is advanced

programming)

Standard Progress Bar

You could also add a Progress bar and have it increase to show its working as well.

Just Dim a counter variable, you can’t use the existing counter as you want to reset it

to 0 when the bar is full and set your max value at something like 10000 in the

properties.

intprogcount += 1

ProgressBar1.Value = intprogcount

If ProgressBar1.Value = 10000 Then

ProgressBar1.Value = 0

intprogcount = 0

End If

Simple Custom Progress Bar

We can also take the time to make a simple Progress bar from a label that can also

show how many times the loop has been run.

Put a small narrow label on your form and dim a counter for it intlblprogressbar.

In the code we want the width of the label to expand until it finds the right hand side

of the form Me.Width and then return back to 0, so when the width of the label and

the distance from the edge of the form to the label (The label.left) equals the width of

the form then reset it back to 0. lblprogressbar.Width + lblprogressbar.Left =

Me.Width.

Use lblprogressbar.Text = intcount to have the counter show on the label.

intlblprogressbar += 1

lblprogressbar.Width = intlblprogressbar

lblprogressbar.Text = intcount

If lblprogressbar.Width + lblprogressbar.Left = Me.Width Then

intlblprogressbar = 0

End If

All the code to date.

Page 112: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 112 2012

Private Sub btnGuessAnswer_Click(sender As Object, e As EventArgs) Handles btnGuessAnswer.Click

Dim strPW As String = txtinput.Text

Dim strguess As String

Dim intcount, intprogcount, intlblprogressbar As Integer

Do

strguess = PWcrackerWithRandom(strPW.Length)

intcount += 1

Me.Text = intcount & " " & strPW

'slows down the program but shows the update

Application.DoEvents()

'loop until the guess = the password

intprogcount += 1

ProgressBar1.Value = intprogcount

If ProgressBar1.Value = 10000 Then

ProgressBar1.Value = 0

intprogcount = 0

End If

intlblprogressbar += 1

lblprogressbar.Width = intlblprogressbar

lblprogressbar.Text = intcount

If lblprogressbar.Width + lblprogressbar.Left = Me.Width Then

intlblprogressbar = 0

End If

Loop Until strPW = strguess

ProgressBar1.Value = 0

intprogcount = 0

lbxOutput.Items.Add("It took " & intcount & " guesses to match " & strPW & " with " & strguess)

End Sub

What if …. we compared each generated word to a dictionary of words, using a hash

table, and kept the words that were real. If we did it long enough could we make a

real sentence?

Page 113: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 113 2012

Nested Loops to create logical selection

The other main way to get a password can come from using a logical process of

looking for every combination of the password and seeing if it is the correct one.

The code for this is remarkably simple yet tedious to create, and limited in its scope.

Surprisingly I haven’t been able to find a shortcut way of writing this

In this case I used 3 nested loops which meant it can only search for 3 letter

passwords. Four nested loops would search for 4 letter passwords, 5 nested loops

would search for 5 letter passwords etc. Slow and laborious to write.

With three loops it starts with the first letters, and then the inner loop increments by 1.

This acts like an odometer in a car.

AAA

AAB

AAC

AAD

Etc

To

999

Private Sub btnLoop_Click(sender As Object, e As EventArgs) Handles btnLoop.Click

Dim strPW As String = txtMASKinput.Text

Dim strguess As String

Dim intcount As Integer

'a string of all the letters you want to search for

Dim strletters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

'nested loops looking for every combination of the letters from AAA to 999

For Each letter1 As Char In strletters

For Each letter2 As Char In strletters

For Each letter3 As Char In strletters

intcount += 1

'add the letters together to get a guess to test

Page 114: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 114 2012

strguess = letter1 & letter2 & letter3

Me.Text = intcount & " " & strguess

Application.DoEvents()

'if the password = the guess then stop the loop

If strPW = strguess Then

lbxOutput.Items.Add("It took " & intcount & " loops to match " & strPW & " with " & strguess)

Return

End If

Next

Next

Next

End Sub

Now that you can break 3 letter passwords, create a program that breaks passwords from 3 to 7 letters automatically, by detecting how many letters you put in and stopping errors for too many or too few letters.

Don’t forget to use methods (subs and functions) so that you have small blocks of easily followed code.

Finish your program by using a Background Worker (next page) to stop your machine freezing when breaking passwords

What if ……. we checked the entry of a list of the top 100 used passwords first? So

we parse a list of all 3 words passwords and check it with the given password. To do

that we need to use arrays and to read a data file in.

Page 115: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 115 2012

17. Background Workers http://msdn.microsoft.com/en-us/library/hybbz6ke.aspx

The BackgroundWorker class allows you to run an operation on a separate,

dedicated thread. Time-consuming operations like downloads and database

transactions can cause your user interface (UI) to seem as though it has stopped

responding while they are running.

When you want a responsive UI and you are faced with long delays associated with

such operations, the BackgroundWorker class provides a convenient solution.

Overview

To execute a time-consuming operation in the background,

1. create a BackgroundWorker and

2. listen for events that report the progress of your operation and

3. signal when your operation is finished.

You can create the BackgroundWorker programmatically or you can drag it onto

your form from the Components tab of the Toolbox.

1. To set up for a background operation, add an event handler for the DoWork

event. Call your time-consuming operation in this event handler. In the

example I called it from the Form Load event. Sub Form1_Load

2. To start the operation, call RunWorkerAsync. BGW1.RunWorkerAsync()

3. To receive notifications of progress updates, handle the ProgressChanged

event. Sub BackgroundWorker1_ProgressChanged

4. To receive a notification when the operation is completed, handle the

RunWorkerCompleted event. Sub BackgroundWorker1_RunWorkerCompleted

You must be careful not to manipulate any user-interface objects in your DoWork

event handler. Instead, communicate to the user interface through the

ProgressChanged and RunWorkerCompleted events.

As your user interface is controlled by the Main thread, you can’t access it with a

background worker, otherwise it might find 2 threads are trying to use it and crash or

go unstable.

If your background operation requires a parameter, call RunWorkerAsync with your

parameter. Inside the DoWork event handler, you can extract the parameter from the

DoWorkEventArgs.Argument property.

Page 116: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 116 2012

This example uses a Progressbar, a label, and a

Button.

Drag a Background Worker on to your program from

the Toolbox and set the properties as follows

Imports System.ComponentModel

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'Raise the DoWork event in a worker thread. ' Start the asynchronous operation.

Me.BGW1.RunWorkerAsync()

End Sub

'This event handler is where the time-consuming work is done.

'This event is raised when you call the RunWorkerAsync method. This is where you start the operation that performs the potentially time-consuming work.

'Your code in the DoWork event handler should periodically check the CancellationPending property value and abort the operation if it is true.

Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BGW1.DoWork

' Get the BackgroundWorker object that raised this event.

Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

For i As Integer = 1 To 100

'checking to see if you hit the cancel button (need it for safety)

Page 117: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 117 2012

If (worker.CancellationPending = True) Then

e.Cancel = True

Exit For

End If

'Raise the ProgressChanged event in the UI thread. Note the first i is passed to the e.ProgressPercentage later on. The second code i & " iterations complete" passes to the TryCast(e.UserState, String)

worker.ReportProgress(i, i & " iterations complete")

'Perform some time-consuming operation here.

Threading.Thread.Sleep(50)

Next i

End Sub

'This method is executed in the UI thread and updates the progress bar.

Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles BGW1.ProgressChanged

Me.ProgressBar1.Value = e.ProgressPercentage

Me.Label1.Text = TryCast(e.UserState, String)

End Sub

'This event handler deals with the results of the background operation.

Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BGW1.RunWorkerCompleted

Me.Label1.Text = "Operation complete"

End Sub

Private Sub btncancel_Click(sender As Object, e As EventArgs) Handles btncancel.Click

If BGW1.WorkerSupportsCancellation = True Then

' Cancel the asynchronous operation.

BGW1.CancelAsync()

End If

End Sub

End Class

Page 118: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 118 2012

18. Text to Speech This is easy, and another tool to add to your toolkit. Just create a new form with a

multiline text box and a button.

Add the following code and then run. Type something in the text box and listen to the

output. A nice way to add voice commands to your program.

Public Class Form1

Private Sub btnSpeak_Click(sender As Object, e As EventArgs) Handles btnSpeak.Click

Dim SAPI = CreateObject("SAPI.spvoice")

SAPI.speak(TextBox1.Text)

End Sub

End Class

What if … we plug this into a calculator to read out the results?

Speech to text Firstly add the following reference into your program as seen below. There is nothing

to add to your form, at this stage it only shows on a message box.

However once you get this running make the output go to a label so you can speak in

the words and save the text.

Page 119: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 119 2012

Imports System.Speech

Imports System.Speech.Recognition

Imports System.Speech.Synthesis

Public Class Form1

Dim replier As New SpeechSynthesizer()

Dim WithEvents questioner As New Recognition.SpeechRecognizer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

Dim gram As New Recognition.SrgsGrammar.SrgsDocument

Dim gramRule As New Recognition.SrgsGrammar.SrgsRule("Rules")

Dim gramSingle As New Recognition.SrgsGrammar.SrgsOneOf("Red", "Green", "Blue")

gramRule.Add(gramSingle)

gram.Rules.Add(gramRule)

gram.Root = gramRule

questioner.LoadGrammar(New Recognition.Grammar(gram))

End Sub

Private Sub questioner_SpeechRecognized(ByVal sender As Object, ByVal e As System.Speech.Recognition.RecognitionEventArgs) Handles questioner.SpeechRecognized

If e.Result.Text = ("Red") Then

MessageBox.Show("Red")

ElseIf e.Result.Text = ("Green") Then

MessageBox.Show("Green")

ElseIf e.Result.Text = ("Blue") Then

MessageBox.Show("Blue")

End If

End Sub

End Class

Page 120: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 120 2012

19. Structures Applications frequently need to store several pieces of information of different data

types that all relate to one thing and must be kept together in a group, such as a

customer’s name and address (strings) and balance (a number).

Usually, an object of a class is used to hold such a group of variables, but you can

also use a structure.

Structures are similar to class objects but are somewhat simpler, A structure

can even have methods and properties as well as member variables, just as a class

can.

Structures are known as value types and classes are known as reference types.

When you assign and modify a value type, only the contents of the modified variable

change.

When you assign and modify a reference type, the original object changes, so the

original variable and assigned variable change because they both point to the same

original object.

That is, a variable representing a structure means the actual chunk of computer

memory that stores the contents of the structure itself, whereas a variable

representing a class instance is actually, as you have seen, a ‘‘hook’’ on which the

object hangs.

This explains the difference in instantiation — you don’t

need to use the New keyword to instantiate a structure

before you use it because it is a value type, just like an

integer.

Use New when instantiating Reference types –

Classes, Objects etc. (Dim myclass as new class)

Don’t use New when you instantiate value types, -

Variables, Structure etc. (Dim mystructure as

structure)

You do have to use the New keyword with a form or

other complex object because it is a class instance — a

reference type. Also, you cannot inherit from a structure

— another important consideration when choosing

whether to use a class or a structure.

Structures are useful for creating lightweight types that are used to hold data such as

Point, Rectangle and Color types.

Structures are of value type, contrary to classes which are of reference type.

This means that structures are allocated on the stack and are passed to the

methods by value.

Structure may contain constructors (except for a no-argument constructor),

fields, methods and properties just like classes.

Page 121: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 121 2012

Like all value types, Structures can neither inherit other class nor can they be

inherited.

A Structure can implement interfaces.

Like every other type in VB.Net, Structures are also implicitly inherited by the

System.Object class.

Instances of a Structure can be created with or without using the New

keyword.

Most of the .Net framework types such as System.Int32 (for an Integer),

System.Double (for a Double), System.Boolean (for a Boolean), System.Byte

(for a Byte),… are implemented as a Structure.

When kept to a small size, a Structure can be more efficiently used by the

system than a class.

Heap and Stack Performance

Visual Basic programs allocate variables from two pools of memory called the stack

and the heap.

Programs take memory for value types (such as integers and dates) from the stack.

Space for reference types comes from the heap. More than one reference can point

to the same chunk of memory allocated on the heap. That makes garbage collection

and other heap-management issues more complex than using the stack, so using the

heap is generally slower than using the stack.

Because structures are value types and classes are reference types, structures are

allocated on the stack and class objects are allocated on the heap. That makes

structures faster than classes. The exact difference for a particular program depends

on the application.

Page 122: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 122 2012

Structures- Customer Exercise Right-click the project name in the Solution Explorer, choose the Add menu item

from the context menu, and then choose the Class submenu item.

Enter Customer in the Name field and then click the Add button to have this item

added to your project.

In this example, you define a structure using a Structure. End Structure statement.

Inside this block, the variables that make up the structure are declared by name and

type: These variables are called members of the structure:

Create the following.

Here are the names of the objects and

controls on the form and the shape of the

Structure .

The Customer Structure

Public Structure Customer

Public FirstName As String

Public LastName As String

Public Property Freemoney() As Single

Public Property Owes() As Single

Private _balance As Single

Public Property Balance() As Single

Get

Page 123: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 123 2012

_balance += Freemoney - Owes

Return _balance

End Get

Set(value As Single)

_balance = value

End Set

End Property

'Name property

Public ReadOnly Property Name() As String

Get

Return FirstName & " " & LastName

End Get

End Property

ReadOnly Property Email() As String

Get

Return FirstName & "-" & LastName & "@VisionCollege.AC.nz"

End Get

End Property

End Structure

The Form Code

Public Class Form1

Dim myCustomer As Customer

Private Sub btncustomer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncustomer.Click

myCustomer.FirstName = txtFirstName.Text

myCustomer.LastName = txtLastName.Text

myCustomer.Balance = txtaccbalance.Text

myCustomer.Freemoney = txtfreemoney.Text

myCustomer.Owes = txtOwes.Text

'Display the customer

DisplayCustomer(myCustomer)

End Sub

Public Sub DisplayCustomer(ByVal customer As Customer)

'Display the customer details on the form

lblFinalBalance.Text = myCustomer.Balance

lblemail.Text = customer.Email

lblName.Text = customer.Name

lbxCustomer.Items.Add(customer.Name & " " & customer.Balance)

Page 124: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 124 2012

End Sub

End Class

In the btnListCustomer_Click procedure, you define a variable of type Customer

using the Dim statement.

The DisplayCustomer procedure simply accepts a Customer structure as its input

parameter and then accesses the members of the structure to set the Text properties

of the text boxes on the form:

Create a random number generator for Freemoney. Create a full property (with get and set, and place it in the get code using _freemoney as a private variable.

Default structure for properties

A Full Property

Private _balance As Single

Public Property Balance() As Single

Get

‘add code here to change output

Return _balance

End Get

Set(value As Single)

_balance = value

‘add code here to filter input

End Set

End Property

Data comes in through Set(value As Single)

value gets passed to _balance at _balance = value

_balance gets returned back to the program in the Get at Return _balance

Page 125: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 125 2012

Cheque processing using Structure This longer exercise uses a structure to process the details of the customer and

produce an output for a cheque. It has methods in the structure that capitalise and

concatenate the name entered as well as calculate the age of the person.

Right-click the project name in the Solution Explorer, choose

the Add menu item from the context menu, and then choose

the Class submenu item and name it Person. Rename it Public

Structure Person as below.

Public Structure Person

'private member variables for public properties they are underscored for convention, and no other reason, to show that they are private, so only work inside the person structure -----------

Private _firstname As String

Private _middlename As String

Private _lastname As String

Private _dob As Date

'private member vars for calculations in this case making a timespan---------------

Private _datedif As TimeSpan

'------------- public properties ---------------

Public Property FirstName As String

Get

'------------- This is the function propercase from below ---------------

Return ProperCase(_firstname)

End Get

Set(ByVal value As String)

_firstname = value

End Set

End Property

Public Property MiddleName As String

Get

Return ProperCase(_middlename)

Page 126: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 126 2012

End Get

Set(ByVal value As String)

_middlename = value

End Set

End Property

Public Property LastName As String

Get

Return ProperCase(_lastname)

End Get

Set(ByVal value As String)

_lastname = value

End Set

End Property

Public Property DOB As Date

Get

Return _dob

End Get

Set(ByVal value As Date)

_dob = value

End Set

End Property

'------------- readonly properties ---------------

ReadOnly Property Fullname As String

Get

Return ProperCase(_firstname.Trim & " " & _middlename.Trim & " " & _lastname.Trim)

End Get

End Property

ReadOnly Property ChequeName As String

Get

'returns the GetChequeName()

Return GetChequeName()

End Get

End Property

ReadOnly Property Age As Integer

Get

' calculate the number of days different

_datedif = Date.Now - DOB

' return this in years

Return _datedif.Days / 365

End Get

End Property

Page 127: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 127 2012

'------------- methods ---------------

' the ChequeName is with first and middle names as capital initials and a fullstop

' the last name in Proper form (first letter capital, all others lowercase)

Private Function GetChequeName() As String

Dim strFirstAndMiddle As String = _firstname.Trim & " " & _middlename.Trim

Dim theNames() As String = strFirstAndMiddle.ToLower.Split(" ")

Dim j As Short

Dim aName As String = ""

' now change first and middle names to capital initials plus ". "

For j = 0 To theNames.Length - 1

aName = theNames(j)

theNames(j) = aName.ToUpper.Substring(0, 1) & ". "

Next

aName = "" ' need to use this again so make it empty

' concatenate the names

For Each strFirstAndMiddle In theNames

aName &= strFirstAndMiddle

Next

' capitalize first letter of last name by using the Proper function

strFirstAndMiddle = ProperCase(_lastname)

Return aName.Trim & " " & strFirstAndMiddle.Trim

End Function

' this function is public so can process and return the middle names to the program

' this has been done like a method deliberately so that it can be used in the program

Function GetMiddleNames() As String

Return ProperCase(_middlename)

End Function

'This function capitalises the first letter of the string passed through

Private Function ProperCase(ByVal strwords As String) As String

' take a string and capitalize first letter of each word

Dim theWords() As String = strwords.Split(" ")

Dim temp As String = "", left As String = "", right As String = ""

Dim j As Short

' go through all words, split off first letter and capitalize it

' make the rest of the word lower case

Page 128: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 128 2012

' replace the words in the array

For j = 0 To theWords.Length - 1

temp = theWords(j)

left = temp.ToUpper.Substring(0, 1)

right = temp.ToLower.Substring(1, temp.Length - 1)

theWords(j) = left & right

Next

' get ready to return name by concatenating all names in theWords array

left = ""

For Each temp In theWords

left &= temp & " "

Next

' now return it

Return left.Trim

End Function

End Structure

Public Class Form1

Private Sub btnProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProcess.Click

Dim myPerson As Person

myPerson.FirstName = txtFirstname.Text

myPerson.MiddleName = txtMiddlename.Text

myPerson.LastName = txtLastname.Text

myPerson.DOB = dtpDOB.Value

lblage.Text = myPerson.Age.ToString

lblFullName.Text = myPerson.Fullname

lblMiddleName.Text = myPerson.GetMiddleNames

lblChequeName.Text = myPerson.ChequeName

End Sub

End Class

Page 129: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 129 2012

20. Using Snippets for VB.net to auto create the Class

properties This is really important as it saves you having to type manually and repetitively the

basic code for a class or Structure property

To create the property do this ….

Type prop and press tab you get this

(If you are lucky it gives you the full property with Get and Set, but

unfortunately not for me)

Fill it in with your name and type Property Firstname() As String

Type in get underneath it

Press the Enter key

Voodoo happens - all the properties self generate

Add your private variables by hand (sadly)

Type in propdef to see a full property

Page 130: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 130 2012

Go Tools / Code Snippets Manager to see all the snippets.

http://msmvps.com/blogs/deborahk/archive/2010/04/11/auto-implemented-

properties.aspx

Page 131: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 131 2012

21. Introduction to Classes Object-Oriented Programming (OOP) is a method of software design and

construction and is the next logical progression, after structured programming, to

improve your code reusability and maintainability.

Put another way, OOP is a method of designing individual software components

(classes) with associated behaviours (methods) and data limitations (properties), and

that helps you piece these components together to create a complete application.

The modern trend in programming languages is for code to be separated into

chunks. When it's being used, each chunk of code (a chunk of code that opens text

files, for example) is known as an Object. The code for the Object can then be

reused whenever it is needed.

Languages like C++ and Java are Object Oriented languages. Until Microsoft came

out with VB.NET, the Visual Basic programming language was not OOP (object

oriented programming. The NET Framework is a whole lot of Classes (called

Namespaces) and the technology to get those Classes to work.

The best thing about OOP is that it allows you to group data into discrete variables

contained within a class in your program. This data is separate and distinct from any

other class in your application. No class can interfere with the data in any other class

without going through a specific interface on that class.

Object Oriented programming has a steeper learning curve, and things like

Encapsulation, Inheritance and Polymorphism have to be digested. Classes are the

heart and soul of an object-oriented language. You will find yourself using classes

whenever you write even the simplest of programs in Visual Basic .NET.

In VB.NET, a class is that chunk of code mentioned earlier. The Form you've started

out with is a Class. If you look right at the top of the code window for a Form, you'll

see:

Public Class Form1

End Class

The word "Public" means that other code can see it. Form1 is the name of the Class

At the bottom of the coding window, you'll see End Class, signifying the end of the

code for the Class.

When you place a Button or a textbox on the Form, you're really adding it to the Form

Class.

When you start the Form, VB does something called instantiation. This basically

means that your Form is being turned into an Object, and all the things needed for

the creation of the Form are being set up for you (Your controls are being added,

variables are being set up an initialised, etc).

And that's the basic difference between a Class and an Object: A Class is the code

itself; the code becomes an Object when you start using it. The big benefit of an

Page 132: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 132 2012

Object Oriented Programming language is that you can create your own Objects. (It's

an Object when you're using the code, remember, and a Class when you're not.)

For example the instructions for doing a pressup are:

Both hands on the floor, and at chest height,

Back straight,

Down to upper arms are horizontal and up to elbows are locked.

These instructions are the Class, and every time you do a pressup you create an

object. If you didn’t have a class then before every pressup you would have to read

the rules again and define them. Now that you have a class, you can just refer back

to the class (instructions) and away you go, pumping out new objects.

A class is also like an octopus.

Remember when we made the telecom project (which we will work on again) we had

to define all the variables

Public Class Form1

Dim strplan As String

Dim sngMonthlycharge As Single

Dim sngIncminutes As Single

Dim sngAdddata As Single

Each of these variables are unrelated to the other. There is also no easy way to

organize them so that they are in related groups. They are just individual variables

that can get confusing in big projects.

In a class they will all be together and seen as a unit.

A Namespace is a group of Classes which are grouped together. The System.IO

Namespace you met earlier groups together Classes that you use to read and write

to a file. System.Windows.Forms is another Namespace you've met. In fact, you

couldn't create your forms without this Namespace. But again, it is just a group of

Classes huddling under the same umbrella.

Read the official documentation here http://msdn.microsoft.com/en-

us/library/zzh9ha57.aspx

OOP terms

Class A container for data and code. The data within the class can be accessed with properties. The code is referred to as methods.

Object An instance of a class in memory. An instance is created using a Dim statement and the New keyword.

Constructor A procedure that is automatically invoked when an object is first instantiated. In Visual Basic 6.0, the constructor was called Class_Initialize. In Visual Basic .NET the constructor is called New.

Destructor A procedure that is automatically invoked when an object is destroyed. In Visual Basic 6.0, the destructor was called Class_Terminate. In Visual Basic .NET, the destructor is called Finalize.

Properties A routine exposed by an object to expose data, and to allow

Page 133: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 133 2012

code outside the object to affect the objects data.

Method An action that can be performed by an object. In Visual Basic .NET, methods are defined as Subs and Functions.

Creating a simple class Let’s use our Thermometer Example as a way to create a simple class.

The class name will be temperature.

To create a class right click on Project name choose Add choose New

Item, choose Class, and save as temperature.

Note: the below may have changed on your computer – now there is a new shortcut

for properties http://msdn.microsoft.com/en-us/library/dd293589.aspx

Auto-implemented properties enable you to quickly specify a property of a class

without having to write code to Get and Set the property.

Get means to Get the value of the property. While Set means to Set the value of the property. Think of Get and Set from the viewpoint of the property, not the main code.

When you write code for an auto-implemented property, the Visual Basic compiler

automatically creates a private field to store the property variable in addition to

creating the associated Get and Set procedures.

With auto-implemented properties, a property, including a default value, can be

declared in a single line. http://msdn.microsoft.com/en-us/library/dd293589.aspx

Lets do them the old way until you get the hang of it.

The old way ….

Page 134: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 134 2012

Temperature Converter with a Class We are going to create a class to hold all the variables of the Temperature project we

did earlier.

Public Class temperature

‘These are private variables, they are only workers for use within the class, you don’t see them outside the class.

Private _sngfah As Single

Private _sngcel As Single

Private _snginput As Single

Public Property snginput() As Single

Get

Return _snginput

End Get

Set(ByVal value As Single)

_snginput = value

End Set

End Property

Private _sngfah as single

Public Property sngfah() As Single

Get

'put your calculations in here

_sngfah = (snginput - 32) * 5 / 9

Return _sngfah

End Get

Set(ByVal value As Single)

_sngfah = value

End Set

End Property

End Class

Do the same for sngcel as well. Add in below to the property of sngcel using the

structure above.

Get

'put your calculation here

_sngcel = snginput * (9 / 5) + 32

Page 135: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 135 2012

Return _sngcel

End Get

Rewrite your main code as such.

Private Sub btnsubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsubmit.Click

'instantiate a new class from

Dim temp As New temperature

temp.snginput = txttemp.Text

If RadioButton1.Checked Then

lbloutput.Text = temp.snginput & " Farenheit is equal to " & temp.sngcel & " Celsius"

ElseIf RadioButton2.Checked Then

lbloutput.Text = temp.snginput & " Celsius is equal to " & temp.sngfah & " Fahrenheit"

End If

End Sub

Turn snginput into a string so that you can catch errors in the class with IsNumeric. Otherwise it has to be placed on the form.

Make Sngcel and Sngfah write only properties.

Finally make a method that shows the text of ice, if < 1, warm, if < 100 and Steam if > 100 back on the form.

So what use is this? All it does is make it harder to define the variables!

But wait, OOP allows you to create classes, blocks of data, that can stand

independent of each other, and be ‘plugged in’ to your program containing or

“encapsulating” all that you need.

Although we now have snginput we don’t want this line temp.snginput =

txttemp.Text in our class in case in the future the text box changes name.

It’s just like plugging in a new system to an existing one.

Page 136: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 136 2012

Fields, Properties, Methods, and Events Fields, Properties, Methods, and Events are called the members of a class. Inside

the class, members are declared as either Public, Private, Protected, Friend, or

Protected Friend:

A class defines properties, methods, and events that let the program work with the

class:

➤ A property is some sort of data value. It may be a simple value (such as a name

or number), or it may be a more complex item (such as an array, collection, or object

containing its own properties, methods, and events).

➤ A method is a subroutine or function. It is a piece of code that makes the object

defined by the class do something.

➤ An event is a notification defined by the class. An event calls some other piece of

code to tell it that some condition in a class object has occurred.

The fields of a class, also called the class's data members, are much like built-in

variables (although they also may be constants).

For example, I can declare a field named value to the DataClass class we just saw

by declaring a variable with that name:

Public Class DataClass

Public value As Integer

End Class

Now I can refer to that field in an object of this class using the familiar object.field

syntax of Visual Basic:

Dim data As New DataClass()

data.value = 5

Using fields like this can give you direct access to the data stored inside an object,

and that's unusual in OOP because you usually want to check the data being stored

in your objects to make sure it's legal first.

An easy way of guarding access to the data in your objects is to use properties.

Properties are retrieved and set like fields, but are handled with the Property Get

and Property Set procedures, which provide more control on how values are set or

returned.

Using properties provides you with an interface to set or get the value of data internal

to an object. You declare properties using Get and Set procedures in a Property

statement

Get Starts a Get property procedure used to return the value of a property. Get blocks are optional unless the property is ReadOnly.

End Get Ends a Get property procedure.

Set Starts a Set property procedure used to set the value of a property. Set

Page 137: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 137 2012

blocks are optional unless the property is WriteOnly. Note that the new value of the property is passed to the Set property procedure in a parameter named Value when the value of the property changes.

End Set Ends a Set property procedure.

Naming Classes and Methods

Classes and objects should have noun or noun phrase names like Customer,

Account, and AddressParser. Avoid words like Manager, Processor, Data, or Info

in the name of a class. A class name should not be a verb.

Methods should have verb or verb phrase names like postPayment, deletePage, or

save. Accessors, mutators, and predicates should be named for their value and

prefixed with get, set, and is according to the javabean standard

string name = employee.getName

customer.setName("mike")

if paycheck.isPosted...

22. Encapsulation A class’s public interface is the set of properties, methods, and events that are

visible to code outside of the class. The class may also have private properties,

methods, and events that it uses to do its job.

The class encapsulates the programming abstraction that it represents. Its public

interface determines what is visible to the application outside of the class. It hides the

ugly details of the class’s implementation from the rest of the world. Because the

class hides its internals in this way, encapsulation is also sometimes called

information hiding.

By hiding its internals from the outside world, a class prevents exterior code from

messing around with those internals. It reduces the dependencies between different

parts of the application, allowing only those dependencies that are explicitly permitted

by its public interface. Removing dependencies between different pieces of code

makes the code easier to modify and maintain. Removing dependencies also helps

break the application into smaller, more manageable pieces.

The simpler and cleaner a class’s public interface is, the easier it is to use. You

should try to hide as much information and behavior inside a class as possible while

still allowing the rest of the program to do its job. Keep properties, methods, and

events as simple and focused as possible.

When you write code that the class needs to use to perform its duties, do not expose

that code to the outside program unless it is really necessary. Adding extra features

complicates the class’s public interface and makes the programmer’s job more

difficult.

Page 138: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 138 2012

This can be a troublesome concept for beginning programmers. Exposing more

features for developers to use gives them more power, so you might think it would

make their jobs easier.

Actually, it makes development more difficult. Rather than thinking in terms of giving

the developer more power, you should think about giving the developer more things

to worry about and more ways to make mistakes. Ideally, you should not expose any

more features than the developer will actually need.

Use the following to show or hide your code from the users.

Public Gives variables public access, which means there are no restrictions on their accessibility.

Private Gives variables private access, which means they are accessible only from within their class, including any nested procedures.

Protected Gives variables protected access, which means they are accessible only from within their own class or from a class derived from that class. Note that you can use Protected only at class level (which means you can't use it inside a procedure), because you use it to declare members of a class.

Friend Gives variables friend access, which means they are accessible from within the program that contains their declaration, as well as anywhere else in the same assembly.

Protected Friend

Gives variables both protected and friend access, which means they can be used by code in the same assembly, as well as by code in derived classes.

Page 139: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 139 2012

Dice program with Classes - revisited

The class file

Imports System.Random

Public Class Dice

Private _dice As Integer

Public Property newdice() As Integer

Get

Randomize()

_dice = Int(1 + 6 * Rnd())

Return _dice

End Get

Set(ByVal value As Integer)

_dice = value

End Set

End Property

End Class

The Main form

Private Sub btnRoll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRoll.Click

Dim Dice1 As Dice = New Dice

Dim Dice2 As Dice = New Dice

Dim newdice1, newdice2 As Integer

Dim storage As String

Dim stopValue As Short

Dim dblCount As Short

' empty the listbox

lbDiceRolls.Items.Clear()

' get the stop value (number to stop when double is found)

stopValue = cbStopOn.Text

Page 140: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 140 2012

' now roll the dice until we get the correct double

Do

newdice1 = Dice1.newdice()

newdice2 = Dice2.newdice()

' make the string to be added to the lisbox

storage = newdice1 & " " & newdice2

' check if it's a double

If newdice1 = newdice2 Then

storage &= " Double!"

dblCount += 1

End If

' put this into the listbox

lbDiceRolls.Items.Add(storage)

Loop Until (newdice1 = newdice2) And (newdice2 = stopValue)

' display totals

lblTotals.Text = "It took " & lbDiceRolls.Items.Count & " rolls to get double " & stopValue

lblDubtotals.Text = "I got " & dblCount & " doubles along the way"

End Sub

End Class

Take all of the variables from the form, and turn them into fields in the class so that there are no Dim’s on the form at all.

Page 141: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 141 2012

23. Inheritance – “Is a” Inheritance is the process of deriving a child class from a parent class (or base

class). The child class inherits all of the properties, methods, and events of the

parent class. It can then modify, add to, or subtract from the parent class.

Making a child class inherit from a parent class is also called deriving the child class

from the parent, and subclassing the parent class to form the child class.

One of the key benefits of inheritance is code reuse. When you derive a class

from a parent class, the child class inherits the parent’s properties, methods, and

events, so the child class gets to reuse the parent’s code. Code reuse not only saves

you the trouble of writing more code but also makes maintenance of the code easier.

Similarly, if you need to modify or delete a property or method, you need to make the

change only in the class where it is defined, not in all of the classes that inherit it.

Parent or Base

class

Child or Derived

classes

Page 142: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 142 2012

Weapons Practice – Class, Inheritance, Constructor This exercise creates a class of weapons, rifle, revolver, bazooka, and each

weapon has its own properties.

The constructor allows you to preset the properties of the class with data. So when

its instantiated it comes complete with its own values.

There already a default Constructor already set in your Class, but you can override it

and set your own Constructor using Sub New().

This exercise also uses the Class modifier of Protected. Protected

means that elements are accessible only from within their own class

or from a derived class.

In this case we have the main Class – weapon, and other derived

classes such as rifle, Bazooka and revolver.

Before you code the form you need to create the classes and their Fields, Properties,

and Methods.

Page 143: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 143 2012

The base class - weapon

Public Class Weapon

'This is the base class for the three derived classes which are used in the program make these member variables Protected rather than Public = can be seen from anywhere. Private = can only see in the base class. I need to use these variables in the derived classes

‘---- Fields ------

Protected _bullets As Short

Protected _name As String

Protected _sound As String

Protected _fullLoad As Short

Protected _defaultSound As String

'---- default Constructor

Sub New()

' set the defaults

_fullLoad = 0

_bullets = _fullLoad

_name = ""

_sound = ""

_defaultSound = ""

End Sub

'There is no way to change the value for these properties from the program - they're changed within the class so we have made them ReadOnly...

‘---- Properties ----

Public ReadOnly Property Name() As String

Get

Return _name

End Get

End Property

Public ReadOnly Property Sound() As String

Get

Return _sound

End Get

End Property

Public ReadOnly Property Bullets() As Short

Get

Return _bullets

End Get

End Property

'This fills the magazine for the selected weapon with ammunition - different for each type of weapon. The _fullLoad and _defaultSound values are overridden in the derived class constructor.

Public Sub Reload()

_bullets = _fullLoad

Page 144: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 144 2012

_sound = _defaultSound

End Sub

'Fire the weapon and reduce the amount of ammunition by 1 if we have no more ammunition, change the sound to "Click"

‘---- Methods ----

Public Sub Fire()

If _bullets > 0 Then

_bullets -= 1

Else

_sound = "Click"

_bullets = 0

End If

End Sub

End Class

Derived class – Revolver

Note that it inherits all the properties of the weapons class and modifies them with

Inherits Weapon

Public Class Revolver

Inherits Weapon

' override the default constructor

Sub New() ' set the defaults

_fullLoad = 6

_defaultSound = "Blam"

_bullets = _fullLoad

_name = "Revolver"

_sound = "Blam"

End Sub

End Class

Derived class – Rifle

Public Class Rifle

Inherits Weapon

' override the default constructor

Sub New() ' set the defaults

_fullLoad = 15

_defaultSound = "Bang"

_bullets = _fullLoad

_name = "Rifle"

_sound = "Bang"

End Sub

End Class

Derived class – Bazooka

Public Class Bazooka

Inherits Weapon

' override the default constructor

Sub New() ' set the defaults

Page 145: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 145 2012

_fullLoad = 1

_defaultSound = "Boooom"

_bullets = _fullLoad

_name = "Bazooka"

_sound = "Boooom"

End Sub

End Class

The main form

Note that we call each class in the code to pass through it properties. There is no

difference in runtime between the two ways of declaring the weapon.

Dim myWeapon As New Weapon ‘instantiate a new object myWeapon

myWeapon = New Revolver ‘change myWeapon to the Revolver class

myWeapon = New Bazooka

myWeapon = New Rifle

Public Class frmMain

Dim myWeapon As New Weapon

Private Sub btnFire_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFire.Click

'Fire the weapon and update the display with the weapon's sound

myWeapon.Fire()

lblNoise.Text = myWeapon.Sound

lblshotsleft.Text = myWeapon.Bullets

End Sub

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click

Me.Close()

End Sub

Private Sub btnReload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReload.Click

'Reload the magazine for this weapon and update the display

myWeapon.Reload()

UpdateDisplay()

lblNoise.Text = ""

End Sub

Private Sub rbRevolver_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rbRevolver.CheckedChanged, rbBazooka.CheckedChanged, rbRifle.CheckedChanged

'Set the weapon to a revolver and update the display with no noise (no shots fired yet!) Above should be

Page 146: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 146 2012

Dim gun As New RadioButton

gun = sender

Select Case gun.Text

Case "Revolver"

myWeapon = New Revolver

Case "Bazooka"

myWeapon = New Bazooka

Case "Rifle"

myWeapon = New Rifle

End Select

UpdateDisplay()

lblNoise.Text = ""

End Sub

Private Sub UpdateDisplay()

'This updates what is seen on the screen the noise will be either nothing or the default noise for that weapon, or click if the weapon is out of ammunition

Me.Text = myWeapon.Name

lblshotsleft.Text = myWeapon.Bullets

'Can't allow these buttons to be pressed until a weapon has been chosen

btnFire.Enabled = True

btnReload.Enabled = True

End Sub

End Class

Add a Bow and Arrow, and a Gattling Gun to the weapon list.

Page 147: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 147 2012

24. Inheritance based Polymorphism Polymorphism in software engineering means that you can have two classes with

different code, but with a common set of methods, properties, or events.

For example the purpose of the Weapon class is to provide a common base from

which other classes can be derived (Revolver, Bazooka etc). Each of these child

classes exhibit polymorphism because it can be treated using methods common to

its parent Weapon.

To implement polymorphism using inheritance, you do not need to use an abstract

base class. Any base class that provides overridable methods (using either the

MustOverride or Overridable keywords) will work fine, as all its subclasses are

guaranteed to have that same set of methods as part of their interface, and yet the

subclasses can provide custom implementation for those methods.

If we add Overridable to the fire sub of the Weapons class

' fire the weapon and reduce the amount of ammunition by 1

' if we have no more ammunition, change the sound to "Click"

Public Overridable Sub Fire()

If _bullets > 0 Then

_bullets -= 1

Else

_sound = "Click"

_bullets = 0

End If

End Sub

Add Overrides to the fire method of a child class such as Bazooka.

The code in the Bazooka fire method will then be used instead of the code in the

Weapon fire method.

Public Overrides Sub Fire()

If _bullets > 0 Then

_bullets -= 1

Else

_sound = "Pfwupp!"

_bullets = 0

End If

End Sub

Now you can change the code in any child method by just adding override to the first

line. That method is used instead of the parent method when myweapon.fire is called

in the code.

Page 148: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 148 2012

Depreciation Rate calculator with Class Using the Depreciation Rate calculator from the earlier lesson convert it to classes

and use it with 5 computing systems chosen from the list below. Create a base class

and derived classes.

Class Diagram Practice Assignments using noun analysis Create a class diagram from the following descriptions use the noun analysis

method. If you look in the "problem statement" for nouns, they will often wind up

as classes. If you look for verbs, they will be methods of those classes.

A simple example of a problem statement might be:

We are a training facility. We need to be able to track the classes that students take. Classes are taught by teachers. Students enrol in classes. Each class is assigned to one teacher and one classroom.

So, we have classes, students, teachers and classrooms. Class will have methods

like AssignTeacher and AssignClassroom. Students will have Enrol. Of course, there

is more, such as how to handle the time of each class, and so on.

Page 149: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 149 2012

Note that you should find at least one situation where inheritance is involved.

Create a class diagram, clearly showing each class, their relationships (including

their multiplicity). Attributes and methods need not be shown (unless you want)

The students at Vision College are enrolled in one or more courses. The available courses are Software Engineering, Web Programming and Design, Business Computing and English studies.

It is possible for students to be enrolled in more than one course at the same time, although if more than one course of study is undertaken it is usual that these should be English studies and any one other course, but this isn’t set in concrete as a student may enrol in day and night classes of any type simultaneously.

Each course is held in one classroom. Courses have one tutor and one classroom. Students must complete assessments for each course.

Our company “DVDs4ALL” has DVD movies, which are hired by our members.

Membership is one of the following: Ordinary, Junior or Gold. The hire rates and privileges for each membership type is different. We need to know details about who has hired what, when and for how long as well as how much has each member spent. We need to be able to look at overdue hires at any time.

The Insurance Assessor Company employs contracted Adjusters who are given claims. Claims come from insurance companies. The Adjusters visit and inspect the damage, write a report to the insurance company and after approval, organise repairs.

Page 150: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 150 2012

The Coffee machine– Class Inheritance and Constructor This Exercise uses a main class and inherited classes to create a coffee machine

that dispenses types of coffee.

This uses a main class of drink, with default properties and derived classes of Flat

White, Long Black, Short Black, Expresso, Latte, Cappuccino, Vienna, Chocolate.

People can choose a machine cup or a customer cup. The water levels alter with

water values doubling for a customer cup (as they are much bigger). See the left

image for the setup.

People can choose sugar to a max of 4 and using sugar also releases a spoon to stir

it with the sugar icon on the left pic in the middle showing.

Public Class drink

Protected _drinkname As String

Protected _portion As Integer 'how strong X spoonfulls of coffee or chocolate - Default

Protected _sugar As Integer ' do they want sugar? - User choice

Protected _whitener As Integer ' whitener - fake milk - Default

Protected _spoon As Boolean 'do they get a spoon? If they have sugar - Default

Protected _cup As Boolean 'do people need a cup? - override size for personal cup - User choice

Protected _grinder As Boolean 'does it need grinding? - Default

Protected _water As Integer ' expressos use one water long black 2 - Default

Protected _chocsprinkle As Boolean ' do you get a chocolate sprinkle on it - Default

Protected _milkfroth As Boolean 'do you froth up the milk - Default

Protected _decaf As Boolean '- User choice

Page 151: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 151 2012

Public Sub New()

'set up defaults

_drinkname = "Default"

_portion = 1

_sugar = 0

_whitener = 0

_spoon = False

_cup = True 'machine cup

_grinder = False

_water = 1

_chocsprinkle = False

_milkfroth = False

_decaf = False

End Sub

Page 152: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 152 2012

Derived Classes

Name Portion -Coffee

Whitener Water Chocsprinkle Milkfroth Grinder

Long Black 2 2 T

Short Black 2 1 T

Latte 2 2 2 T T

Cappuccino 1 1 2 T T

Vienna 2 2 T

Chocolate 0 2 2 T T

Example of derived classes

Public Class longblack

Inherits drink

Private _longblack As Boolean

Public Sub New()

_drinkname = "Long Black"

_portion = 2

_water = 2

_grinder = True

End Sub

End Class

Two main subs on the form.

Sub drinktype()

Select Case drinkselect

Case 1

drink = New flatwhite

Case 2

drink = New longblack

Case 3

drink = New shortblack

Case 4

drink = New expresso

Case 5

drink = New Latte

Case 6

drink = New cappuccino

Case 7

drink = New vienna

Case 8

drink = New chocolate

End Select

drinkOptions()

If drink.drinkname = "Chocolate!" Then

btndecaf.Visible = False

lbldecaf.Visible = False

Label1.Visible = False

Page 153: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 153 2012

Else

btndecaf.Visible = True

lbldecaf.Visible = True

Label1.Visible = True

End If

pbspoon.Visible = False'reset the spoon image to false

btncup.Text = "Machine cup"'set the button for cup to default

lblcustcup.Visible = False

End Sub

Sub drinkOptions()

lblname.Text = drink.drinkname

lblportion.Text = drink.portion

lblsugar.Text = drink.sugar

lblwhitener.Text = drink.whitener

lblspoon.Text = drink.spoon

lblcup.Text = drink.cup

lblgrinder.Text = drink.grinder

lblwater.Text = drink.water

lblchoc.Text = drink.chocsprinkle

lblmilkfroth.Text = drink.milkfroth

lbldecaf.Text = drink.decaf

pbcup.Visible = False

End Sub

Page 154: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 154 2012

Create the drink from the ingredients Classes To make part 2 show use form2.Show() to load the second form.

To make this I used a system of numbers of 1, 2, 4, 8, 16, 32, 128. Each number is

assigned to an option eg: 1 coffee = 1, 2 coffee = 2, 1 water = 4, 2 water = 16 etc

Combinations of ingredients then result in a unique number that is then given a

name. 2 + 4 = 6. = Short Black.

Page 155: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 155 2012

25. Importing Text into your Program One of the basic tools we need to use is the ability to get stuff into your program and

send it out at the end. There are a number of ways to access information, such as

Database, web access, or text files. We will start with a simple text file.

Using a combo box load some file paths in via the Collections (see image below).

This gives you a range of files to use.

Firstly we need to import System.IO. Imports are for adding namespaces that hold

extra information and functionality for your program. You just “Import” them in at the

beginning of the code and then you can use the objects in your code.

Make sure you have the three files in your C drive or use some of your own files and

just call their names.

In your ComboBox add the paths to your files in the Items

Collection.

Page 156: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 156 2012

The File class – simple read and write data to text files Needs Imports System.IO

File.ReadAllBytes: Useful for files not stored as plain text. You

can open images or movies with this method.

File.ReadAllLines: Microsoft: "Opens a file, reads all lines of the

file with the specified encoding, and closes the file."

File.ReadAllText: Returns the contents of the text file at the

specified path as a string. Useful for plain text or settings

files. This method opens a file, reads each line of the file, and

then adds each line as an element of a string. It then closes the

file.

For simplicity, this is the best method to use. More advanced methods can be used

to read files in line-by-line, which may be more efficient if you have a very large file.

Dim value As String = File.ReadAllText(path)

txtdata.Text = value

File.WriteAllBytes: Useful for files such as images that were created or mutated in

memory.

File.WriteAllLines: Stores a string array in the specified file, overwriting the

contents.

File.WriteAllText: Writes the contents of a string to a text file. One of the simplest

ways to persist text data.

File.AppendAllText: Use to append the contents string to the file at path. Microsoft:

"Appends the specified string to the file, creating the file if it doesn't already exist."

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

Imports System.IO

Public Class Form1

Dim strpath As String

'Using File.ReadAllText

Private Sub btntext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btntext.Click

strpath = cbpath.Text

'clear the data in the textbox

txtdata.Clear()

Try 'copy the file into the textbox

Dim value As String = File.ReadAllText(strpath)

txtdata.Text = value

Catch ex As Exception 'catch errors

Page 157: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 157 2012

MsgBox("Check that the filename is correct")

End Try

End Sub

StreamReader - importing to a ListBox StreamReader is designed for character input in a particular encoding. Use

StreamReader for reading lines of information from a standard text file.

Using a Using to End Using means you don’t have to open and close the

StreamReader.

See that StreamReader is loading the data in line by line, then each line is looped

into a ListBox. The StreamReader stops when it reaches the end, and you can use a

number of ways to determine that.

Private Sub btnlist_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlist.Click

lbdata.Items.Clear()

strpath = cbpath.Text

' Open file.txt with the Using statement.

Using SR As StreamReader = New StreamReader(strpath)

' Store contents in this String.

Dim line As String

' Read first line then enter the loop.

line = SR.ReadLine

' Loop over each line in file, While list is Not Nothing.

Do While (Not line Is Nothing)

lbdata.Items.Add(line)

' Read in the next line.

line = SR.ReadLine

Loop

End Using

End Sub

StreamReader has heaps of interesting methods, so try some out

http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx

Try this: Replace the Do While with the Do Until

' Do While (Not line Is Nothing)

Do Until SR.EndOfStream

Page 158: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 158 2012

Saving with StreamWriter Create a new button, Btnsave and add the following code. First load the Lbdata

before saving.

StreamWriter writes data to a text file. It is easy to use. Ideally it should be used

inside a VB.NET Using statement. This ensures the correct disposal of its resources.

This writes from the ListBox, note that we have to iterate through each item in the

ListBox

Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click

Dim strpathout As String = txtpathout.Text

Using writer As StreamWriter = New StreamWriter(strpathout)

'for the items in the list box

For i = 0 To lbdata.Items.Count - 1

writer.WriteLine(lbdata.Items.Item(i))

Next

End Using

End Sub

This writes from the TextBox

Using writer As StreamWriter = New StreamWriter(strpathout)

writer.Write(txtdatain.Text)

End Using

Page 159: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 159 2012

26. Using OpenFile Dialog and SaveFile Dialog If you want to open documents from other paths then you can use the Open File

Dialog to find that path. After which you can then pass the path to the StreamReader

and work on it.

Drag an Open File Dialog from the dialogs bar into your form. It will nest at the

bottom.

Imports System.IO

Public Class Form1

Private Sub btnopen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnopen.Click

lbltext.Text = "" 'clear the data in the textbox

OpenFileDialog1.Title = "Please Select a File"

OpenFileDialog1.InitialDirectory = "C:"

OpenFileDialog1.ShowDialog()

End Sub

Page 160: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 160 2012

Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk

Dim strm As System.IO.Stream 'the data stream

Dim strpath As String ' path to the file

Dim strtext As String 'Holds the file opened

strm = OpenFileDialog1.OpenFile()

'show the path of the file in the form

txtpath.Text = OpenFileDialog1.FileName.ToString()

strpath = OpenFileDialog1.FileName.ToString()

If Not (strm Is Nothing) Then

'insert code to read the file data STREAMREADER BELOW

Try 'copy the file into the textbox

strtext = File.ReadAllText(strpath)

lbltext.Text = strtext

Catch ex As Exception 'catch errors

MsgBox("Check that the filename is correct")

End Try

strm.Close() 'close the streamreader

End If

End Sub

End Class

Save the file using Save File Dialog. Create a Btnsave first

and stick it under that.

There are many handy options on the properties window for the dialog.

Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click

SaveFileDialog1.ShowDialog()

End Sub

Private Sub SaveFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles SaveFileDialog1.FileOk

Dim FileToSaveAs As String = SaveFileDialog1.FileName

Dim objwriter As New System.IO.StreamWriter(FileToSaveAs)

objwriter.Write(lbltext.Text)

objwriter.Close()

End Sub

Page 161: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 161 2012

Creating a shopping List Create a text file with food items. Load it into a list box. Then using buttons move the

items from one list box to another.

Save the new list to another text file by using a button.

Make sure you use error protection.

Code that you might need

lbclientlist.Items.Add(lbmasterlist.SelectedItem)

Page 162: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 162 2012

27. Add Menus and Tool Strip to your project Get more from beginning MS visual basic.pdf

In the Toolbox find menus and Toolbars and drag the

MenuStrip to the top of your form

In the MenuStrip type in the files you want as seen right.

Double click on the Menu name to open the code window

that activates on menu item click and add your code.

Private Sub LoadFileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadFileToolStripMenuItem.Click

MsgBox("this is the Load menu")

End Sub

Private Sub ShowTextBoxToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShowTextBoxToolStripMenuItem.Click

txtdata.Visible = True

End Sub

It’s That easy!!!!

Add Toolstrip by dragging it to the form, then Right click,

choose Insert Standard items, and edit them as you wish

World’s greatest bands

Public Class Form1

Private Sub mnuTheWho_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuTheWho.Click

lblDisplay.Text = "Roger Daltrey" & vbCrLf & "John Entwistle " & vbCrLf & "Keith Moon" & vbCrLf & "Pete Townshend" & vbCrLf & "Dave Mackintosh - Drums" & vbCrLf & "The Who have sold about 100 million

Page 163: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 163 2012

records, and have charted 27 top forty singles in the United Kingdom and United States, as well as 17 top ten albums, with 18 Gold, 12 Platinum and 5 Multi-Platinum album awards in the United States alone."

If MessageBox.Show("Do you like The Who?", "The Who Survey", MessageBoxButtons.YesNo) = DialogResult.Yes Then

MessageBox.Show("The Who are Awesome!")

Else

MessageBox.Show("Maybe you've never heard of The Who?")

End If

End Sub

Private Sub mnuClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuClose.Click

Application.Exit()

End Sub

'Executes when the About menu is selected

Private Sub mnuAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAbout.Click

AboutForm.Show() 'Opens the About Form

Me.Hide() 'Hides the Main form for later use.

End Sub

Private Sub mnuLedZepplin_Click(sender As Object, e As EventArgs) Handles mnuLedZepplin.Click

lblDisplay.Text = _

"Jimmy Page - Lead Singer" & vbCrLf & _

"John Bonham" & vbCrLf & _

"Robert Plant" & vbCrLf & _

"John Paul Jones" & vbCrLf & _

"They are widely considered to be one of the most successful, innovative and influential rock groups in history."

If MessageBox.Show("Do you like Led Zepplin?", "Led Zepplin Survey", MessageBoxButtons.YesNo) = DialogResult.Yes Then

MessageBox.Show("Led Zepplin are Awesome!")

Else

MessageBox.Show("Maybe you've never heard of Led Zepplin?")

End If

End Sub

Private Sub mnuRollingStones_Click(sender As Object, e As EventArgs) Handles mnuRollingStones.Click

lblDisplay.Text = _

"Mick Jagger" & vbCrLf & _

"Keith Richards" & vbCrLf & _

"Ronnie Wood" & vbCrLf & _

"Charlie Watts" & vbCrLf & _

"Critical acclaim and popular consensus has accorded them the title of the World’s Greatest Rock and Roll Band"

If MessageBox.Show("Do you like The Rolling Stones?", "The Rolling Stones Survey", MessageBoxButtons.YesNo) = DialogResult.Yes Then

Page 164: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 164 2012

MessageBox.Show("The Rolling Stones are Awesome!")

Else

MessageBox.Show("Maybe you've never heard of The Rolling Stones?")

End If

End Sub

End Class

Page 165: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 165 2012

28. Common String Methods Strings are very important and very versatile in programming. Not only are they used

for passing text but also for other types of data.

Instantiating String Objects String objects can be instantiated in two ways. First, we can create a String object as

if it were a native data type:

Dim name As String = "Howard The Duck"

We can also create a string using more conventional object-oriented syntax:

Dim name As New String("David Quack")

We are not limited to calling the String class constructor with just a string literal. We

can also instantiate String objects using other types of data. For example, we can

instantiate a string from an array of characters:

Dim chars() As Char = {"H"c, "e"c, "l"c, "l"c, "o"c, " "c, ","c, " "c, "w"c, "o"c, "r"c, "l"c, "d"c, "!"c}

Dim greeting As New String(chars)

Txtoutput.text =greeting

The small c tells the program it’s a char. This program fragment outputs the following:

Hello, world!

You can also instantiate a string with just part of a character array. The constructor

will take a character array name, a starting position, and a length, and the constructor

will build a string that begins at the starting position of the array and continues until

the number specified by the length is reached.

Here is an example:

Dim partGreet As New String(chars, 0, 5)

Another option is to instantiate a string using the same character repeated n times.

For example, if we want to create a string of 20 spaces, we call the constructor like

this:

Dim spaces As New String(" "c, 20)

Finally, you can use the String class copy constructor to instantiate a string using a

reference to another String object. Here’s an example:

Dim st As String = "Goodbye"

Dim parting As New String(st)

Although there are many operations you can perform on strings, a small set of

operations dominate. Three of the top operations are

1. Finding a substring in a string,

2. Determining the length of a string, and

3. Determining the position of a character in a string.

Page 166: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 166 2012

MEMBER DESCRIPTION

Chars Gets the character at a specified position in the string.

Compare Compares two strings.

Copy Creates a new string by copying a string.

CopyTo Copies a specified number of characters from a specified position in this string to a specified position in an array of characters.

Empty A constant representing the empty string.

EndsWith Tells you whether the specified string matches the end of this string.

IndexOf Returns the index of the first occurrence of a substring within the string.

Insert Returns a new string with a substring inserted at the specified place.

Join Lets you join together an array of strings with a specified separator.

LastIndexOf Gives the index of the last occurrence of a specified character or string within the string.

Length Gets the number of characters in the string

FUNCTION DESCRIPTION

PadLeft Right-aligns the characters in this string, padding on the left with spaces or a specified character to a specified total length.

PadRight Left-aligns the characters in this string, padding on the right with spaces or a specified character to a specified total length.

Remove Deletes the specified number of characters from this string, beginning at the specified location.

Replace Replaces all occurrences of a substring with a different substring.

Split Splits a string into an array of substrings.

StartsWith Determines whether a specified substring starts the string.

Substring Returns a substring from the current string from the position indicated.

ToCharArray Copies the characters in this string to a character array.

ToLower Returns a lowercase copy of this string.

ToUpper Returns an uppercase copy of this string.

Trim Either removes spaces or removes all occurrences of a set of characters specified in a Unicode character array from the beginning and end of the string.

TrimEnd Either removes spaces or all occurrences of a set of characters specified in a Unicode character array from the end of the string.

TrimStart Either removes spaces or all occurrences of a set of characters specified in a Unicode character array from the beginning of the string

Page 167: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 167 2012

All the samples below are based on two pre-declared string variables: strOriginal and strModified.

Dim strOriginal As String = "These functions will come handy"

Dim strModified As String = String.Empty

Iterate a String

You can use the ‘for’ loop or ‘foreach’ loop to iterate through a string. The ‘for’ loop

gives you more flexibility over the iteration.

For i As Integer = 0 To strOriginal.Length - 1

MessageBox.Show(strOriginal(i).ToString())

Next i

Or

For Each c As Char In strOriginal

MessageBox.Show(c.ToString())

Next c

Split a String

You can split strings using String.Split(). The method takes an array of chars,

representing characters to be used as delimiters. In this example, we will be splitting

the strOriginal string using ‘space’ as delimiter.

Dim delim As Char() = {" "}

Dim strArr As String() = strOriginal.Split(delim)

For Each s As String In strArr

MessageBox.Show(s)

Next s

Split text to an array

Let’s use Split to break up an address into an array by using the comma ,

data = "Mike, McMillan,3000 W. Scenic,North Little " & "Rock, AR,72118"

Dim sdata() As String

sdata = data.Split(",")

Now we can access these data using standard array techniques:

Dim index As Integer

For index = 0 To sdata.GetUpperBound(0)

Console.WriteLine(sdata(index))

Next

There is one more parameter we can pass to the Split method—the number of elements we want to

store in the array. For example, if we want to put the first string element in the first position of the

array, and the rest of the string in the second element, we would call the method like this:

sdata = data.Split(",",2)

The elements in the array are as follows:

Page 168: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 168 2012

0th element = Mike

1st element = McMillan,3000 W. Scenic,North Little Rock,AR,72118

Extract SubStrings from a String

The String.Substring() retrieves a substring from a string starting from a specified

character position. You can also specify the length

' only starting position specified

strModified = strOriginal.Substring(25)

MessageBox.Show(strModified)

' starting position and length of string to be extracted specified

strModified = strOriginal.Substring(20, 3)

MessageBox.Show(strModified)

Reverse a String

One of the simplest ways to reverse a string is to use the StrReverse() function.

Dim strModified As String = StrReverse(strOriginal)

MsgBox(strModified)

Use this to check for palindromes

Compare Two Strings

You can use the String.Compare() to compare two strings. The third parameter is a

Boolean parameter that determines if the search is case sensitive(false) or not(true)

If (String.Compare(strOriginal, strModified, False)) < 0 Then

MessageBox.Show("strOriginal is less than strOriginal1")

ElseIf (String.Compare(strOriginal, strModified, False)) > 0 Then

MessageBox.Show("strOriginal is more than strOriginal1")

ElseIf (String.Compare(strOriginal, strModified, False)) = 0 Then

MessageBox.Show("Both strings are equal")

End If

Test if String is null or Zero Length

A simple way to test if a string is null or empty is to use the

String.IsNullOrEmpty(string) which returns a Boolean value.

Dim check As Boolean = String.IsNullOrEmpty(strOriginal)

Convert the Case of a String

The String class contains methods to convert a string to lower and upper cases.

However, it lacks a method to convert a string to Proper Case/Title Case

' Lower Case

MessageBox.Show(textInfo.ToLower(strOriginal))

' Upper Case

Page 169: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 169 2012

MessageBox.Show(textInfo.ToUpper(strOriginal))

Count the occurrence of letters (not spaces) in a string

Here is an easy way to count how many letters there are in a string

Dim strtext As String = "She sells sea shells on the sea shore chelsea"

Dim i As Integer

Dim count As Integer

For i = 0 To strtext.Length - 1

If strtext.Substring(i, 1) > " " Then

count += 1

End If

Next

Me.Text = count

Count the occurrences of words in a String

You can adopt multiple ways to find the occurrence of a word in a string. One of them

is to use the String.IndexOf() which is one of the ways of finding the occurrence of

the word.

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

'Using IndexOF()

Dim intstartindex As Integer = 0

Dim intcount As Integer = -1

Dim intchangedindex As Integer = -1

Dim strOriginal As String = "She sells sea shells on the sea shore in chelsea"

Dim srchString As String = "sea"

Do While intstartindex <> -1 ' -1 means it can't find it

intstartindex = strOriginal.IndexOf(srchString, intchangedindex + 1)

intcount += 1

intchangedindex = intstartindex

Loop

MessageBox.Show(srchString & " occurs " & intcount & " times")

' Using Regular Expression

Dim rex As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(srchString)

Dim count As Integer = rex.Matches(strOriginal).Count

MessageBox.Show("Using RegEx " & srchString & " occurs " & count & " times")

End Sub

Page 170: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 170 2012

Insert Characters inside a String

The String.Insert() inserts text at a specified index location of a string. You can

insert either a character or a string at a given index location. For eg: We will insert a

string “very” at index 26 in string strOriginal.

strModified = strOriginal.Insert(26, "very ")

MessageBox.Show(strModified)

Replace characters in a String

The String.Replace() removes characters from a string and replaces them with a

new character or string.

strModified = strOriginal.Replace("come handy", "be useful")

MessageBox.Show(strModified)

Create Date and Time from String

Use the DateTime.Parse() to convert a string representing datetime to its DateTime

equivalent. The DateTime.Parse() provides flexibility in terms of adapting strings in

various formats.

strOriginal = "8/20/2008"

Dim dt As DateTime = DateTime.Parse(strOriginal)

Trimming a String

The String.Trim() provides two overloads to remove leading and trailing spaces as

well as to remove any unwanted character. Here’s a sample demonstrating the two

overloads. Apart from trimming the string, it also removes the "#" character.

strOriginal = " Some new string we test ##"

strModified = strOriginal.Trim().Trim(Char.Parse("#"))

Convert String To Integer

In order to convert string to integer, use the Int32.Parse(). The Parse method

converts the string representation of a number to its 32-bit signed integer equivalent.

If the string contains non-numeric values, it throws an error.

Similarly, you can also convert string to other types using Boolean.Parse(),

Double.Parse(), char.Parse() and so on.

strOriginal = "12345"

Dim temp As Integer = Int32.Parse(strOriginal)

Page 171: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 171 2012

String Functions Exercise

Public Class Form1

Dim strInput1 As String

Dim strInput2 As String

Private Sub btnCompare_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompare.Click

If checkStrings() Then

Select Case String.Compare(strInput1, strInput2)

Case 0

lblDisplay.Text = strInput1 & " is equal to " & strInput2

Case Is < 0

lblDisplay.Text = strInput1 & " comes before " & strInput2

Case Is > 0

lblDisplay.Text = strInput1 & " comes after " & strInput2

End Select

End If

End Sub

Private Sub btnConcat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConcat.Click

If checkStrings() Then

lblDisplay.Text = String.Concat(strInput1, strInput2)

End If

End Sub

Private Sub btnEquals_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEquals.Click

If checkStrings() Then

If strInput1.Equals(strInput2) Then

lblDisplay.Text = "The strings are the same."

Else

lblDisplay.Text = "The strings are different."

End If

Page 172: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 172 2012

End If

End Sub

Private Sub btnIndexOf_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIndexOf.Click

If checkStrings() Then

Dim intIndex As Integer = strInput1.IndexOf(strInput2)

Select Case intIndex

Case -1

lblDisplay.Text = "The second string appears no where in the first"

Case Else

lblDisplay.Text = "The index of the second string is " & intIndex & " in the first string"

End Select

End If

End Sub

Private Sub btwInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btwInsert.Click

If checkStrings() Then

Dim intInsertIndex As Integer

If Int32.TryParse(InputBox("Enter the index where the second string should be inserted into the first string", "Insert Index"), intInsertIndex) Then

lblDisplay.Text = strInput1.Insert(intInsertIndex, strInput2)

Else

MessageBox.Show("Please enter a valid integer")

End If

End If

End Sub

Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click

If checkStrings() Then

Dim intRemoveIndex1 As Integer

Dim intRemoveIndex2 As Integer

If Int32.TryParse(InputBox("Enter the index where the removal should begin for the first string", "First String Removal Index"), intRemoveIndex1) Then

If Int32.TryParse(InputBox("Enter the index where the removal should begin for the second string", "Second String Removal Index"), intRemoveIndex2) Then

lblDisplay.Text = _

"First String: " & strInput1.Remove(intRemoveIndex1) & vbCrLf & _

"Second String: " & strInput2.Remove(intRemoveIndex2)

Else

MessageBox.Show("Please enter a valid integer")

End If

Else

Page 173: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 173 2012

MessageBox.Show("Please enter a valid integer")

End If

End If

End Sub

Private Sub btnReplace_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReplace.Click

If checkStrings() Then

lblDisplay.Text = _

strInput1.Replace(InputBox("Enter the string you want to replace from string 1", "String Replacement"), strInput2)

End If

End Sub

Private Sub btnToLower_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnToLower.Click

If checkStrings() Then

lblDisplay.Text = _

"First string: " & strInput1.ToLower & vbCrLf & _

"Second string: " & strInput2.ToLower

End If

End Sub

Private Sub btnToUpper_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnToUpper.Click

If checkStrings() Then

lblDisplay.Text = _

"First string: " & strInput1.ToUpper & vbCrLf & _

"Second string: " & strInput2.ToUpper

End If

End Sub

Private Sub btnTrim_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTrim.Click

If checkStrings() Then

lblDisplay.Text = _

"String 1: " & strInput1.Trim & vbCrLf & _

"String 2: " & strInput2.Trim

End If

End Sub

Private Sub btnTrimEnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTrimEnd.Click

If checkStrings() Then

lblDisplay.Text = _

"String 1: " & strInput1.TrimEnd & vbCrLf & _

"String 2: " & strInput2.TrimEnd

End If

End Sub

Page 174: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 174 2012

Private Sub btnTrimStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTrimStart.Click

If checkStrings() Then

lblDisplay.Text = _

"String 1: " & strInput1.TrimStart & vbCrLf & _

"String 2: " & strInput2.TrimStart

End If

End Sub

'Used be sure that the strings are not empty.

Private Function checkStrings() As Boolean

strInput1 = txtString1.Text

strInput2 = txtString2.Text

lblDisplay.Text = "" 'resets the label

If Not String.IsNullOrEmpty(strInput1) Then 'Checks to see that the string isnt empty

If Not String.IsNullOrEmpty(strInput2) Then 'Checks to see that the string isnt empty

Return True

Else

MessageBox.Show("Please enter a string in the second textbox") 'User Debug

Return False

End If

Else

MessageBox.Show("Please enter a string in the first textbox") 'User Debug

Return False

End If

End Function

End Class

Page 175: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 175 2012

Char and Chars = Characters Char and Chars get quite confusing. Here is the difference.

Char is a variable type. It can hold one character at a time (the Char is short for

Character).

Chars is a method of the String variable type. You can use it on any length of string,

not just a Char variable. And that's the difference between the two: Char is a variable

type, while Chars is a method you can use on Strings.

Create the following program to see how they both work

Private Sub btnchars _Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnchars.Click

Dim OneCharacter As Char

Dim Name As String = "YourName"

Dim i As Integer

For i = 0 To Name.Length - 1 ' minus 1 because it starts at 0

OneCharacter = Name.Chars(i) ' i gives the number for each letter

lbchars.Items.Add(OneCharacter)

Next i

End Sub

Add an If statement to check if the character is numeric

and if so print out

Page 176: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 176 2012

Starts With and Ends With methods Two other comparison methods that can be useful when working with strings are

StartsWith and EndsWith. These instance methods take a string as an argument and

return True if the instance either starts with or ends with the string argument.

Next we present two short programs that demonstrate the use of these methods.

First, we’ll demonstrate the EndsWith method:

Module Module1

Sub Main()

Dim nouns() As String = {"cat", "dogs", "bird", "eggs", "bones"}

Dim pluralNouns As New Collection

Dim noun As String

For Each noun In nouns

If (noun.EndsWith("s")) Then

pluralNouns.Add(noun)

End If

Next

For Each noun In pluralNouns

Console.WriteLine(noun)

Next

Console.Read()

End Sub

End Module

First, we create an array of nouns, some of which are in plural form. Then we loop

through the elements of the array, checking to see whether any of the nouns are

plurals. If a plural is found, it is added to a collection. Then we loop through the

collection, displaying each plural.

We use the same basic idea in the next program to determine which words start with

the prefix “tri”:

Module Module1

Sub Main()

Dim words() As String = {"triangle", "diagonal", "trimester", "bifocal", "triglycerides"}

Dim triWords As New Collection

Dim word As String

For Each word In words

If (word.StartsWith("tri")) Then

triWords.Add(word)

End If

Next

For Each word In triWords

Console.WriteLine(word)

Next

Console.Read()

End Sub

End Module

Page 177: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 177 2012

The Like Operator There is one additional comparison technique we need to examine that is not part of

the String class: the Like operator. This operator works in much the same way as the

regular expression engine but without all the flexibility of regular expressions.

However, the Like operator is able to discern many simple patterns that come up

frequently in string processing situations.

With this operator, a string is compared to a pattern. If there is a match, the

expression returns True; otherwise the expression returns False.

The pattern can consist of either a complete string or a string made up of characters

and special symbols that are used as wildcards. These wildcards can be used to

match any single character, number, or ranges of characters and/or numbers.

The wildcards and range operators used in Like comparisons are the following:

?: matches any single character,

*: matches zero or more characters,

#: matches any single digit,

[char-list]: matches any character in the list, and

[!char-list]: matches any character not in the list.

Here are some examples using the Like operator:

Module Module1

Sub Main()

Dim s1 As String = "foobar"

Dim aMatch As String

aMatch = IIf(s1 Like "foo?ar", "match", "no match")

Console.WriteLine(aMatch)

aMatch = IIf(s1 Like "f*", "match", "no match")

Console.WriteLine(aMatch)

Dim s2 As New String("H2")

aMatch = IIf(s2 Like "[hH][0-9]", "match", "no match")

Console.WriteLine(aMatch)

Console.Read()

End Sub

End Module

The output from this program is as follows:

match

match

match

The first match works because the “?” in the pattern “foo?ar” matches the “b” in

“foobar”.

The second match works because the first letter in the string matches the first letter

in the pattern and the “*” in the pattern matches any of the other characters in the

string. Be careful when using the asterisk in a pattern because it tends to match even

when you don’t want it to, leading to it being called a “greedy” operator.

Page 178: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 178 2012

The most interesting match in the program is the last one. This example might be

useful when processing a bunch of HTML text in search of heading tags. A heading

tag in HTML starts with the letter “H” (or “h”), followed by a digit indicating the level of

the heading. The pattern we used “[hH] [0-9]” leads the Like operator to look for

either an “h” or an “H” in the first character and any digit 0 through 9 in the second

character.

Page 179: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 179 2012

Check a valid email address One of the most basic tools on the net is email validation. This tool leads well to an

exercise on strings. Just how do you tell if [email protected] is valid or not? There

are so many variables.

Here is the beginning of a program you can use. In order to check how your code is

going you need to show an output to see the result. Listboxes are an ideal way to

record output during debugging, as you can see the entries.

This exercise tests the email address and then assigns it to a listbox for valid or

invalid. In the real world it might be a long file to be checked.

Below is the code needed. Replace the ???? with the code needed. (What? Do I

have to give you everything?).

CountCharacter(stremail, "@") calls the function at the bottom.

CountCharacter(ByVal value As String, ByVal ch As Char)

Stremail gets passed to value and the "@" gets passed to ch.

Public Class Form1

Private Sub btnemailtest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnemailtest.Click

Dim intdot As Integer 'there has to be a dot

Dim intatsymbol As Integer 'there has to be an @ symbol

Dim intAtSymbolDot As Integer 'there can't be an @.

Dim intDotAtSymbol As Integer 'there can't be a .@

Dim intDotDot As Integer 'There can't be a ..

Dim intSpace As Integer 'there can't be a space

Dim intcount As Integer = 0 'a counter used for multiples

'pass the email from the text box to the variable

Dim stremail As String = txtemailinput.Text

'tests if its true - it IS EMPTY

If String.IsNullOrEmpty(stremail) Then

MsgBox("At least stick something in the box")

End If

Page 180: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 180 2012

'test to see if true or false

' These must be true

intatsymbol = stremail.IndexOf("@")

intdot = ????

'these must be false

intSpace = ????

intDotAtSymbol = ????

intAtSymbolDot = ????

intDotDot = ????

'these must not be more than 1 from the function below

intcount = CountCharacter(stremail, "@")

intcount = CountCharacter(stremail, ".") + intcount

MessageBox.Show(intcount)

'Some things are bigger than 0 = true and some < 0 = false

If intatsymbol > 0 And ????? And intcount < 3 Then

MessageBox.Show(stremail & " is a valid email address")

lbrealemail.Items.Add(stremail)

Else

lbinvalidemail.Items.Add(stremail)

End If

End Sub

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer

Dim cnt As Integer = 0

For Each c As Char In value

If c = ch Then cnt += 1

Next

Return cnt

End Function

End Class

However this is not complete. [email protected] will return as a true email as well. Control the letter length so that the last letters are more than 1 and the other fields are suitable.

Also people who use Hotmail are too stupid to worry about, so class their email addresses as fails.

Also we need to extract the user names to use as identification. Create another listbox showing valid email usernames – seen above

Page 181: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 181 2012

Check a valid email address – using classes

Change the program to use classes. There might be even easier coding than this to

check for true or false in the Properties. Here is the class I developed for it for the

first part of the exercise without Hotmail or extracting usernames.

Public Class testemail

' These must be true

Private _intatsymbol As Integer 'there has to be an @ symbol

Private _intdot As Integer 'there has to be a dot

'these must be false

Private _intcount As Integer

Private _intSpace As Integer 'there can't be a space

Private _intDotDot As Integer 'There can't be a ..

Private _intDotAtSymbol As Integer 'there can't be a .@

Private _intAtSymbolDot As Integer 'there can't be an @.

'this holds the string

Private _stremail As String ' string holding email

Sub New()

_intcount = 0

End Sub

Public Property stremail() As String

Get

Return _stremail

End Get

Set(ByVal value As String)

_stremail = value

End Set

End Property

Public Property intcount() As Integer

Get

'counts how amny @ and . there are in the string

_intcount = Form1.CountCharacter(_stremail, "@")

_intcount = Form1.CountCharacter(_stremail, ".") + _intcount

Return _intcount

End Get

Set(ByVal value As Integer)

_intcount = value

End Set

End Property

Public Property intSpace() As Integer

Get

_intSpace = _stremail.IndexOf(" ")

Return _intSpace

End Get

Page 182: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 182 2012

Set(ByVal value As Integer)

_intSpace = value

End Set

End Property

Public Property intDotDot() As Integer

Get

_intDotDot = _stremail.IndexOf("..")

Return _intDotDot

End Get

Set(ByVal value As Integer)

_intDotDot = value

End Set

End Property

Public Property intDotAtSymbol() As Integer

Get

_intDotAtSymbol = _stremail.IndexOf(".@")

Return _intDotAtSymbol

End Get

Set(ByVal value As Integer)

_intDotAtSymbol = value

End Set

End Property

Public Property intAtSymbolDot() As Integer

Get

_intAtSymbolDot = _stremail.IndexOf("@.")

Return _intAtSymbolDot

End Get

Set(ByVal value As Integer)

_intAtSymbolDot = value

End Set

End Property

Public Property intatsymbol() As Integer

Get

_intatsymbol = _stremail.IndexOf("@")

Return _intatsymbol

End Get

Set(ByVal value As Integer)

_intatsymbol = value

End Set

End Property

Public Property intdot() As Integer

Get

_intdot = _stremail.IndexOf(".")

Page 183: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 183 2012

Return _intdot

End Get

Set(ByVal value As Integer)

_intdot = value

End Set

End Property

End Class

Check domain via the internet

Better than doing an internal check on an email address is extracting the domain

name from the email address and querying the whois database to see if it’s a real

domain.

First we need to extract out the domain name from the email address.

‘check if the domain is true or not

Dim chop As String = mytestemail.stremail

Dim domain As String = chop.Substring(chop.IndexOf("@") + 1)

CheckFromNet(domain)

Then we pass the domain to a new sub

Private Sub CheckFromNet(domain As String)

In this sub put the code from later in the manual that allows access to the internet.

Change the Uri to Dim webaddress As New Uri("http://www.whois.com/whois/"

& domain) so when we send it appends the domain name to the end of the url

(test.com)

At the end add the following code which checks through the code and looks for the

tick image (the site is available) or the text Invalid domain name.

Page 184: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 184 2012

If s.Contains("/images/ok.png") Or s.Contains("Invalid domain name...") Then

Me.Text = "Not a current address or invalid"

Else

Me.Text = "VALID"

End If

Finally if the site is real, then extract out the country name to see where it comes

from.

Get the DNS IP addresses from the domain name

The DNS class provides simple domain name resolution functionality. This

Dns.GetHostEntry(domain) returns the DNS as a host name or IP address to an

IPAddress() instance.

This code checks the domain name that we extracted above and checks it against

the domain server returning the IP addresses.

I pass them to a ListBox, so put a ListBox on your page first. Just add the following

code to your CheckFromNet sub

ListBox1.Items.Clear()

Try

Dim host As IPHostEntry = Dns.GetHostEntry(domain)

Dim ip As IPAddress() = host.AddressList

Dim index As Integer

For index = 0 To ip.Length - 1

ListBox1.Items.Add(ip(index))

Next index

Catch

End Try

You can also loop through with a foreach

For Each i As Object In ip

ListBox1.Items.Add(i)

Next

Page 185: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 185 2012

Create a Document Statistics counter

The image below shows the statistics for this document. We can easily create a

similar program that will read a document and generate the same types of statistics.

Page 186: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 186 2012

Filter words by length – using class This exercise imports a text file and filters the words in it by word length. You can use

a variety of ways to read the file in. Once it has been passed to a variable it is filtered

by 3 class files with a main Filter Class and some inherited classes.

The Form and its classes

Code for the main form

Imports System.IO 'needed for file

Public Class Form1

Dim strpath As String 'to hold the text

Dim myfilter As New filter 'main class

Private Sub btntext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btntext.Click

myfilter.Counter = 0 'set counter to 0 each click otherwise accumlates

strpath = cbpath.Text 'sets path to the file

txtdata.Clear()'clear the data in the textbox and listbox

lbdata.Items.Clear()

Try

'copy the file into the textbox read in the text from the file to the variable

Dim strtext As String = File.ReadAllText(strpath)

txtdata.Text = strtext 'pass it to the textbox

Dim spacefinder As Char() = {" "} 'splits the text at the space

Dim strtextArr As String() = strtext.Split(spacefinder)

'loop through to grab each word

For Each word As String In strtextArr 'word is defined as a string"

'pass length of each word to Class to compare it

myfilter.Wordlength = word.Length

'pass word to the class to add it to the listbox if correct length

myfilter.Word = word

'if the word output is bigger than 0 then print it

Page 187: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 187 2012

If myfilter.Addword.Length > 0 Then

lbdata.Items.Add(myfilter.Addword)

End If

'repeat loop until end of words

Next word

Me.Text = myfilter.Counter 'show counter on form

Catch ex As Exception

'catch errors

MsgBox("Check that the filename is correct or that there are no other messups")

End Try

End Sub

Private Sub rblessthan4_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rblessthan4.CheckedChanged, rbUnder6.CheckedChanged, rball.CheckedChanged

Dim fakeRB As RadioButton

fakeRB = sender

Select Case fakeRB.Text

Case "Under 4"

myfilter = New LessThanFour

Case "Under 6"

myfilter = New undersix

Case Else

myfilter = New filter

End Select

End Sub

Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click

Dim strpathout As String = txtpathout.Text

Dim i As Integer

Dim w As IO.StreamWriter

w = New IO.StreamWriter(strpathout)

'for the items in the list box

For i = 0 To lbdata.Items.Count - 1

w.WriteLine(lbdata.Items.Item(i))

Next

w.Close()

End Sub

End Class

Public Class filter

Private _counter As Integer

Private _wordlength As Integer

Page 188: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 188 2012

Protected _length As Integer

Private _word As String

Private _addword As String

Sub New()

_length = 10000

_counter = 0

End Sub

Public Property Addword() As String

Get

wordfilter()

Return _addword

End Get

Set(ByVal value As String)

_addword = value

End Set

End Property

Public Property Word() As String

Get

Return _word

End Get

Set(ByVal value As String)

_word = value

End Set

End Property

Public Property Wordlength() As Integer

Get

Return _wordlength

End Get

Set(ByVal value As Integer)

_wordlength = value

End Set

End Property

Public Property length() As Integer

Get

Return _length

End Get

Set(ByVal value As Integer)

_length = value

End Set

End Property

Sub wordfilter()

If _wordlength < _length Then

Page 189: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 189 2012

_counter += 1

_addword = _word

Else

_addword = ""

End If

End Sub

Public Property Counter() As Integer

Get

Return _counter

End Get

Set(ByVal value As Integer)

_counter = value

End Set

End Property

End Class

Public Class LessThanFour

Inherits filter

Sub New()

_length = 4

End Sub

End Class

Public Class over6

Inherits filter

Sub New()

_length = 6

End Sub

End Class

Public Class undersix

Inherits filter

Sub New()

_length = 6

End Sub

End Class

Page 190: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 190 2012

29. Stringbuilder Stringbuilder is a class designed to work with large repetitive string operations. For

example the StringBuilder class can boost performance when concatenating many

strings together in a loop

The methods of Stringbuilder are:

Append(string)

Adds the string in the parameter to the existing string.

fullName.Append(" Jr.")

fullName is now Joe Smith Jr. The original string variable was changed.

Insert(index, string)

Inserts a string into an existing string at the index location. In this example, we add a

middle initial.

fullName.Insert(5, "M. ")

fullName is now Joe M. Smith Jr.

Remove(startIndex, count)

Remove a specified number of characters, as specified by the count parameter. The

startIndex determines where to start removing characters.

fullName.Remove(5, 3)

This removes the middle initial.

FullName is now Joe Smith Jr.

Replace(oldString, newString)

Replace an existing string or substring, within a string, with a new string.

Chars(index)

Get the character at the index location.

Length

Returns the number of characters in the string.

Capacity

Get or set the number of characters for the string.

Page 191: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 191 2012

Imports System.IO

Imports System.Text

Public Class Form1

Dim strpath As String

Dim stbuilder As New System.Text.StringBuilder

Private Sub btngo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btngo.Click

strpath = txtpath.Text

'copy the file into the textbox

Dim txtused As String = File.ReadAllText(strpath)

'make an array to hold split words - thats how you need to get it in.

Dim words As String() = txtused.ToString.Split(" ")

'made a variable to hold each word

Dim word As String

For Each word In words

'add each word to each other word

stbuilder.Append(word & " ")

'replace 'and' with 'chocolate'

stbuilder.Replace("and", "chocolate")

Next

'inserts text at the beginning ) of the string

stbuilder.Insert(0, "This is a practice with StringBuilder ")

'output to text box

txtoutput.Text = stbuilder.ToString

End Sub

End Class

Page 192: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 192 2012

30. Web interface projects These projects may need to bypass the proxy server to operate. Just use the code

later in this section. Otherwise the code in the Metservice program will suffice.

Metservice temperature program

Working with Strings

Metservice provides local weather temperatures for people In New Zealand. The

URL is http://m.metservice.com/towns/christchurch to download a local temperature

with the town appended to the end.

If you cannot use the download in Visual Studio owing to the proxy limitations then

just put the url into a browser and save the html as a text file (metservice). It can be

passed as a string into your program using your Resource File for testing purposes.

Otherwise use the code at the end of this exercise to bypass the proxy.

Dim strmetservice As String = My.Resources.Resource1.metservice

Below is the code to get the html as a string into your program. Use a button to run

the program to update the temperature, and a Label to show the code you have

downloaded so you can work on it (you need to see what you are doing to it)

Imports System.Net

Imports System.IO

Public Class Form1

Private Sub btntemperature_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btntemperature.Click

Dim client As New System.Net.WebClient

Try

Dim strmetservice As String = client.DownloadString("http://m.metservice.com/towns/christchurch")

lblhtml.Text = strmetservice

Catch ex As Exception

MsgBox(ex.Message)

End Try

End Sub

Using strings strip the code back to the component pieces, pass them to labels and

view them in your program.

I would use the structure of strmetservice = all the html code. First you need to strip out the quotation marks, as it messes with the rest of the code otherwise. Use 4 Quote marks to mean a Quote (sigh, don’t ask me, I would think it was 3). Strmetservice.replace(””””, String.Empty)

Page 193: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 193 2012

Then pass to strtemp as (strtemp = strmetservice) and use the string functions to

strip the temperature code back to the temperature. Look for this part of the HTML

code to work on note that the “quotes are removed.

<div class=actual>15.4<span class=temp>&deg;C</span>

Dim inttempleft as integer to hold the number of the left hand side Use inttempleft = strtemp.IndexOf” <div class=actual>”), to get the number of the beginning of the temperature, add + 14 or however many the characters are you have put in the IndexOf to count forward to the temperature. Then use strtemp.Substring(inttempleft, 10) to get a new string of only 10 characters Then find the text to the right <span class=temp> and create a new substring that deleted the right leaving only the lonely temp 15 left. It’s that easy! Then pass the strmetservice to strfeelslike and look for

<div class="feel-likes"><strong>Feels like 15<span class="temp">&deg;C</span>

Then strmetservice to strimageurl and dig out the image url

In the code is the name of the image that is downloaded as well. Extract the url

which is around here and pass it to a variable strimage..

<div class="mob-page" id="forecasts-block"><h2>10 Day Forecast</h2><div class="item">

<img src="/sites/all/themes/mobile/images/wx-icons/showers_wht.gif"

So

Dim strimage as string

strimage = showers_wht.gif

Append it to the main url and put that url in the string strimageurl into the following

code (example url given).

Dim strimageurl As String

strimageurl = "http://m.metservice.com//sites/all/themes/mobile/images/wx-icons/" & strimage

The image does not have to be saved to a folder first.

Dim mywebclient As New Net.WebClient

'Byte array holds the data

Dim ImageInBytes() As Byte = mywebclient.DownloadData(strimageurl)

'Create a memory stream using the byte

Page 194: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 194 2012

Dim ImageStream As New IO.MemoryStream(ImageInBytes)

'Create a bitmap from the memory stream

PictureBox1.Image = New System.Drawing.Bitmap(ImageStream)

'No files need to be written to the drive

Using the formulas from your older temperature program create the Fahrenheit

temperature .

Create a way, probably using a combo box that you can change the cities that

the temperature refers to.

In the main metservice website, http://metservice.com/national/index you can find a

list of the cities supported by the program and use them via cut and paste. You will

need to look in their source code to find it.

Getting through the proxy server

This is the code to get through the proxy server; you need your username and

password. At present to check it I run it off a button which should return the page as

text

Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click

'I saved the details as a string resource and can just call them up as needed

Dim password As String = My.Resources.Resource1.Password

Dim username As String = My.Resources.Resource1.Username

'need to set the network credentials

Dim myNetCredentials As New NetworkCredential("", "")

'you can also use My.User.Name to extract out the users name

myNetCredentials.UserName = username

myNetCredentials.Password = password

Dim webaddress As New Uri("http://m.metservice.com/towns/christchurch")

Dim request As New WebClient

'get the proxy ID in this case 10.6.0.254:3128

request.Proxy = WebRequest.GetSystemWebProxy()

'pass across the username and password to the proxy

request.Proxy.Credentials = myNetCredentials

Try

'download the website as a string.

Dim s As String = request.DownloadString(webaddress)

'output it to see what you are working with

RichTextBox1.Text = s

Catch webex As WebException

End Try

Page 195: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 195 2012

End Sub

Other ways of creating a download

' Get the stream containing content returned by the server.

Dim dataStream As Stream = response.GetResponseStream()

' Open the stream using a StreamReader for easy access.

Dim reader As New StreamReader(dataStream)

' Read the content.

Dim responseFromServer As String = reader.ReadToEnd()

' Display the content.

Me.Text = responseFromServer

' Cleanup the streams and the response.

reader.Close()

dataStream.Close()

response.Close()

What if?

You can get the user using My.User.Name or better Windows.Forms.SystemInformation.UserName and you can get the

domain and proxy using WebRequest.GetSystemWebProxy(). So all that is missing is the password.

We did make a password cracker earlier. What if we add that in to get the password and then save it as a text file so you can reuse it later?

What have you got? A way to access the net from any logged on computer without knowing the password.

Page 196: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 196 2012

Whitepages Phone book We can easily use this structure to create an application that checks the whitepages

for names and returns back the number and address.

Go to http://whitepages.co.nz when you add a name and place to the boxes and

press find it sends it via the url string, like this http://whitepages.co.nz/white-

all/smith/christchurch/

All we have to do is then append to http://whitepages.co.nz & ”/” & strname & ”/” &

strplace and send it.

We can even add extra parameters such as ?sort=name to the end as seen in the

Narrow By section.

Maybe we can extract the data from this page to pass it to a Google map?

http://whitepages.co.nz/w/101088869/. Maybe we can pass the address straight to

Google maps, for the location.

The returning page can be stripped back to get out the data we want. This would

make a great Android app as well.

Page 197: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 197 2012

DuckDuckGo using Json and Nuget The purpose of this project is to be able to send a request for a definition to

DuckDuckGo, and return an answer which is parsed to extract the text from the JSON.

JSON is a very popular and important way of moving data around the net and to

programs accessing the net. (All code at the end)

To do this we could write our own JSON parser, or use one from Nuget. Lets not

reinvent the wheel and use Newtonsoft.json from Nuget..

First make a new project, and SAVE it. (I didn’t and kept getting an error) it needs to be

saved first so it can install the package into your project.

Go to this link http://nuget.org/packages/Newtonsoft.Json and follow the instruction

using the Package Manager Console help as well.

Once it’s installed it just needs to be called. This link gives an overview of how to use

the package. http://james.newtonking.com/projects/json-net.aspx . When I dimmed

the following Dim JSONobject As JObject the program automatically added the

import Imports Newtonsoft.Json.Linq

The code of the program is the Bypass the proxy code to download a string and then

change the Uri to http://api.duckduckgo.com/?q=definition%20chocolate&format=json .

From there you need to output the returned string to see how the JSON is built. I

outputted it to a richtextbox and then copied and pasted it into my code as a comment.

' {"Definition":"","DefinitionSource":"","Heading":"chocolate (definition)","AbstractSource":"The Free Dictionary","Image":"","RelatedTopics":[],"AbstractText":"Fermented, roasted, shelled, and ground cacao seeds, often combined with a sweetener or flavoring agent.","Abstract":"Fermented, roasted, shelled, and ground cacao seeds, often combined with a sweetener or flavoring agent.","AnswerType":"","Redirect":"","Type":"A","DefinitionURL":"","Answer":"","Results":[],"AbstractURL":"http://www.thefreedictionary.com/_/search.aspx?pid=aff18&word=chocolate"}

It might look like gobbledegook at this stage but there is a simple plan to it. JSON is in

Key : Value pairs so looks like this "Heading":"chocolate (definition)"

{

"Definition":"",

"DefinitionSource":"",

"Heading":"chocolate (definition)",

"AbstractSource":"The Free Dictionary",

"Image":"",

"RelatedTopics":[],

"AbstractText":"Fermented, roasted, shelled, and ground cacao seeds, often combined with a sweetener or flavoring agent.",

"Abstract":"Fermented, roasted, shelled, and ground cacao seeds, often combined with a sweetener or flavoring agent.",

"AnswerType":"",

"Redirect":"",

Page 198: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 198 2012

"Type":"A",

"DefinitionURL":"",

"Answer":"",

"Results":[],

"AbstractURL":http://www.thefreedictionary.com/_/search.aspx?pid=aff18&word=chocolate

}

Main code to run this.

Dimension the JObject -

Dim JSONobject As JObject = JObject.Parse(strdownload)

Strdownload is the string being returned from the net. Its renamed from S in the Proxy

example.

We are returning just one string in this case, sometimes you want

to return an array of data (presumable Item(Object) as a guess). So

I chose Item(String) from the options.

Use JSONobject.Item("Heading") to extract out the text

chocolate (definition)

I passed it to a ListBox - lbxdefn.Items.Add(JSONobject.Item("Heading"))

Use JSONobject.Item("AbstractText") to extract out the text Fermented, roasted,

shelled, and ground cacao seeds, often combined with a sweetener or flavoring

agent.

I used a Textbox, Button, ListBox, and RichTextBox.

Imports System.Net

Imports Newtonsoft.Json.Linq

Public Class Form1

Dim strdownload As String

Page 199: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 199 2012

Private Sub btndefinition_Click(sender As Object, e As EventArgs) Handles btndefinition.Click

'I saved the details as a string resource and can just call them up as needed

Dim password As String = My.Resources.Resource1.Password

Dim username As String = My.Resources.Resource1.Username

Dim wordpath As String = "http://api.duckduckgo.com/?q=definition%20" & txtword.Text & "&format=json"

Me.Text = wordpath

'need to set the network credentials

Dim myNetCredentials As New NetworkCredential("", "")

'you can also use My.User.Name to extract out the users name

myNetCredentials.UserName = username

myNetCredentials.Password = password

Dim webaddress As New Uri(wordpath)

Dim request As New WebClient

'get the proxy ID in this case 10.6.0.254:3128

request.Proxy = WebRequest.GetSystemWebProxy()

'pass across the username and password to the proxy

request.Proxy.Credentials = myNetCredentials

Try

'download the website as a string.

strdownload = request.DownloadString(webaddress)

'output it to see what you are working with

txtdefn.Text = strdownload

Catch webex As WebException

End Try

Dim JSONobject As JObject = JObject.Parse(strdownload)

lbxdefn.Items.Add(JSONobject.Item("Heading"))

lbxdefn.Items.Add(JSONobject.Item("AbstractText"))

'lbxdefn.Items.Add(JSONobject.Item("Abstract"))

End Sub

End Class

More: http://duckduckhack.com/

http://nuget.org/packages/Newtonsoft.Json

http://james.newtonking.com/projects/json-net.aspx

http://jsonformat.com/

Page 200: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 200 2012

31. The DateTime and TimeSpan Types The DateTime and TimeSpan data types also have built-in methods and properties.

These class members allow you to perform three useful tasks:

Extract a part of a DateTime (for example, just the year) or convert a

TimeSpan to a specific representation (such as the total number of days or

total number of minutes)

Easily perform date and time calculations

Determine the current date and time and other information (such as the day of

the week or whether the date occurs in a leap year)

For example, the following block of code creates a DateTime object, sets it to the

current date and time, and adds a number of days. It then creates a string that

indicates the year that the new date falls in (for example, 2013).

Dim MyDate As DateTime = DateTime.Now MyDate = MyDate.AddDays(100)

Dim DateString As String = MyDate.Year.ToString()

The next example shows how you can use a TimeSpan object to find the total

number of minutes between two DateTime objects.

Dim MyDate1 As Date = DateTime.Now

Dim MyDate2 As Date = DateTime.Now.AddHours(3000)

Dim Difference As TimeSpan Difference = MyDate2.Subtract(MyDate1)

Dim NumberOfMinutes As Double NumberOfMinutes = Difference.TotalMinutes

The DateTime and TimeSpan classes also support the + and – arithmetic operators,

which do the same work as the built-in methods. That means you can rewrite the

example shown previously like this:

Dim MyDate1 As DateTime = DateTime.Now

Dim Interval As TimeSpan = TimeSpan.FromHours(3000)

Dim MyDate2 As DateTime = MyDate1 + Interval

Subtracting one DateTime object from another produces a TimeSpan.

Dim Difference As TimeSpan

Difference = MyDate2 - MyDate1

These examples give you an idea of the flexibility .NET provides for manipulating

date and time data. The tables below list some of the more useful built-in features of the

DateTime and TimeSpan types.

Page 201: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 201 2012

Useful DateTime Members Member Description

Now Gets the current date and time. You can also use the UtcNow property to change the computer’s local time (which is relative to the local time zone) to a Universal Coordinated Time (UTC). Assuming your computer is correctly configured, this corresponds to the current time in the Western European (UTC + 0) time zone.

Today Gets the current date and leaves time set to 00:00:00.

Year, Date, Month, Hour, Minute, Second, and Millisecond

Returns one part of the DateTime object as an integer. For example, Month will return 12 for any day in December.

DayOfWeek Returns an enumerated value that indicates the day of the week for this DateTime, using the DayOfWeek enumeration. For example, if the date falls on Sunday, this will return DayOfWeek. Sunday.

Add() Adds a TimeSpan to a DateTime and returns the result as a new DateTime. For convenience, these operations are mapped to the + and – operators, so you can use them instead when performing calculations with dates.

Subtract() Subtracts a TimeSpan or DateTime from another DateTime. Returns a TimeSpan that represents the difference.

AddYears(), AddMonths(), AddDays(), AddHours(), AddMinutes(), AddSeconds(), AddMilliseconds()

Accepts an integer that represents a number of years, months, and so on, and returns a new DateTime. You can use a negative integer to perform a date subtraction.

DaysInMonth() Returns the number of days in the specified month in the specified year.

IsLeapYear() Returns True or False depending on whether the specified year is a leap year.

ToString() Returns a string representation of the current DateTime object.You can also use an overloaded version of this method that allows you to specify a parameter with a format string.

Note

Methods such as Add() and Subtract() don’t change a DateTime object. instead, they return a new DateTime or TimeSpan object.

Page 202: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 202 2012

Useful TimeSpan Members

Member Description

Days, Hours, Minutes, Seconds, Milliseconds

Returns one component of the current TimeSpan. For example, the Hours property can return an integer from −23 to 23.

TotalDays, TotalHours, TotalMinutes, TotalSeconds, TotalMilliseconds

Returns the total value of the current TimeSpan as a number of days, hours, minutes, and so on. The value is returned as a double, which may include a fractional value. For example, the TotalDays property might return a number such as 234.342.

Add() and Subtract()

Combines TimeSpan objects. For convenience, these operations are mapped to the + and – operators, so you can use them instead when performing calculations with times.

FromDays(), FromHours(), FromMinutes(), FromSeconds(), FromMilliseconds()

Allows you to quickly create a new TimeSpan. For example, you can use TimeSpan.FromHours(24) to create a TimeSpan object exactly 24 hours long.

ToString() Returns a string representation of the current TimeSpan object. You can also use an overloaded version of this method that allows you to specify a parameter with a format string.

Page 203: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 203 2012

32. Arrays and Collections In the beginning there were variables, and they were good. The idea that you map a

location in memory to a value was a key to tracking a value. However, most people

want to work on data as a set. Taking the concept of a variable holding a value, we

move to the concept of a variable that could reference an array of values.

Arrays are just lists of data that have a single data type. For example, you might want

to store a list of your friends’ ages in an integer array or their names in a string array.

When you define an array, you’re actually creating a variable that has more than one

dimension. For example, if you define a variable as a string, you can only hold a

single string value in it:

Dim strName As String

However, with an array you create a kind of multiplier effect with a variable, so you

can hold more than one value in a single variable. An array is defined by entering the

size of the array after the variable name. For example, if you wanted to define a

string array with 10 elements, you’d do this:

Dim strName(9) As String

The reason why you use(9)instead of (10)to get an array with 10 is simply that because numbering in an array starts at zero, the first element in an array is zero, the second element is one, and so on.

When you have an array, you can access individual elements in it by providing an

index value between 0 and a maximum possible value — this maximum possible

value happens to be one less than the total size of the array.

For example, to set the element with index 2 in the array, you’d do this:

strName(2) = "George"

To get that same element back again, you’d do this:

MessageBox.Show(strName(2))

There are 3 main types of array, The ArrayList and the List types are new and are

based on the collections namespace. They are the recommended types of array that

programmers should use as they are capable of being used across the entire dot net

framework, and automatically increase and decrease in size. The other one, it’s the

traditional Array which comes in a variety of flavours depending on its needs but

works the same in each one.

We will cover these 3 types in more depth later. This next exercise just introduces the

3 types of array and shows their differences.

Page 204: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 204 2012

Arrays Exercise

There are 3 ways we have created arrays in this exercise, each are different.

Dim ArrayList As New Collections.ArrayList

Dim itemlist As New List(Of String)

Dim array(4) As Integer

Dim wordsArray() As String

Arrays

All arrays in .NET begin at 0, but when an array is declared in Visual Basic, the

index defines the upper limit of the array, not the number of elements. The

challenge is to remember that all subscripts go from 0 to the upper bound, meaning

that each array contains one more element than its upper bound. This Dim array(4)

As Integer holds 5 items.

Here in the code the values are passed to the array

Dim array(4) As Integer

array = New Integer() {0, 1, 2, 3, 4}

I could rewrite it as below as it counts how many values go into it

automatically.

Dim array() = New Integer() {0, 1, 2, 3, 4}

The problem is that after 5 values you have to rebuild the array to hold more using

Redim and Preserve (which I will talk about).

Here is a good example of the code above.

Dim wordsArray() As String

Dim temp As String = "The rain in Spain falls mainly down the Drain"

wordsArray = temp.ToUpper.Split(" ")

The above could be written as

Dim temp As String = "The rain in Spain falls mainly down the Drain"

Dim wordsArray() = temp.ToUpper.Split(" ")

Page 205: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 205 2012

Which will give it an upperlimit of 8 (nine words starting with 0)

Collections - ArrayList

Collections are an inbuilt

class of Array (As New Collections.ArrayList) and they

can store any type of data in the same array to any

quantity because each item is stored as an Object, not

an int, or string etc.

Data is added to an arraylist collection simply by using ArrayList.Add

ArrayList.Add(23) ArrayList.Add("Apple") ArrayList.Add(32.345) ArrayList.Add("Pear") ArrayList.Add("Grape")

However holding any type of data is also a drawback as each item has to be

converted to an Object, and then back to its initial type which is called Boxing, and

makes operations slightly slower with large data owing to having to be Boxed and

unboxed.

The second issue is that having collections based only on the type Object goes

against the best practice of having a strongly typed environment. As soon as you

started loading items into a collection, you lose all type checking. Is that meant to be

23 or 2b? No checking for type consistency happens.

Other collections we can use are:

Collection Description

ArrayList Implements an array whose size increases automatically as elements are added.

BitArray Manages an array of Booleans that are stored as bit values. Hashtable Implements a collection of values organized by key. Sorting is done

based on a hash of the key. Queue Implements a first in, first out collection.

Page 206: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 206 2012

SortedList Implements a collection of values with associated keys. The values are sorted by key and are accessible by key or index.

Stack Implements a last in, first out collection.

Generic List – preferred

There are many examples of generic templates in the .NET Base Class Library

(BCL). Many of them can be found in the System.Collections.Generic namespace,

but others are scattered through the BCL as appropriate.

Many of the examples focus on generic collection types, but this is only because it is

here that the performance gains, due to generics, are seen. In most cases, generics

are used less for performance gains than for the strong typing benefits they provide.

The primary motivation for adding generics to .NET was to enable the creation of

strongly typed collection types. Because generic collection types are strongly typed,

they are significantly faster than the previous inheritance-based collection model.

Anywhere you presently use collection classes in your code, you should consider revising that code to use generic collection types instead.

Because the technology to support generics was created primarily to build collection classes, it naturally follows that you might create a generic collection anytime you would otherwise build a normal collection class.

A generic is often written as something like List(Of T). The type (or class) name in

this case is List. The letter T is a placeholder, much like a parameter. It indicates

where you must provide a specific type value to customize the generic. For instance,

you might declare a variable using the List(Of T) generic:

Dim itemlist As New List(Of String)

Data is added using the .Add()

itemlist.Add("Chocolate") itemlist.Add(34) itemlist.Add("Carrot") itemlist.Add(30)

As you specify a T in this case String then everything that enters the itemlist is

considered a string. As a result you can’t add itemlist.Add(34) to

itemlist.Add(30) as they are considered strings and not integers.

Note:

ArrayList is Loosely Typed as items are stored as an Object not as string or Integer. List can only hold one type (such as string or integer) as a result its Strongly Typed

This means that it is not late bound like ArrayList, but rather is early bound. The net result is much higher performance, along with all the type-safety benefits of being strongly typed.

Page 207: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 207 2012

Working with ArrayList ArrayLists are one of the most flexible data structures and contain a simple list of

values. We can easily can add, insert, delete etc. Its advantage over lists as it can

take multiple types of values.

This project uses a single method Sub updatearraylist() to update the ListBox, its

at the end of the code.

Public Class Form1

Dim ItemList As New Collections.ArrayList

Private Sub btngo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btngo.Click

ItemList.Add(23)

ItemList.Add("Apple")

ItemList.Add(32.345)

ItemList.Add("Pear")

ItemList.Add("Grape")

updatearraylist()

End Sub

Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd.Click

'make sure that there is text in the text box to add to the list. Put a check around the code below to make sure txtinput.Text is not empty

ItemList.Insert(1, txtinput.Text)

updatearraylist()

End Sub

Private Sub btnremove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnremove.Click

'make sure you click on an item before hitting remove. Put a check around the code below to make sure lbxarray.selecteditem is not empty

ItemList.Remove(lbxarray.SelectedItem)

Page 208: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 208 2012

updatearraylist()

End Sub

Private Sub btnsort_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsort.Click

'You can only sort if the items are the same type like strings, however this data has strings and integers, so you have to delete the integers first or warn people

ItemList.Sort()

updatearraylist()

End Sub

'Check if the word exists and remove it from the list

Private Sub btncheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncheck.Click

'make sure you have a word in the text box. Put a check around the code below to make sure lbxarray.selecteditem is not empty

Dim strcheck As String

strcheck = txtinput.Text

'I am using a ForEach for this loop, they are just as easy to use, if not easier. Than If loops.

For Each item As Object In ItemList

If strcheck = item Then

Me.Text = "Found!"

End If

Next

'Remove the item from the list

ItemList.Remove(strcheck)

updatearraylist()

End Sub

'This updates the arraylist and shows the new items in the listbox each time you click on a button. You can replace the For loop with a For Each as seen above

Sub updatearraylist()

lbxarray.Items.Clear()

For i = 0 To ItemList.Count - 1

lbxarray.Items.Add(ItemList.Item(i))

Next

End Sub

Read in a list of words using Streamreader

Using r As StreamReader = New StreamReader("C:\words1.txt")

Look back at the StreamReader exercise to see how to do it. The ‘List’ used there is

just an arraylist. Output the results using Streamwriter.

Page 209: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 209 2012

Arraylist and random numbers Create a program that takes a preloaded ArrayList and randomly chooses an item

from it. That item is moved to a second ListBox and deleted from the first ListBox.

You will need to find a way so that the random number generated is less than the

number of items, otherwise loop until it is.

Here is some code to get started with…..

Private Sub btnrandom_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnrandom.Click

Dim random As Integer

‘generates a random number

random = randomnumber.random

Me.Text = random ‘ show it on the top of the form

‘add the item to the new listbox

lbrandom.Items.Add(ItemList.Item(random))

‘delete the item from the first listbox

ItemList.Remove(ItemList.Item(random))

‘update the array

updatearraylist()

End Sub

Page 210: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 210 2012

Work out General Depreciation rates on computers Using the General Depreciation Rates from the NZ IRD PDF (or website) extract out

the depreciation rates for the computer area on Page 47.

I would save the rates comma delimitated into a text file, load the text file into an

array. Then access each part of the array to see the data and choose your Computer

part from a combo box.

It would be a great project to test your skills.

This guide sets out the general depreciation rates for both diminishing value (DV)

and straight line (SL)

Fields

The following details are shown for each asset:

Fields Example

Name, Backup units (tape type)

the estimated useful life (years), 4

DV depn rate (%), 50

DV rate including the 20% loading (DV + 20% loading (%)),

60.0

SL depn rate (%), 40

SL rate including the 20% loading (SL +20% loading (%)) 48.0

Example of the text file

Backup units (tape type) 4 50 60.0 40 48.0 ,Banknote dispensers 6.66 30 36.0 21 25.2, Bridges 4 50 60.0 40 48.0, Cabling 6.66 30 36.0 21 25.2, CAD/CAM equipment 4 50 60.0 40 48.0, Communications controllers 4 50 60.0 40 48.0, Computer and associated equipment (used for typesetting) 5 40 48.0 30 36.0, Computer equipment (default class) 4 50 60.0 40 48.0, Control equipment (process, computer, if separately identified) 8 25 30.0 17.5 21.0, Data concentrators 4 50 60.0 40 48.0, Digitisers 4 50 60.0 40 48.0, Disk drives (for use with mini computers) 4 50 60.0 40 48.0, Disk drives (for use with personal computers) 4 50 60.0 40 48.0, EFTPOS terminals 4 50 60.0 40 48.0, Floors (for computer rooms) 20 10 12.0 7 8.4, Gas dowsing systems 20 10 12.0 7 8.4, Laptop computers 4 50 60.0 40 48.0, Mainframe computers 6.66 30 36.0 21 25.2, Mini computers 4 50 60.0 40 48.0, Modems 4 50 60.0 40 48.0, Multiplexers 4 50 60.0 40 48.0, Network servers 4 50 60.0 40 48.0, Notebook computers 4 50 60.0 40 48.0, Personal computers 4 50 60.0 40 48.0, Plotters 5 40 48.0 30 36.0, Power conditioners 6.66 30 36.0 21 25.2, Power supplies (uninterruptable) 6.66 30 36.0 21 25.2, Printers 5 40 48.0 30 36.0, Routers 4 50 60.0 40 48.0, Scanners 4 50 60.0 40 48.0, Terminals (without capability of local storage capacity) 6.66 30 36.0 21 25.2, Voice mail equipment 4 50 60.0 40 48.0

* The 20% depreciation loading doesn’t

apply to assets acquired after 20 May

2010.

Page 211: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 211 2012

Calculator using words – simple array This calculator takes a string of text and numbers and splits it to answer the formula.

Such a simple project could easily be modified for a number of more advanced

purposes.

Public Class Form1

Private Sub btnAction_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAction.Click

Dim wordsArray() As String

Dim temp As String

Dim num1 As Single

Dim num2 As Single

Dim answer As Single

' get the text and split it into array

temp = txtInstruction.Text

'make the words uppercase, and split them with the space pass it to wordarray()

wordsArray = temp.ToUpper.Split(" ")

'check it works

lbcheck.Items.Add(wordsArray(0))

lbcheck.Items.Add(wordsArray(1))

lbcheck.Items.Add(wordsArray(2))

lbcheck.Items.Add(wordsArray(3))

Page 212: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 212 2012

' get the numbers - 1st will always be in wordsArray(1)

' 2nd will always be in wordsArray(3)

num1 = CSng(wordsArray(1))

num2 = CSng(wordsArray(3))

Select Case wordsArray(0)

Case "MULTIPLY"

answer = num1 * num2

Case "DIVIDE"

answer = num1 / num2

Case "SUBTRACT"

answer = num2 - num1

Case "ADD"

answer = num1 + num2

End Select

' put answer in place in the label

lblResult.Text = "The answer is: " & answer

End Sub

Page 213: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 213 2012

Scrabble Dictionary – using lists This example takes a word list and compares the entered word to that list to see if it

matches. Try making this program without using the code.

I used a class mydic to hold some of the properties (I should have used more in it). I

load in words1.txt to try it out but also a word list that takes AGES to load up in the

listbox. As a result I had to have the option to turn off the listbox loading when using

the dictionary

How to start?

1. Create a button, Textbox, to hold the path, and a list to pass it to.

2. Use file open tools to open the words1.txt file and load it into the listbox

3. Create another textbox to hold the word you want to test and a second

button to compare the word with the list items.

4. Make a class dict to hold the string variables that are in the code (you

can work it out from the names)

5. Create a label to hold the “Word Found” or “Word Not Found”

6. We have to make both list and word entered lower case to avoid

mistakes.

7. Using FOR EACH we need to match the word in the variable with the

word in the list.

8. After that is done everything else is tidying up.

9. Replace the radiobuttons with Menu options

Page 214: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 214 2012

Imports System.IO

Public Class Form1

Dim mydict As New dict ‘ a class created called dict

Dim wordlist As New List(Of String)

Dim blnlistboxOnOff As Boolean = True

Private Sub btnload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnload.Click

lbwords.Items.Clear()

' We need to read into this List.

Try

mydict.strpath = cbpath.SelectedItem

Me.Text = mydict.strpath

' Open file.txt with the Using statement.

Using r As StreamReader = New StreamReader(mydict.strpath)

' We need to read into this List. Store contents in this String.

Dim line As String

line = r.ReadLine ' Read first line.

' Loop over each line in file, While list is Not Nothing.

Do While (Not line Is Nothing)

line = line.ToLower 'all lower case

wordlist.Add(line) ' Add this line to list.

If blnlistboxOnOff = True Then

lbwords.Items.Add(line)

End If

line = r.ReadLine ' Read in the next line.

Loop

End Using

Dim length As Integer = File.ReadAllLines(mydict.strpath).Length

btnload.Text = length

Catch

MsgBox(mydict.strpath & " It screwed up")

End Try

End Sub

Private Sub btncompare_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncompare.Click

mydict.strselectedword = txtword.Text ' copy word to variable

mydict.strselectedword = mydict.strselectedword.ToLower ' make it lower case

Dim word As String

For Each word In wordlist

If word = mydict.strselectedword.ToString Then

lbltrueorfalse.Text = "Word found"

Return

Page 215: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 215 2012

Else

lbltrueorfalse.Text = "Not a word"

End If

Next

End Sub

Private Sub Form1_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated

lbltrueorfalse.Text = ""

End Sub

Private Sub cbpath_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbpath.SelectedIndexChanged

btnload.Text = "Load"

End Sub

Private Sub rbon_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbon.CheckedChanged, rboff.CheckedChanged

Dim fakerb As New RadioButton

fakerb = sender

If fakerb.Text = "Listbox on" Then

blnlistboxOnOff = True

ElseIf fakerb.Text = "Listbox off" Then

blnlistboxOnOff = False

End If

End Sub

End Class

Page 216: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 216 2012

Advanced Scrabble Incremental Search Change the radio buttons to Menu items and show options for Listview ON/Off and

Incremental Search ON/Off

In this version we want search to work as the person begins typing in the word into

the textbox.

To do this we need to treat each letter as a char, a single character. Using the earlier

exercise on Char Here we can pull out each letter as its typed in.

There are two things wrong with this system.

2 When the search starts with the first letter it will look for that letter anywhere in

the word.

3 The listbox search is really slow with the large files. We need to turn incremental

search off, this can be done in a number of ways, auto or manual. I used a

manual procedure

4 A better way to make this would be to search the array we made earlier and just

show the found items in the listbox. So your challenge is to make that.

Private Sub txtword_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtword.TextChanged

‘ match the individual letters with the letters in the list, sort of like an incremental search.

Try

Dim wordasletter As String

‘need to turn search on and off as it hangs with the dictionary

If blnsearchOff = True Then

Dim word As String = txtword.Text

‘create a variable to hold a single letter

Dim OneLetter As Char

Page 217: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 217 2012

Dim i As Integer

For i = 0 To word.Length - 1 ' minus 1 because it starts at 0

OneLetter = word.Chars(i) ' i gives the number for each letter

wordasletter &= OneLetter 'adds a single letter

Next i

'code for listbox selection - multiextended means you can have more than one selection

lbwords.SelectionMode = SelectionMode.MultiExtended

' Loop through all items the ListBox.

Dim findcount As Integer

For j As Integer = 0 To lbwords.Items.Count - 1

'turn off and selections that might be on

lbwords.SetSelected(j, False)

'j gives how many its found

If lbwords.Items(j).ToString.IndexOf(wordasletter) <> -1 And i > 2 Then

Me.Text = i

'if there is a word then turn on selections of them.

lbwords.SetSelected(j, True)

findcount += 1

Me.Text = findcount

End If

Next

End If

Catch

End Try

End Sub

Page 218: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 218 2012

Scrabble Exercise - using a Hash table The Hashtable class is a dictionary collection, where every item is indexed with a

unique value. Hashtable collections are ideal for situations where you need to quickly

retrieve individual items, because you can look up items using the corresponding key

values, rather than by iterating through the contents of the entire collection. However,

unlike arrays or the ArrayList class, you can't access items using an index number.

When using a Hashtable, you must decide what information to use for indexing items.

This data must be unique. It might be derived from the object itself, or you might

generate it on demand using a sequence number. If you don't have a suitable value

to use as a key, you can always use the reference of the object you are adding:

' Use the object reference as a key.

Dim Col As New Hashtable()

Col.Add(ItemA, ItemA)

The exercise below uses the word list as the Key as well as the Value. It runs

amazingly fast with 170,000 entries! Each time you type a letter it checks it against

the dictionary and adds words into the listbox.

Imports System.IO

Public Class Form1

Dim mydict As New dict

Dim hasht As New Hashtable

Dim blnlistboxOnOff As Boolean = False

Private Sub btnload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnload.Click

lbwords.Items.Clear()

btnload.Text = "...loading"

Try ' We need to read into this List.

mydict.strpath = cbpath.SelectedItem

Me.Text = mydict.strpath

' Open file.txt with the Using statement.

Using r As StreamReader = New StreamReader(mydict.strpath)

Dim line As String ' Store contents in this String.

line = r.ReadLine ' Read first line.

Page 219: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 219 2012

Dim linecount As Integer = 0

' Loop over each line in file, While list is Not Nothing.

Do While (Not line Is Nothing)

line = line.ToLower 'all lower case

'add line to hash table using each line as the key and the Value

hasht.Add(line, line)

‘How many lines? – just for info

linecount += 1

Me.Text = linecount

‘Output to list box or not?

If blnlistboxOnOff = True Then

lbwords.Items.Add(line)

End If

line = r.ReadLine ' Read in the next line.

Loop

End Using

'show the length of the file on the button

Dim length As Integer = File.ReadAllLines(mydict.strpath).Length

btnload.Text = length

Catch

MsgBox(mydict.strpath & " its not there.Try again")

End Try

End Sub

Private Sub Form1_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated

'so you don't see label1 when it loads

lbltrueorfalse.Text = ""

End Sub

Private Sub txtword_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtword.TextChanged

'make an array to match the individual letters with the letters in the list, sort of like an incremental search.

Try

Dim wordasletter As String = ""

Dim word As String = txtword.Text

Dim OneLetter As Char

Dim i As Integer

For i = 0 To word.Length - 1 ' minus 1 because it starts at 0

OneLetter = word.Chars(i) ' i gives the number for each letter

'adds a single letter

' Me.Text &= OneLetter ' working adds a single letter together

wordasletter &= OneLetter

Next i

'compare the word being entered to hashtable entries

If hasht.ContainsKey(wordasletter) Then

Page 220: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 220 2012

'if true show Is a Word and add to listbox

lbltrueorfalse.Text = wordasletter & " is a word"

lbwords.Items.Add(wordasletter)

Else

lbltrueorfalse.Text = wordasletter & " keep typing"

End If

Catch

End Try

End Sub

Private Sub ListboxOnToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListboxOnToolStripMenuItem1.Click

blnlistboxOnOff = True ‘turn listbox ON and show on menubar

ListboxViewToolStripMenuItem.Text = "Listbox ON"

End Sub

Private Sub ListboxOffToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListboxOffToolStripMenuItem1.Click

blnlistboxOnOff = False

ListboxViewToolStripMenuItem.Text = "Listbox OFF"

End Sub

End Class

Note that like the ArrayList, the Hashtable stores items as the generic object type,

and you must use casting code when retrieving an item.

Some other useful Hashtable members include:

Remove deletes an item from the collection. You specify the key of the item you

want removed. This allows you to quickly remove an object using the following

syntax:

Col.Remove(ItemA)

Contains and ContainsKey return True or False, depending on whether a specified

key is in the Hashtable. This provides a quick way to perform a simple search.

ContainsValue returns True or False, depending on whether a specified object is in

the Hashtable. For example, in the previous code example where the Hashtable was

used to store Customer objects, you could call ContainsValue with a Customer

object. It would return True only if this object is already in the collection.

The Keys property provides a read-only collection of all the keys used in the

Hashtable.

The Values property provides a read-only collection of all the objects in the

Hashtable.

The Hashtable class works more or less the same way as the standard Visual Basic 6 Collection type, which is still included in Visual Basic .NET for backward compatibility. However, for most programming tasks, a

Page 221: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 221 2012

Hashtable is preferable to a generic collection, because a Hashtable ensures that every item has a key that can be used to locate or remove the item.

Without a key, the only way to find an item is by iterating through the entire collection and examining each object. Furthermore, only the Hashtable supports any type of object as a key. The generic collection is limited to string values.

Permutations and Scrabble finder - incomplete A permutation, by dictionary standards, is an ordered arrangement of a set of

objects, and permutating is the act or process of changing the lineal order of an

ordered set of objects. In other words, it's re-ordering the elements of a list, like an

array. So how is this valuable?

Imagine an array, consisting of the elements a, b, and c. We'll write this as (a,b,c).

When we permutate this array, we want to re-arrange the elements, so that the a is in

a different position relative to b and c. Of course, when we're done, we want to end

up with the following:

(a,b,c)

(a,c,b)

(b,a,c)

(b,c,a)

(c,a,b)

(c,b,a)

Page 222: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 222 2012

33. Sorting Socks project A poster on StackOverflow.com, presents an interesting project.

Yesterday I was pairing the socks from the clean laundry, and figured out the way I

was doing it is not very efficient. I was doing a naive search — picking one sock and

"iterating" the pile in order to find its pair. This requires iterating over n/2 * n/4 = n2/8

socks on average.

As a computer scientist I was thinking what I could do? Sorting (according to

size/color/...) of course came into mind to achieve an O(NlogN) solution.

Hashing or other not-in-place solutions are not an option, because I am not able to

duplicate my socks (though it could be nice if I could).

So, the question is basically:

Given a pile of n pairs of socks, containing 2n elements (assume each sock has

exactly one matching pair), what is the best way to pair them up efficiently with up to

logarithmic extra space? (I believe I can remember that amount of info if needed.)

http://stackoverflow.com/questions/14415881/how-to-pair-socks-from-a-pile-

efficiently

http://www.reddit.com/r/programming/comments/16x9a3/how_to_pair_socks_from_a

_pile_efficiently/

So create a program that can sort socks from a basket of laundry that contains all

sorts of laundry. Sure the easiest way is to iterate one sock over the entire laundry

basket as he says, but read the articles and see if we can create another way to sort

socks.

The laundry basket could start from a text file, or even a randomly created list of

laundry at runtime.

Read the Related Articles list on the right for further ideas.

Sounds like fun

Page 223: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 223 2012

34. The T shirt algorithm http://boingboing.net/2013/03/02/how-an-algorithm-came-up-with.html

Recently on Amazon a T shirt logo has created a lot of fuss. Lets see if we can

create a better algorithm, maybe even generated from internet searches as well, but

certainly using the dictionaries we have.

Here is the article ….

You may have heard that Amazon is selling a "KEEP CALM AND RAPE A LOT" t-

shirt. How did such a thing come to pass?

Well, as Pete Ashton explains, this is a weird outcome of an automated algorithm

that just tries random variations on "KEEP CALM AND," offering them for sale in

Amazon's third-party marketplace and printing them on demand if any of them

manage to find a buyer.

The t-shirts are created by an algorithm. The word “algorithm” is a little scary to some

people because they don’t know what it means. It’s basically a process automated by

a computer programme, sometimes simple, sometimes complex as hell.

Amazon’s recommendations are powered by an algorithm. They look at what you’ve

been browsing and buying, find patterns in that behaviour and show you things the

algorithm things you might like to buy.

Amazons algorithms are very complex and powerful, which is why they work. The

algorithm that creates these t-shirts is not complex or powerful. This is how I expect it

works.

1. Start a sentence with the words KEEP CALM AND.

2. Pick a word from this long list of verbs. Any word will do. Don’t worry, I’m sure

they’re all fine.

3. Finish the sentence with one of the following: A LOT, OFF, THEM, IF, THEM

or US.

4. Lay these words out in the classic Keep Calm style.

5. Create a mockup jpeg of a t-shirt.

6. Submit the design to Amazon using our boilerplate t-shirt description.

7. Go back to 1 and start again.

There are currently 529,493 Solid Gold Bomb clothing items on Amazon. Assuming

they survive this and don’t get shit canned by Amazon I wouldn’t be at all surprised if

they top a million in a few months.

It costs nothing to create the design, nothing to submit it to Amazon and nothing for

Amazon to host the product. If no-one buys it then the total cost of the experiment is

effectively zero. But if the algorithm stumbles upon something special, something that

is both unique and funny and actually sells, then everyone makes money.

Page 224: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 224 2012

http://www.programmableweb.com/api/amazon-ecommerce

http://aws.amazon.com/visualstudio/

Page 225: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 225 2012

35. Search and Sort Algorithms

Bubble Sort The first sorting algorithm to examine is the

bubble sort.

The bubble sort is one of the slowest

sorting algorithms available, but it is also

one of the simplest sorts to understand and

implement, which makes it an excellent

candidate for our first sorting algorithm.

The sort gets its name because values

“float like a bubble” from one end of the list

to another. Assuming you are sorting a list

of numbers in ascending order, higher

values float to the right whereas lower

values float to the left.

This behavior is caused by moving through

the list many times, comparing adjacent

values, and swapping them if the value to

the left is greater than the value to the

right.

There are some great animated images

here

http://en.wikipedia.org/wiki/Bubble_sort that

give a good overiew how it works.

Page 226: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 226 2012

Public Class Form1

'declare it globally from data Structures and Algorithmns P 88

Dim theArray As New ArrayList

Dim counter As Integer = 1

Dim strArray As String

Private Sub BubbleSort()

Dim outer, inner, temp As Integer

For outer = theArray.Count - 1 To 1 Step -1

For inner = 0 To outer - 1

'if the first number is bigger than the second number

If (theArray(inner) > theArray(inner + 1)) Then

'then pass the first number to a temp

temp = theArray(inner)

'make the second number replace the first number (really just copy them both across)

theArray(inner) = theArray(inner + 1)

'move the first number to replace the second number

theArray(inner + 1) = temp

End If

'this just prints each row of the array out in the listbox

strArray = ""

For i As Integer = 0 To theArray.Count - 1

strArray += theArray(i) & " "

counter += 1

Next

lbxSorted.Items.Add("Inner " & inner & ", Outer " & outer & ", " & strArray)

'end display

Next

Next

Page 227: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 227 2012

End Sub

Private Sub btnSort_Click(sender As Object, e As EventArgs) Handles btnSort.Click

LoadArray()

BubbleSort()

lbxSorted.Items.Add("====NEW SORT====")

'clear the array for the next run

theArray.Clear()

End Sub

Private Sub LoadArray()

'create the array add in random numbers

Dim count As Integer = 0

Do While count < 6

theArray.Add(GetRandom(1, 11))

count += 1

Loop

End Sub

Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer

' by making Generator static, we preserve the same instance (i.e., do not create new instances with the same seed over and over) between calls

Static Generator As System.Random = New System.Random()

Return Generator.Next(Min, Max)

End Function

End Class

Sort a list of words using Bubble sort

The String.Compare Method can be used to compare two words returning: A is less

than B, A s equal to B, A is greater than B.

We need to pass words into an array, then use Strong.Compare to sort them with

each other. Using this we can build a simple dictionary from a list of words.

http://msdn.microsoft.com/en-us/library/zkcaxw5y.aspx

Page 228: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 228 2012

Selection Sort The Selection sort works by starting at the beginning of the array, comparing the first

element with the other elements in the array.

The smallest element is placed in position 0, and the sort then begins again at

position 1 looking for the next smallest element in the array and moves it to position

1. This continues until each position except the last position has been the starting

point for a new loop.

Two loops are used in the SelectionSort algorithm. The outer loop moves from the

first element in the array to the next to last element; the inner loop moves from

the second element of the array to the last element, looking for values that are

smaller than the element currently being pointed at by the outer loop. After

each iteration of the inner loop, the most minimum value in the array is

assigned to its proper place in the array.

Public Class Form1

'declare it globally from data Structures and Algorithmns P 88

Dim theArray As New ArrayList

Dim strArray As String

Dim outer, inner, temp As Integer

'This sort works by starting at the beginning of the array, comparing the first element with the other elements in the array. The smallest element is placed in position 0, and the sort then begins again at position 1. This continues until each position except the last position has been the starting point for a new loop

Public Sub SelectionSort()

'The outer loop moves from the first element in the array to the next to last element;

For outer = 0 To theArray.Count - 2

Page 229: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 229 2012

'the inner loop moves from the second element of the array to the last element, looking for values that are smaller than the element currently being pointed at by the outer loop. After each iteration of the inner loop, the most minimum value in the array is assigned to its proper place in the array.

For inner = outer + 1 To theArray.Count - 1

If (theArray(inner) < theArray(outer)) Then

'Yes it is smaller then swap the numbers around

temp = theArray(outer)

theArray(outer) = theArray(inner)

theArray(inner) = temp

displayswap()

End If

displaynoswap()

Next

Next

End Sub

Private Sub displaynoswap()

'Print stuff out so you can see it

strArray = ""

For i As Integer = 0 To theArray.Count - 1

strArray += theArray(i) & " "

Next

lbxSorted.Items.Add("Outer (" & outer & ") " & ", Inner (" & inner & ") " & strArray & " " & theArray(outer) & " is smaller than " & theArray(inner))

'end display

End Sub

Private Sub displayswap()

'Print stuff out so you can see it

strArray = ""

For i As Integer = 0 To theArray.Count - 1

strArray += theArray(i) & " "

Next

lbxSorted.Items.Add("Outer (" & outer & ") " & ", Inner (" & inner & ") " & strArray & " " & theArray(inner) & " is bigger than " & theArray(outer) & " Swapped! ")

Page 230: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 230 2012

'end display

End Sub

Private Sub btnSort_Click(sender As Object, e As EventArgs) Handles btnSort.Click

lbxSorted.Items.Clear()

LoadArray()

SelectionSort()

'clear the array for the next run

theArray.Clear()

End Sub

Private Sub LoadArray()

'create the array add in random numbers

Dim count As Integer = 0

Do While count < 5

theArray.Add(GetRandom(1, 11))

count += 1

Loop

End Sub

Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer

' by making Generator static, we preserve the same instance (i.e., do not create new instances with the same seed over and over) between calls

Static Generator As System.Random = New System.Random()

Return Generator.Next(Min, Max)

End Function

End Class

Page 231: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 231 2012

Sequential Searching The most obvious type of search is to begin at the beginning of a set of records and

move through each record until you find the record you are looking for or you come to

the end of the records. This is called a sequential search.

A sequential search (also called a linear search) is very easy to implement. Start at

the beginning of the array and compare each accessed array element to the value

you’re searching for. If you find a match, the search is over. If you get to the end of

the array without generating a match, then the value is not in the array.

Public Class Form1

Dim theArray As New ArrayList

Dim randomNumber As Integer

Private Sub btnsearch_Click(sender As Object, e As EventArgs) Handles btnsearch.Click

lbxdisplay.Items.Clear()

' Initialize the random number generator

Randomize()

LoadArray()

' Calculate a random number between 1 and 10

randomNumber = Int(1 + 10 * Rnd())

' For Each item As Integer In theArray

Dim strArray As String

For i = 0 To theArray.Count - 1

'string holds the numbers for the display

strArray += theArray(i) & " "

'show if there is a match

If theArray(i) = randomNumber Then

Page 232: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 232 2012

lbxdisplay.Items.Add("The Random Number " & randomNumber & " is in the Array")

End If

Next

lbxdisplay.Items.Add("====Results ====")

lbxdisplay.Items.Add("The Random Number is " & randomNumber)

lbxdisplay.Items.Add("The array is " & strArray)

theArray.Clear()

End Sub

Private Sub LoadArray()

'create the array add in random numbers

Dim count As Integer = 0

Do While count < 6

theArray.Add(GetRandom(1, 11))

count += 1

Loop

End Sub

Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer

' by making Generator static, we preserve the same instance (i.e., do not create new instances with the same seed over and over) between calls

Static Generator As System.Random = New System.Random()

Return Generator.Next(Min, Max)

End Function

End Class

Page 233: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 233 2012

36. Advanced Search and Sort Algorithms

Making a sequential search faster: self-organizing data The fastest successful sequential searches occur when the data element being

searched for is at the beginning of the data set. You can ensure that a successfully

located data item is at the beginning of the data set by moving it there after it has

been found.

The concept behind this strategy is that we can minimize search times by putting

items that are frequently searched for at the beginning of the data set. Eventually, all

the most frequently searched for data items will be located at the beginning of the

data set. This is an example of self-organization, in that the data set is organized not

by the programmer before the program runs, but by the program while the program is

running.

It makes sense to allow your data to organize in this way since the data being

searched probably follow the “80–20” rule, meaning that 80% of the searches

conducted on your data set are searching for 20% of the data in the data set. Self-

organization will eventually put that 20% at the beginning of the data set, where a

sequential search will find them quickly.

Probability distributions such as this are called Pareto distributions, named for

Vilfredo Pareto, who discovered these distributions by studying the spread of income

and wealth in the late 19th century.

Lets use the Sequential Search program from earlier and just add a swap function.

Here is the solution with multiple

numbers the same.

The random number of 2 is three

times in an array of 112221. The

final array is 222111

Page 234: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 234 2012

New code below to change existing and add to your program.

Add a new global variable

Dim movednumberposition As Integer = 0

We need this so that its not always the first position that gets numbers added to.

Otherwise only the first place theArray(0) is used to store the number. With the

movednumberposition the first place is sued for the first number and the second

place is used for a second number etc.

Its primitive but it works.

Private Sub btnsearch_Click(sender As Object, e As EventArgs) Handles btnsearch.Click

lbxdisplay.Items.Clear()

' Initialize the random number generator

Randomize()

LoadArray()

' Calculate a random number between 1 and 10

randomNumber = Int(1 + 10 * Rnd())

' For Each item As Integer In theArray

Dim strArray As String

For i = 0 To theArray.Count - 1

'string holds the numbers for the display

strArray += theArray(i) & " "

'show if there is a match

If theArray(i) = randomNumber Then

lbxdisplay.Items.Add("The Random Number " & randomNumber & " is in the Array")

'swap the numbers in the array

swap(i)

End If

Next

lbxdisplay.Items.Add("====Results ====")

lbxdisplay.Items.Add("The Random Number is " & randomNumber)

lbxdisplay.Items.Add("The array is/was " & strArray)

theArray.Clear()

End Sub

Private Sub swap(ByRef match As Integer)

Dim temp As Integer

temp = theArray(match)

Page 235: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 235 2012

theArray(match) = theArray(movednumberposition)

theArray(movednumberposition) = temp

'make the next place the storage otherwise the same position gets changed

movednumberposition += 1

'display the new swopped array

Dim strArray As String

For i = 0 To theArray.Count - 1

'string holds the numbers for the display

strArray += theArray(i) & " "

Next

lbxdisplay.Items.Add("The new swapped array is " & strArray)

End Sub

Problems with this code:

If you search for an item, find it, and it moves to the top of the list when you search

for it later on it will be move to the new position further down the list! We can make a

rule that a data item is relocated to the beginning of the data set only if its location

lies outside the first 20% of the items in the data set.

To do this we add another criteria And i > (theArray.Count * 0.2) to the If statement

From

If theArray(i) = randomNumber Then

to

If theArray(i) = randomNumber And i > (theArray.Count * 0.2) Then

The other way we can rewrite the SeqSearch method is to swap a found item with

the element that precedes it in the data set similar to how data are sorted using the

Bubble sort.

Using this method the most frequently accessed items will eventually work their way

up to the beginning of the data set. This technique also guarantees that if an item is

already at the beginning of the data set it won’t move back down.

Using the Bubble Sort exercise rewrite your code, or create a new version of it to show this working.

This search still has a problem in that as the last item found goes in the next

available spot, there is nothing that shows what the number 1 searched item is. So if

someone searches for 3 90% of the time and then 5 there is nothing to show that 3

was far more important in searching than 5.

Page 236: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 236 2012

How to solve this? Create a frequency table of items that shows how many times an

item has been searched for and sort by the frequency table.

Use a Dictionary (Key / Value) to hold the items in the array and change the value, increment it by 1 each time a search has been made.

Page 237: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 237 2012

QuickSort Algorithm – Divide and conquer This is a very fast search algorithm with a small code footprint.

It is universally accepted that the QuickSort algorithm is the fastest sorting algorithm

and should be used for most sorting scenarios. The Sort method that is built into

several of the .NET Framework library classes is implemented using QuickSort,

which explains the dominance of QuickSort over other sorting algorithms.

To understand how the QuickSort algorithm works, imagine you are a teacher and

you have to alphabetize a stack of student papers.

You will pick a letter from the middle of the alphabet, such as M, putting student

papers whose name starts with A through M in one stack and those whose names

start with N through Z in another stack.

Then you split the A–M stack into two stacks and the N–Z stack into two stacks using

the same technique. Then you do the same thing again until you have a set of small

stacks (A–C, D–F,..., X–Z) of two or three elements that sort easily.

Once the small stacks are sorted, you simply put all the stacks together and you

have a set of sorted papers.

As you should have noticed, this process is recursive, since each stack is divided into

smaller and smaller stacks. Once a stack is broken down into one element, that stack

cannot be further divided and the recursion stops.

How do we decide where to split the array into two halves? There are many choices,

but we’ll start by just picking the first array element because if they are random,

chances are its not going to be the absolute top or bottom, just a number inbetween.

Once that choice is made, we next have to get the array elements into the proper

“half” of the array (keeping in mind that it is entirely possible that the two halves will

not be equal, depending on the splitting point).

Page 238: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 238 2012

(images from here http://www.codeproject.com/Articles/353509/Computer-

Algorithms-Quicksort )

Public Class Form1

Dim theArray As New ArrayList

Public Sub QSort()

'0 = first elelemt in the array, last element in the array

recQSort(0, theArray.Count - 1)

End Sub

Public Sub recQSort(ByVal first As Integer, ByVal last As Integer)

'recursion loop to divide down the array until if there is nothing there stop

If ((last - first) <= 0) Then

Return

Else

'make a pivot from the last entry in the array

Dim pivot As Integer = theArray(last)

Dim part As Integer = Me.Partition(first, last)

'run the same sub again, repeatedly

recQSort(first, part - 1)

recQSort(part + 1, last)

End If

End Sub

Public Function Partition(ByVal first As Integer, ByVal last As Integer) As Integer

Page 239: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 239 2012

'get the pivot from the first

Dim pivotVal As Integer = theArray(first)

'lbxdisplay.Items.Add("The pivotvalue is " & pivotVal)

'get the first element (0)

Dim theFirst As Integer = first

Dim okSide As Boolean

'add 1 to first to move along the array

first += 1

Do

'set to true

okSide = True

While (okSide) 'while its true

'if first is bitter than the pivot value

If (theArray(first) > pivotVal) Then

okSide = False

Else

first += 1

okSide = (first <= last) 'true

End If

End While

okSide = (first <= last)

While (okSide) 'is true

If (theArray(last) <= pivotVal) Then

okSide = False

Else

last -= 1

okSide = (first <= last)

End If

End While

'main engine swapping elements

If (first < last) Then

Swap(first, last)

display()

first += 1

last -= 1

End If

Loop While (first <= last)

Swap(theFirst, last)

display()

Return last

End Function

Public Sub Swap(ByVal item1 As Integer, ByVal item2 As Integer)

Dim temp As Integer = theArray(item1)

theArray(item1) = theArray(item2)

theArray(item2) = temp

End Sub

Page 240: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 240 2012

Sub display()

'display the new swopped array

Dim strArray As String

For i = 0 To theArray.Count - 1

'string holds the numbers for the display

strArray += theArray(i) & " "

Next

lbxdisplay.Items.Add("Swapped array: " & strArray)

End Sub

Private Sub btnsearch_Click(sender As Object, e As EventArgs) Handles btnsearch.Click

lbxdisplay.Items.Clear()

' Initialize the random number generator

Randomize()

LoadArray()

QSort()

End Sub

Private Sub LoadArray()

'create the array add in random numbers

Dim count As Integer = 0

Do While count < 20

theArray.Add(GetRandom(1, 100))

count += 1

Loop

End Sub

Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer

' by making Generator static, we preserve the same instance (i.e., do not create new instances with the same seed over and over) between calls

Static Generator As System.Random = New System.Random()

Return Generator.Next(Min, Max)

End Function

End Class

Page 241: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 241 2012

An Improvement to the QuickSort Algorithm

If the data in the array are random, then picking the first value as the “pivot” or

“partition” value is perfectly acceptable. Otherwise, however, making this choice will

inhibit the performance of the algorithm.

A popular method for picking this value is to determine the median value in the array.

You can do this by taking the upper bound of the array and dividing it by 2, for

example using the following code:

Dim pivotVal As Integer = (theArray.Count - 1) / 2

Studies have shown that using this strategy can reduce the running time of the

algorithm by about 5%

Page 242: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 242 2012

37. Stack and the Heap Because all data types are based on the core Object class, every variable you

dimension can be assured of having a set of common characteristics. However, this

logical inheritance does not require a common physical implementation for all

variables.

This is important because while everything in .NET is based on the Object class,

under the covers .NET has two major implementations of types: value and reference.

For example, what most programmers consider to be some of the basic underlying

types, such as Integer, Long, Character, and even Byte, are not implemented as

classes. This is important, as you’ll see when you look at boxing and the cost of

transitioning between value types and reference types. The difference between value

types and reference types is an underlying implementation difference:

Value types represent simple data storage located on the stack. The stack is

used for items of a known size, so items on the stack can be retrieved faster

than those on the managed heap.

Reference types are based on complex classes with implementation

inheritance from their parent classes, and custom storage on the managed

heap. The managed heap is optimized to support dynamic allocation of

differently sized objects.

Note that the two implementations are stored in different portions of memory. As a

result, value types and reference types are treated differently within assignment

statements, and their memory management is handled differently. It is important to

understand how these differences affect the software you will write in Visual Basic.

Understanding the foundations of how data is manipulated in the .NET Framework

will enable you to build more reliable and better-performing applications.

Consider the difference between the stack and the heap. The stack is a

comparatively small memory area in which processes and threads store data of fixed

size. An integer or decimal value needs the same number of bytes to store data,

regardless of the actual value. This means that the location of such variables on the

stack can be efficiently determined. (When a process needs to retrieve a variable, it

has to search the stack. If the stack contained variables that had dynamic memory

sizes, then such a search could take a long time.)

Reference types do not have a fixed size—a string can vary in size from two bytes to

nearly all the memory available on a system. The dynamic size of reference types

means that the data they contain is stored on the heap, rather than the stack.

However, the address of the reference type (that is, the location of the data on the

heap) does have a fixed size, and thus can be (and, in fact, is) stored on the stack.

By storing a reference only to a custom allocation on the stack, the program as a

whole runs much more quickly, as the process can rapidly locate the data associated

with a variable.

Page 243: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 243 2012

38. Stack and Queue – not done Peak and poke

39. Delegates – to do

40. Func and Lambda In the simplest terms, a lambda expression is an anonymous method that is

sometimes referred to as an inline method or function. It is a function or

subroutine without a name that can be used wherever a delegate is valid. The

examples below use a Func to pass data in and out on the left hand side of the = and

a Lamba to calculate on the right hand side.

An anonymous method is an unnamed method that is created inline, or inside of a

method, rather than as a method block itself. Here is the lamba of the code below

Function(x As Integer) x * 2. Note that by itself it means nothing, its anonymous.

They behave just like any other method and can have both parameters and return

values. The lambda expression syntax starts with the keyword Function, which is

then followed by an argument list and a single expression.

The following is an example of a basic lambda expression definition. It defines

doubleIt as a lambda expression that takes an integer and returns an integer. The

lambda expression effectively takes the input, multiplies it by 2, and then returns the

result.

Dim doubleIt As Func(Of Integer, Integer) = Function(x As Integer) x * 2

Add the function in a button click (btnLambda) then put a number in the function

Me.Text = doubleIt(5) and run it to see it work.

You can see that the Func function to the left of the = has an in parameter and an

out parameter, in this case below both string. In the above example they were both

Integer. The Func type essentially a delegate that has the return type (out) specified

as the last generic parameter and allows up to four arguments to be supplied (in)

as the leading generic parameters

Page 244: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 244 2012

The second part after the = is the lambda. Here x is setting the string to Upper

Function(x As String) x.ToUpper()

By itself x means nothing, its only in the context of the first half of the code that the

use becomes apparent. A lambda expression can be used as an argument to

another function. In this case it is called a higher-order procedure.

Here are two parameters being passed to the lambda. Two strings in and one string

out. Each string in is then given a name (x and y) then acted upon and the result

returned. This is what is returned … x.ToUpper() & " " & y.ToLower

Dim AddText As Func(Of String, String, String) = Function(x As String, y As String) x.ToUpper() & " " & y.ToLower

Private Sub btnlambda_Click(sender As Object, e As EventArgs) Handles btnlambda.Click

Me.Text = AddText("Some text", "SOME MORE TEXT")

End Sub

Lambdas are used extensively in database (Linq to Entities) coding and in C#.

http://msdn.microsoft.com/en-us/library/bb531253.aspx

http://msdn.microsoft.com/en-us/magazine/cc163362.aspx#S1

41. Unit Testing – to do http://msdn.microsoft.com/en-us/library/ms182524%28v=vs.90%29.aspx

42. Recursion - incomplete Recursion is repeatedly calling the same function to provide some meaningful output;

at least that's what a computer scientist will tell you. A more mathematical definition

of recursion is plugging in some start values into a function, getting the function's

results and reapplying them to the orginal function.

Now, we have to trace our way back up! See, the factorial function was called six

times. At any function level call, all function level calls above still exist! So, when we

have N = 2, the function instances where N = 3, 4, and 5 are still waiting for their

return values.

So, the function call where N = 1 gets retraced first, once the final guy returns 0. So,

the function call where N = 1 returns 1*1, or 1. The next higher function call, where N

Page 245: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 245 2012

= 2, returns 2 * 1 (1, because that's what the function call where N = 1 returned). You

just keep working up the chain.

Where N = 2, 2*1, or 2 was returned

Where N = 3, 3*2, or 6 was returned

Where N = 4, 4*6, or 24 was returned

Where N = 5, 5*24, or 120 was returned

And since N = 5 was the first function call (hence the last one to be recalled), the

value 120 is returned.

http://www.4guysfromrolla.com/webtech/060299-2.shtml

Page 246: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 246 2012

43. Overloaded Methods When we use a method or property, we type the “dot” and a list of methods or

properties pops up. For example in the MessageBox object, we click the “dot” type

the word “Show” and a left bracket and we can see this:

1 of 21 Show(Text as String etc…

This says that there are 27 different uses of the “Show” method and as you type

through the parameters, the one it is expecting is made bold so you can see what to

type.

The way that has been achieved is to have several methods with the same name but

with different parameters.

First, we need to make a base class with some useful properties and methods. Let’s

go for something that will translate a string from one thing to another. I’m just going to

reverse the string in one method and reverse and make upper case in the other.

Right-click on the project name in the Solution Explorer at the right and add a class.

Name it “Translate”

Now we need to add two private member-variables, two properties and two methods.

As you can see, there’s little going on here at all. I’ve used two methods called

“Process” which have different parameters.

Public Class translate

Private _normText As String

Private _revText As String

' to hold the normal text (text to be processed)

Public Property NormText() As String

Get

Return _normText

End Get

Page 247: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 247 2012

Set(ByVal value As String)

_normText = value

End Set

End Property

' to hold the finished (processed) text

Public ReadOnly Property RevText() As String

Get

Return _revText

End Get

End Property

' first process method

Public Overloads Sub Process(ByVal t As String)

Dim temp As String

Dim j As Integer

temp = ""

For j = t.Length - 1 To 0 Step -1

temp &= t.Substring(j, 1)

Next

_revText = temp

End Sub

' second process method (has an extra Boolean parameter)

Public Overloads Sub Process(ByVal t As String, ByVal caps As Boolean)

Dim temp As String

Dim j As Integer

temp = ""

For j = t.Length - 1 To 0 Step -1

temp &= t.Substring(j, 1)

Next

'new

If caps Then

_revText = temp.ToUpper

Else

_revText = temp.ToLower

End If

End Sub

End Class

You can see that we have a bit of functionality here and the two properties which will

contain the “Normal” text and the “Processed” text.

We need to make a form now that will let us use this class. We need a couple of text

boxes and a couple of buttons. Here’s mine:

Page 248: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 248 2012

Please name the textboxes - top one “txtNorm” and bottom one “txtRev”

Also, the first button is “btnRev” and the second is “txtRevCaps”, the top Radiobutton

“rb1” and the other “rb2”. Change the Text and “Check” “Upper Case”

Add a suitable caption to the form by changing its “Text” property, now we can set up

the code.

Public Class Form1

Dim trans As New translate

Private Sub btnreverse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnreverse.Click

If txtNorm.Text <> "" Then

' load the normal text

Trans.NormText = txtNorm.Text

' process it using the first method (no boolean)

Trans.Process(txtNorm.Text)

' display result

txtresult.Text = trans.RevText

End If

End Sub

Private Sub btnRC_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRC.Click

If txtnorm.Text <> "" Then

' load the normal text

trans.NormText = txtnorm.Text

' process it - force the second method by adding a boolean value

If rbUpperCase.Checked Then

trans.Process(txtnorm.Text, True)

Else

Here I have two text

boxes

and two buttons and two Radio

Buttons

Page 249: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 249 2012

trans.Process(txtnorm.Text, False)

End If

' display result

txtresult.Text = trans.RevText

End If

End Sub

Private Sub txtresult_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtresult.Enter

' don't want people typing here so send them to txtNorm

txtnorm.Focus()

End Sub

End Class

OK - now to explain the code. We need a global Translator object because I want to

use it from one or other of the button clicks so I’ve created a global variable called

“Trans” of type “Translator”.

Then, we don’t want people to click into the textbox “txtresult” so I’ve put a bit of code

there that says when focus enters this control, send it back to “txtNorm”

Finally, there’s the button click code for each button. Pretty much the same except for the Boolean parameter which is passed through to the method causing it to use the second “Process” method. ByVal caps As Boolean

If caps Then

_revText = temp.ToUpper 'this is the true

Else

_revText = temp.ToLower 'this is the false

End If

Back in the code …

If rbUpperCase.Checked Then

trans.Process(txtnorm.Text, True)

Else

trans.Process(txtnorm.Text, False)

End If

We could have left out the code handling the Boolean and it still would have used the

second “Process” method to be used. I’ve used “True” for upper-case and “False” for

lower-case. But we could add whatever code we required.

Here’s three runs of the program. First just the first button and then the second

button.

Page 250: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 250 2012

So here we can see that each of the possible outcomes has been tested to ensure

that everything worked as planned.

Here, the first button was

clicked giving the

expected result

Whereas here, the

second button was

clicked showing that it

used the second method -

radio button set to “Upper

Case”

Again here, the second

button was clicked

showing that it used the

second method - radio

button set to “Lower

Case”

Page 251: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 251 2012

ADO.Net 4 and SQL

44. TSQL Cheat Sheet

String Functions

Exact Numerics Bit Tinyint Smallint Bigint Decimal Money Numeric Approximate Numerics Float Real Date and Time Smalldatetime Datetime Timestamp Strings Char Varchar Text Unicode Strings Nchar Nvarchar Ntext Binary Strings Binary Image Varbinary Miscellaneous Cursor Table Xml Sql_variant

Common Functions

AVG() Returns the average value COUNT() Returns the number of rows FIRST() Returns the first value LAST() Returns the last value MAX() Returns the largest value MIN() Returns the smallest value SUM() Returns the sum UCASE() - Converts a field to upper case LCASE() - Converts a field to lower case MID() - Extract characters from a text field LEN() - Returns the length of a text field ROUND() - Rounds a numeric field to the number of decimals specified NOW() - Returns the current system date and time FORMAT() - Formats how a field is to be displayed

Date Functions

DATEADD (datepart, number, date) DATEDIFF (datepart, start, end) DATENAME (datepart, date) DATEPART (datepart, date) DAY (date) GETDATE() GETUTCDATE() MONTH (date) YEAR (date)

Operators Allowed in the WHERE Clause

With the WHERE clause, the following operators can be used: Operator Description = Equal <> Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern IN To specify multiple possible values for a column Note: In some versions of SQL the <> operator may be written as !=

Logical processing order of select

FROM table ON join condition JOIN table WHERE clauses GROUP BY columns WITH CUBE / WITH ROLLUP HAVING condition SELECT columns DISTINCT ORDER BY columns TOP % or number

Page 252: Intro to VB 7 March 2013

Vision College Friday, 8 March 2013 ADO.Net

Page 252 2012

CTES - Common Table Expressions

WITH cteName ( columnList ) AS ( SELECT statement ) SELECT columns FROM cteName INNER JOIN table ON condition

Recursive CTEs

WITH cteName ( columnList ) AS ( -- Anchor statement: SELECT columns FROM table… UNION ALL Recursion statement: SELECT columns FROM table… INNER JOIN cteName ON … ) SELECT columns FROM cteName

Over and partition by

/* Aggregate functions include COUNT, MIN, MAX, AVG, ROW_COUNT(), etc. */ SELECT agg_func(col1) OVER(), agg_func(col1)

OVER(PARTITION BY col2), columns FROM table…

Create a Stored Procedure

CREATE PROCEDURE name @variable AS datatype = value AS -- Comments SELECT * FROM table GO

Create a Trigger

CREATE TRIGGER name ON table FOR DELETE, INSERT, UPDATE AS -- Comments SELECT * FROM table GO

Page 253: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 253 2013

Introduction

Most of today's applications need to interact with database systems to persist, edit or view

data. In .NET, data access services are provided through ADO.NET components. ADO.NET

is an object oriented framework that allows you to interact with database systems. We usually

interact with database systems through SQL queries or stored procedures.

The best thing about ADO.NET is that it is extremely flexible and efficient. ADO.NET also

introduces the concept of disconnected data architecture.

In traditional data access components, you made a connection to the database system and then

interacted with it through SQL queries using the connection. The application stays connected

to the DB system even when it is not using DB services. This commonly wastes valuable and

expensive database resources, as most of the time applications only query and view the

persistent data.

ADO.NET solves this problem by managing a local buffer of persistent data called a data set.

Your application automatically connects to the database server when it needs to run a query

and then disconnects immediately after getting the result back and storing it in the dataset.

This design of ADO.NET is called disconnected data architecture and is very much similar to

the connectionless services of HTTP on the internet. It should be noted that ADO.NET also

provides connection oriented traditional data access services.

Traditional DB creates a continuous connection tying up resources.

ADO just connects in to create a subset of the database, a DataSet

Another important aspect of disconnected architecture is that it maintains a local repository of

data in the dataset object. The dataset object stores the tables, their relationships and their

different constraints. The user can perform operations like update, insert and delete on this

local dataset. The changes made to the dataset are applied to the actual database as a batch

when needed. This greatly reduces network traffic and results in better performance.

ADO.NET provides data access services in the Microsoft .NET platform.

Page 254: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 254 2013

You can use ADO.NET to access data by using the .NET Framework data providers which

are:

Data Provider for SQL Server (System.Data.SqlClient).

Data Provider for OLEDB (System.Data.OleDb).

Data Provider for ODBC (System.Data.Odbc).

Data Provider for Oracle (System.Data.OracleClient).

There are two central components of ADO.NET classes: the DataSet, and the .NET

Framework Data Provider.

Data Provider is a set of components including:

the Connection object (SqlConnection, OleDbConnection, OdbcConnection, OracleConnection)

the Command object (SqlCommand, OleDbCommand, OdbcCommand, OracleCommand)

the DataReader object (SqlDataReader, OleDbDataReader, OdbcDataReader, OracleDataReader)

and the DataAdapter object (SqlDataAdapter, OleDbDataAdapter, OdbcDataAdapter, OracleDataAdapter).

DataSet object represents a disconnected cache of data which is made up of

DataTables and DataRelations that represent the result of the command.

ADO.NET was built for a disconnected architecture , so it enables truly disconnected

data access and data manipulation through its Dataset Object, which is completely

independent from the Data Source.

The ADO.NET Object Model

Page 255: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 255 2013

How it works

You first get a connection to a data source, which means using a data provider to

access a database. The default data provider that Visual Basic .NET works with is

Microsoft's SQL Server, version 7.0 or later, and I'll use that data provider in this

book.

However, Visual Basic also can work with any data provider that can support Open

Database Connectivity (ODBC), such as Oracle. To work with SQL server, you use

ADO.NET SQLConnection objects, and to work with any other data provider, you

use ADO.NET OleDbConnection objects.

Tip Studies have shown that data access with Visual Basic .NET is up to 70 percent faster with SQL Server connections than with standard OLE-DB connections.

After you have a connection to a data source, you create a data adapter to work with

that data. You need a data adapter because datasets do not maintain any active

connection to the database—they are disconnected from the database.

The data adapter is what actually applies your SQL statements to a database and

causes your datasets to fill with data. Data adapters are there to apply your

commands to the database— because datasets are disconnected from that

database—and they're fundamental to the whole process. To work with the SQL

Server data provider, you use SQLDataAdapter objects, and to work with ODBC

data providers, you use OleDbAdapter objects.

Once you have a data adapter, you can generate a dataset using that adapter.

Datasets are what you actually work with in your code when you want to use data

from databases. (Although, note that in addition to datasets, there are also data

readers, which are fast, read-only mini-datasets that you can only move through

records with in ascending order)

For example, to get access to the data in a table, I would

1. first create a connection to the database the table was stored in,

2. then create an adapter with the SQL to retrieve that table (for example, if the

table was named students, that SQL might be "SELECT * FROM students"),

and

3. then fill a DataSet object using that adapter. Note that each data adapter can

handle only one SQL query at a time, but DataSet objects can store multiple

tables, and to place multiple tables in a dataset, you can use multiple data

adapters—see "Adding Multiple Tables to a Dataset" in this chapter.

Tip The names of tables and fields in datasets are case-insensitive, so the students table is the same as the Students table or the STUDENTS table.

Those are the three objects that it's essential to know about:

1. Data connections to connect to the database,

2. Data adapters to execute SQL with

Page 256: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 256 2013

3. and datasets to store the data—as returned from data adapters—that your

code will actually work on.

That's a simplified view, because there are many other objects, but it fits the majority

of scenarios..

When you decide whether your application should use a DataReader or a DataSet

consider the type of functionality that your application requires.

Use a DataSet to do the following:

Cache data locally in your application so that you can manipulate it. If you only

need to read the results of a query, the DataReader is the better choice.

Remote data between tiers or from an XML Web service.

Interact with data dynamically such as binding to a Windows Forms control or

combining and relating data from multiple sources.

Perform extensive processing on data without requiring an open connection to

the data source, which frees the connection to be used by other clients.

DataReader

If you do not require the functionality provided by the DataSet, you can improve the

performance of your application by using the DataReader to return your data in a

forward-only, read-only manner.

Although the DataAdapter uses the DataReader to fill the contents of a DataSet, by

using the DataReader, you can boost performance because you will save memory

that would be consumed by the DataSet, and avoid the processing that is required to

create and fill the contents of the DataSet.

Accessing Data using ADO.NET overview Data access using ADO.NET involves the following steps:

• Defining the connection string for the database server

• Defining the connection (SqlConnection or OleDbConnection) to the

database using a connection string

• Defining the command (SqlCommand or OleDbCommand) or command string

that contains the query

• Defining the Data Adapter (SqlDataAdapter or OleDbDataAdapter) using the

command string and the connection object

• Creating a new DataSet object

• If the SQL command is SELECT, filling the DataSet object with the results of

the query through the Data Adapter

• Reading the records from the DataTables in the DataSets using the

DataRow and DataColumn objects

• If the SQL command is UPDATE, INSERT or DELETE. The dataset will be

updated through the data adapter

• Accepting to save the changes in the DataSet to the database

Page 257: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 257 2013

DataSet

The DataSet is a cache of data that is stored in memory. It’s a lot like a mini

database engine, but its data exists in memory. You can use it to store data in tables,

and using the DataView component you can query the data in various ways.

The DataSet is very powerful. In addition to storing data in tables, it stores a rich

amount of metadata, or ‘‘data about the data.’’ This includes things like table and

column names, data types, and the information needed to manage and undo

changes to the data. All of this data is represented in memory in Extensible Markup

Language (XML). A DataSet can be saved to an XML file and then loaded back into

memory very easily. It can also be passed in XML format over networks, including

the Internet.

Because the DataSet component stores all of the data in memory, you can scroll

through the data both forward and backward, and make updates to the data in

memory.

DataGridView

The DataGridView control is a container that allows you to bind data from your data

source and have it displayed in a spreadsheet-like format, displaying the columns of

data horizontally and the rows of data vertically.

The DataGridView also provides many properties that allow you to customize the

appearance of the component itself, as well as properties that allow you to customize

the column headers and the display of data.

More important, though, are the quick links at the bottom of the Properties window for

the Data- GridView, which allow you to customize the appearance of the

DataGridView itself through several predefined format styles.

BindingSource

The BindingSource acts like a bridge between your data source (DataSet) and your

data-bound controls (that is, controls that are bound to data components). Any

interaction with the data from your controls goes through the BindingSource, which in

turn communicates with your data source.

For example, your DataGridView control will be initially filled with data. When you

request that a column be sorted, the DataGridView control will communicate that

intention to the BindingSource, which in turn communicates that intention to the data

source.

The BindingSource is the component that you will bind to the DataSource property of

your controls.

BindingNavigator

The BindingNavigator control provides a standard UI that enables you to navigate

through the records in your data source. The BindingNavigator control is bound to

your BindingSource component much like the DataGridView control is. When you

click the Next button in the BindingNavigator, it in turn sends a request to the

BindingSource for the next record, and the BindingSource in turn sends the request

to the data source.

Page 258: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 258 2013

TableAdapter

There’s one last component to talk about: the TableAdapter. This component does

not reside in the Toolbox but can be automatically generated for you depending on

how you add your data access components to your project.

The TableAdapter contains the query that is used to select data from your database,

as well as connection information for connecting to your database. It also contains

methods that will fill the DataSet in your project with data from the database. You can

also choose to have the TableAdapter generate INSERT, UPDATE, and DELETE

statements based on the query that is used to select data.

Data Binding

Data binding means taking data referenced by your BindingSource and binding it to a

control. In other words, the control will receive its data from your data access

components, and the data will be automatically displayed in the control for the user to

see and manipulate. In Visual Basic 2010, most controls support some level of data

binding. Some are specifically designed for it, such as the DataGridView and

TextBox.

ADO.NET Namespaces

System.Data namespace contains

System.data.SqlClient for accessing SQL Server databases

System.Data.OleDb for accessing OLE DB-compliant databases (e.g. ACCESS)

Page 259: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 259 2013

Creating a Data Connection using the Wizard Turn on the data Sources tab

Choose a database from the options

Go Browse to find your database (assuming you have put it somewhere easy to find

like C Drive first)

Choose your database (4 ships)

Page 260: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 260 2013

Choose YES to copy the file into your current project.

Choose all the objects to have in your dataset.

You now have a working database in your Project!

Drag the following fields onto your form and run.

Drag an ID field on to your form first to set the data properties then when you use a DataGridView it will all work OK. Otherwise it’s a pain in the ***

Each time you built your project the database file is copied to the output directory and

used from there. Any changes you make during the build to the DB is lost when you

rebuild it as the original DB is reloaded over the existing one you are using. Set the

Copy to Output setting to “copy if newer” so that the copy in the output directory won’t

Page 261: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 261 2013

be overwritten unless the database file on the project directory contains the more

current data.

Click “Show all Files” to see the dataset created from the

database. The Files in the Solution Explorer are called

the Schema.

Drag a DataGridView onto your form from the Data

Toolbox. It displays data from the data source in a grid.

The toolbar is also added at the same time.

The DataGridView adds 5 objects to the design tray at the bottom.

The Dataset – contains the table used

The TableAdapter – provides commands that can be used with the table in the

database. Also manages the flow of data between the database and the dataset.

The TableAdapterManager – to write the data in two or more tables to the database

to ensure integrity.

Page 262: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 262 2013

The BindingNavigator – defines the toolbar that contains the controls for working

with the data source.

The code behind the program to date

The TableAdapter Fill method loads the data into the DataSet Object.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'TODO: This line of code below loads data into the '_4shipsDataSet.Ships' table. You can move, or remove it, as needed.

Me.ShipsTableAdapter.Fill(Me._4shipsDataSet.Ships)

End Sub

When the user changes data in the DataGridView the changes are updated to the

However the changes aren’t saved to the database until the user clicks save on the

Toolbar with the ShipsBindingNavigatorSaveItem_Click

Private Sub ShipsBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShipsBindingNavigatorSaveItem.Click

Me.Validate()

Me.ShipsBindingSource.EndEdit()

Me.TableAdapterManager.UpdateAll(Me._4shipsDataSet)

End Sub

Me.Validate() does stuff mostly unimportant that validates the data to be saved.

Me.ShipsBindingSource.EndEdit() ends the editing on that row and allows it to be

saved. Data on a row can’t be saved until the next row is selected.

Me.TableAdapterManager.UpdateAll(Me._4shipsDataSet). Saves the changes back to the

database

Page 263: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 263 2013

How to use the Dataset Designer Choose the dataset designer to work with a graphical interface.

Note how it works with 2 tables. Although it looks like ShipName is connected to

Surname, it’s not, its connected to Boat.

Note the TableAdapter lists the queries used in each table. Fill is

the main query and generates the Insert, Update and delete statements for the table.

The SQL statement from the Query is found in the Properties window.

Right click on a query and Preview Data to see what your query retrieves.

Page 264: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 264 2013

Text Boxes - Formatting and Advanced Binding Drag a textbox onto the form from the Data Sources

Build the program at least once to tie in the fields to the dataset. Then when you look

in the Properties you will see under Text the BindingSource.

If you see that then when you click on DataBindings you will find (Advanced)

Click on (Advanced) to open the Formatting and Advanced Binding window

Page 265: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 265 2013

Using a DataGrid to create a Master/Detail form A form that displays data from a main and related table is called a

Master/Detail Form.

You can see the relationship in the DataSources Window, The ship-

Name table shows up twice also nested under the Ships Table. This

indicates that the tables have a relationship with each other.

To create a DataGridView control simply drag the ship-Name table

from this subordinate place into the form and it immediately creates

the correct binding source and table adapter objects.

Change the columns using the smart tag system to edit, and delete fields using the

check boxes.

Header Text is the field at the top of the column.

Edit this to better describe the contents of the

column.

You can edit the cell style to format the

columns by clicking on Default Cell Style.

Page 266: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 266 2013

Add columns to your grid that hold extra features

such as Buttons, text boxes, and combo boxes.

Add the button detail and then use the Edit columns

to set the following

Here is what it looks like ….

Page 267: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 267 2013

Creating a Parameterized Query Click on the Smart tab for the ID field then select Add Query and call it

FillByPassengerID

We are going to make a Paramaterised Query where someone types in the ID to see

the people,. So add Where ID = ? to the Query text as above.

Note: We are using ? as it is understood by an MDB based table if it was an SQL DB it would be ID = @ID.

Now when you type in a number and click on the FillBy button it shows the person

Click on the Smart Tab on the Data Grid and choose New Query

Add Where Boat = ? and save it as By Boat Name.

Now when you run it you can type in the boat name and see the boat.

Page 268: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 268 2013

Back in the dataset Schema you can see the Query you have created

Page 269: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 269 2013

Create a new 4 new buttons on the same toolbar line as shown below.

Name them Sir George Seymour, Cressy, Randolph, Charlotte Jane. Set them as

In the Copy the code you made for the first button FillByBoatName and replace them

with the names of the ships like…

Private Sub btnRandolph_Click(sender As System.Object, e As System.EventArgs) Handles btnRandolph.Click

'Randolph

Try

Me.ShipsTableAdapter.FillByboatname1(Me._4shipsDataSet.Ships, "Randolph")

Catch ex As System.Exception

System.Windows.Forms.MessageBox.Show(ex.Message)

End Try

End Sub

Finally you end up with something like

And then you can delete the first Fillbyboatname.

Page 270: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 270 2013

Creating Queries in the Table Adapter You can add queries directly to the table Adapter and then call them from the

program.

Follow the windows

Page 271: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 271 2013

SELECT ID, Surname, [First names], Age, Sex, Status, Children, Family, Occupation, Fare, Cabin, Boat, Type, Embarked, DELATE FROM Ships

WHERE type = 'Colonist'

Order By Surname

Fill the existing datatable

Page 272: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 272 2013

Back in your code make a new button on the toolbar and call it Colonist

In the code for it add the following.

Private Sub TSBcolonist_Click(sender As System.Object, e As System.EventArgs) Handles TSBcolonist.Click

Try

Me.ShipsTableAdapter.FillByColonist(Me._4shipsDataSet.Ships)

Catch ex As System.Exception

System.Windows.Forms.MessageBox.Show(ex.Message)

End Try

End Sub

Clicking the Colonist button should return the following.

Page 273: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 273 2013

Return a single value from the Database Create a Query as shown above then choose Single Value. Use the SQL statement

SELECT AVG(Age) FROM Ships and save as AverageAge

Create a button called AverageAge. I have also tidied up

the tool bars deleting out the early stuff.

Add the code below

Me.ShipsTableAdapter.AverageAge() gets the function

(its called a function because it returns a value) and formats it to 2 decimal places

and passes to a label.

There is also a test one passed to the me.Text

Private Sub TSBAverageAge_Click(sender As System.Object, e As System.EventArgs) Handles TSBAverageAge.Click

Try

Me.Text = Me.ShipsTableAdapter.AverageAge()

lblage.Text = "Average age " & FormatNumber(Me.ShipsTableAdapter.AverageAge(), 1)

Catch ex As System.Exception

System.Windows.Forms.MessageBox.Show(ex.Message)

End Try

End Sub

Page 274: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 274 2013

Using the same structure as above create a query

and attach it to a button called ‘How Many Males’

that counts how many males there are on the ship.

SELECT COUNT(Sex) FROM Ships

WHERE Sex = 'M'

Output it to the lblage.Text field

Create a third query to find how many of the males are married. Add the output to the

lblage.text field to generate an output as seen below.

Using the table below find the oldest and the youngest males. Make 2 new queries to

hold each data using MAX and MIN.

Output as a string in the same label as seen here

Page 275: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 275 2013

Using the Query Builder Instead of creating the SQL manually you can use a Query Builder to make it for you.

This can be easier and more accurate than making it yourself however you lose the

ego boost of writing a good SQL Statement.

Create a new Query as we have earlier however when you enter the SQL window

click the button.

As you build your Query it automatically writes the SQL and when you want to see

the output you press

Create the Query Below by unclicking the Delate field at the top, then adding in the

following filters

WHERE (Boat = 'Cressy') AND (Age < 30) AND (Sex = 'M')

Page 276: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 276 2013

Create a button on the Form to show the Data in the same table.

Create a new Query to find all people who’s first name begins with B and are

between 10 and 50 years old

Wildcard characters are shown with a %. B% means every word starting with B.

A range of numbers or dates can be given with the BETWEEN term

WHERE ([First names] LIKE 'B%') AND (Age BETWEEN 10 AND 50)

Create a button to show them off as per the last exercise.

Page 277: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 277 2013

You can create an expression, a calculated field and name it in the Alias field.

The COUNT will count how many of each type of boat there is, and when combined

with Group By will show how many people came on each boat. People is a name

given to the new field that is created, the name of the Expression.

Group By will list each unique entry of Boats (ie: the 4 of them).

SELECT Boat, COUNT(Boat) AS People

FROM Ships

GROUP BY Boat

Note: this query doesn’t output correctly back on the form. I am not sure why.

However the design is still important.

Page 278: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 278 2013

45. Practical – Creating queries with the Cars

Database Create a new application and import the Cars database to use.

1. Build a DataGrid and load the data into it.

2. Resize the columns to get a better view of the contents.

3. Move AP (Automatic Price – Price for Automatic cars) and MP (manual Price

for cars) to 4th and 5th place.

4. Delete the deleted field.

Page 279: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 279 2013

Using the NZ Cars database, create queries to solve the problems below. Save each

query that you create on a button on the ToolBarStrip

1. List the make and model of cars that have 2 Doors

2. Count the number of automatic cars in the database.

3. List the make and model of automatic cars that have two doors.

4. Count the number automatic cars that have two doors.

5. List in alphabetical order of make, then model the cars that are less than

1000 cc

6. Count the number of cars that are less than 1000 cc

7. Fred's garage will only fit a car that is 3500mm or less. How many different

car models can he choose from? Create a query that returns the number of

cars.

8. Find the Make and Model of the highest priced automatic BMW. Hint you

need to use two queries in a similar way to the above problem.

9. List in order of make then model the cars that have 5 doors, are manual

and have a power rating that is greater than or equal to 70kw and less than

or equal to 80kw.

10. Modify the query in 10 above so that it returns the number of cars. Hint

Use the count function and change 'Group by' to 'Where'

11. Tom wants to buy a new car that in the price range 20000 to 23000 dollars

inclusive. He doesn't want a make that starts with either the letter T or the

letter F. Produce a list in alphabetic order of Make of the cars that fit these

criteria.

12. Produce a list of manual cars in order of make then model for all cars that

have the letters 'gt' in their model name.

13. Mary is a Toyota car dealer and is going to stock one of each model of the

manual Toyota cars that are in the database. How much is this going to

cost her.

14. Produce a listing in alphabetic order of make then model of all cars that are

available in both manual and automatic versions.

15. Create a query to count and list the number of car models available for

each make of car in the database.

16. Construct a query to calculate and list the average capacity (cc) for each

Make of car in the database.

17. Mary is a fastidious buyer and has decided that she will only buy a car if

the Model name starts with "F" or "C" and the model has the letter "i" in it,

is an automatic and has a capacity (cc) that is less than 3 litres. What cars

fit these criteria.

18. All cars in this database have GST added. Create a query to give both

automatic and manual car prices without GST added i.e. exclusive GST.

19. Find the make and model of the shortest car? To answer this question you

need to setup two queries. The first query simply finds the minimum value

for car length. The second query combines this with the fields Make and

Model to give you the make and model of the shortest car.

Page 280: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 280 2013

46. Using manual Connections

Setting up SQL Server Before we create a manual connection your computer has to be set up to run the

SQL database.

We are running Microsoft’s latest SQL Server 2012 which can be easily downloaded

for free from the Microsoft website.

When you have installed it you have the following shortcuts loaded onto your Start

menu

Click on SQL Management Studio to activate the SQL Server.

In your Object Explorer you should be able to see

Page 281: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 281 2013

The top line is the name of your computer\SQLExpress and in brackets the path to

the Database you will use. (Mine is on the desktop)

If you DON”T see this then you need to do the following.

Go to the SQL Server Configuration Manager back on your Start Menu bar

Right Click on the Server Agent and start it.

Hopefully that will get you going.

Page 282: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 282 2013

If you see nothing in that window, you are really screwed. Try this….

When you cannot add a Database 1. Make sure you have administrative rights on the computer

2. Uninstall the existing SQL Server 2008 and all the components from the control panel.

Remember to backup the user databases before uninstalling SQL Server.

3. Backup the registry.

4. Delete the following keys in regedit:

--HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server

--HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer

5. Go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

and delete all the sub-keys referencing SQL Server.

6. Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services and delete all the

keys referencing SQL Server.

7. Rename all the SQL Server folders in the computer.

8. Download and install Windows Cleanup Utility: http://support.microsoft.com/?id=290301

Run the utility and remove any SQL Server components that you find.

9. Reboot the machine

10. Download and install Microsoft .Net Framework 3.5 SP1:

http://www.microsoft.com/downloads/details.aspx?FamilyId=AB99342F-5D1A-413D-8319-

81DA479AB0D7&displaylang=en

Download and install Windows Installer 4.5. (Windows 7 has Windows Installer 4.5)

http://support.microsoft.com/kb/942288

Check if the computer has Visual Studio 2008. If so, you need to install Visual Studio

2008 SP1. For more information, please see http://support.microsoft.com/kb/956139

Download SQL Server 2008 Express Edition Service Pack 1 and install it:

http://www.microsoft.com/downloads/details.aspx?familyid=01AF61E6-2F63-4291-

BCAD-FD500F6027FF&displaylang=en

How to restore administrator access to a SQL server I recently obtained a development machine that had SQL Server 2008 installed.

Unfortunately, I got this error:

CREATE DATABASE permission denied in database 'master'

Despite being an administrator on the box, AND having launched Management Studio in

Administrator mode (on Windows 7). Attempts to grant myself permissions, or to make any

changes to SQL server resulted in:

User does not have permission to perform this action( Microsoft SQL Server, Error:15247)

This all happened because I was not a SQL Server administrator despite being an

administrator on the box itself. This is a new situation in SQL Server 2008. In SQL Server

2005, the local Administrators group was part of the SQL Server administrators. It turns out

that only the person who installed SQL Server is a SQL Server administrator. Since that

person was not available, I was faced with either uninstalling and reinstalling, or getting into

an argument with SQL Server.

Being stubborn, I chose to argue. I knew as an Administrator I could do anything I wanted, it

was just a matter of finding the right registry keys/files/whatever to add myself to the group.

Page 283: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 283 2013

The trick is to put SQL server into single-user maintenance mode so that it ignores

authentication.

NOTE: In all of the examples below, you may have to change parameters or command-lines

based on your server name and instance name.

Force SQL server to support mixed-mode authentication

1. Run REGEDIT

2. Go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQLServer NOTE: This key will vary slightly based on the installed version and instance name.

3. Set "LoginMode" to 2.

(Source: http://support.microsoft.com/kb/285097)

4. Restart SQL Server.

Force SQL server to let you in temporarily

1. Go to services.

2. Stop SQL Server.

3. Grab the SQL server command-line (right click the service - properties). Mine is: "C:\Program Files\Microsoft SQL

Server\MSSQL10.SQLEXPRESS\MSSQL\Binn\sqlservr.exe" -sSQLEXPRESS 4. Open an administrative command prompt.

5. Run the command-line from step 3, but add -m -c for single-user maintenance mode

command-line.

6. Open another administrative command prompt.

7. Run cd C:\Program Files\Microsoft SQL Server\100\Tools\Binn

8. Run sqlcmd -S localhost\SQLEXPRESS from that same directory (replace with your

server and instance name)

9. Now you can do all the stuff everyone told you to do that didn"t work. For example, to

create a hero user with administrative access: CREATE LOGIN hero WITH PASSWORD="123", DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english],

CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF EXEC sys.sp_addsrvrolemember @loginame = "hero", @rolename = "sysadmin" GO

10. QUIT and close the command-prompt

11. Go to the SQL Server command-line window and hit ctrl+C. It will prompt "Do you wish

to shutdown SQL Server (Y/N)?" and enter Y.

12. Close the command-prompt

(Source: http://msdn.microsoft.com/en-us/library/dd207004.aspx)

Finally, login using your hero

1. Restart the SQL Server service

2. Login using SQL Server authentication as the user "hero" with password "123"

3. *BAM* now you are in. Now give yourself sysadmin access, etc, etc.

Page 284: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 284 2013

Loading in your Golf Database Once SQL Server is running we need to load in the database.

Right click on Database and then you can choose to Add a new DB or Create one.

In this exercise we will create an empty Database and import data for it.

Call your DB GOLF and click OK< we don’t need to create tables for it.

Page 285: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 285 2013

Right Click on Golf, Click on Tasks and Import Data.

Choose the Microsoft Access Jet Database Engine for DataSource then click Browse

and find the Golf Database and click Open and then go Next

In the next window check the destination is going to the Golf DB (Mine is Golf2)

Page 286: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 286 2013

After another window you will see the table to

choose, just choose the Golf table, the others

are queries.

Then Next, then when asked run it.

Success! Data has been imported into your Database.

This is really handy on a number of levels, firstly you don’t have to add data by hand to your database and secondly you can change from Access to SQL easily for small databases.

Page 287: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 287 2013

Check that your data has arrived safely by running a simple SQL query

Run a Query in SQL Express Click on New Query and in the window below type SELECT * FROM golf. This will

select all the fields from the Golf table.

Then click to see your fields.

You should have “Query Executed Successfully” and 32 rows at the bottom of the

screen

Page 288: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 288 2013

Creating an SQL Connection Specify a connection string containing all the information required to open a

connection to the database. Either use the constructor of the SqlConnection object

or set it using the property SqlConnection.ConnectionString.

The following information is required

Server – name of the SQL server to be accessed. - usually localhost if SQL Server is

on the same machine as the one running VS .NET, or the computer name followed

by a backslash followed by the named instance of SQL Server)

Database – the name of the database you want to connect to.

UserID * – an account with this name will need to exist in SQL Server and have

permission to access the specified database.

Password * – for the specified user

SQL Server can be setup to use the Account of the user who is running the program.

In this case you don’t need to specify a username and password.

Specify that you are using “Integrated Security”. Set IntegratedSecurity = True in

the connection string. Note that the user will still require permission to use the SQL

Server database – this is granted using the SQL Server Enterprise Manager.

On a new Form under Form Load add the following to set the connection path.

Imports System.Data.SqlClient

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

'Create the DB connection

Dim connection As New SqlConnection

Dim connectionString As String = "Data Source=localhost\sqlexpress;Initial Catalog=golf;" & "Integrated Security=True"

connection.ConnectionString = connectionString

Connect using SqlConnection Class

To execute a query properties must first be set on the SqlCommand object. The

command will usually be a Select, Insert, Update or Delete query. It can be either a

SQL string or a call to a stored procedure. The query may contain parameters if

desired.

The simplest method is to initialise a SqlCommand object with no parameters and

later set the properties required. Generally SqlCommand objects aren’t used on their

own but rather with Data Adapters or DataReaders.

You must set the “Connection” property on the SqlCommand object before the query

can be executed.

Page 289: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 289 2013

You must also set the CommandText property to specify the SQL string or stored

procedure to be executed. Most databases require all string values to be in single

quotes:

'select the data

Dim selectcommand As New SqlCommand

selectcommand.Connection = connection

Dim selectStatement As String =

"SELECT * " & "FROM Golf ORDER by ID"

selectcommand.CommandText = selectStatement

You could specify multiple tables in this section

Opening and Closing the Connection

theConnection.Open()

theConnection.Close()

Next we have to open the connection, and read in the data to a class called Golf.

Then close the Reader and Close the Connection.

Create a new class called Golf and add the Properties. (Example below)

Public Class Golf

Private _id As Integer

Private _Surname As String

Private _Firstname As String

Private _Title As String

Private _Gender As String

Private _DOB As Date

Private _Street As String

Private _Suburb As String

Private _City As String

Private _Available As Integer

Private _Handicap As Integer

Public Property ID() As Integer

Get

Return _id

End Get

Set(ByVal value As Integer)

_id = value

End Set

End Property

Page 290: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 290 2013

Public Property Surname() As String

Get

Return _Surname

End Get

Set(ByVal value As String)

_Surname = value

End Set

End Property

Etc ... add the rest of the properties as well.

Once we have the Class created we can pass the data to it using the reader.

'read in the data with a datareader open the data connection

connection.Open()

'instantiate a reader close the connection when the data reader is closed

Dim reader As SqlDataReader = selectcommand.ExecuteReader(CommandBehavior.CloseConnection)

Dim Golf As New Golf

'read the data into the class

Do While reader.Read()

Golf = New Golf

Golf.ID = reader("ID")

Golf.Title = reader("Title").ToString

Golf.Firstname = reader("Firstname").ToString

Golf.Surname = reader("Surname").ToString

Golf.Gender = reader("Gender").ToString

Golf.DOB = reader("DOB")

Golf.Street = reader("Street").ToString

Golf.Suburb = reader("Suburb").ToString

Golf.City = reader("City").ToString

Golf.Available = reader("Available week days")

Golf.Handicap = reader("Handicap")

Loop

reader.Close()

connection.Close()

Once the data has been added it can then be worked with.

Page 291: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 291 2013

Display data in a ListView So we presumably have some data but we can’t see it. Let’s create a ListView to load

the data in so that we know everything is working OK.

From the Toolbox drag on a ListView and name it LVGolf

In the Property name 10 columns with the appropriate

names as shown below. I changed the TEXT property and the NAME property to the

same.

In the View Property set it to Details

We need to add the code to read the data into a listview. Although we have a whole

bunch of columns you can’t just specify them in a listview as it only really holds one

item down the page. The columns are really pseudo columns. Therefore we need to

use the .SubItems. property to align the extra columns.

We also use With and End With to tell the program to add them together.

Add this code underneath your Golf.Handicap = reader("Handicap") code.

With LVgolf.Items.Add(Golf.ID)

.SubItems.Add(Golf.Title)

.SubItems.Add(Golf.Firstname)

.SubItems.Add(Golf.Surname)

.SubItems.Add(Golf.Gender)

.SubItems.Add(Golf.DOB)

.SubItems.Add(Golf.Street)

.SubItems.Add(Golf.Suburb)

.SubItems.Add(Golf.City)

.SubItems.Add(Golf.Available)

.SubItems.Add(Golf.Handicap)

End With

Page 292: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 292 2013

Returning Scalar (single) value Create a new button. Call it BTNCount

You can also create Scalar queries to return a single value. In this example we will

use a simple COUNT to show on the button how many Golfers there are. Copy the

code from the Form Load section and change the SQL Query to see it run.

Private Sub btncount_Click(sender As System.Object, e As System.EventArgs) Handles btncount.Click

'Create the DB connection

Dim connection As New SqlConnection

Dim connectionString As String = "Data Source=localhost\sqlexpress;Initial Catalog=golf;" &"Integrated Security=True"

connection.ConnectionString = connectionString

Dim selectcommand As New SqlCommand

selectcommand.Connection = connection

Dim selectStatement As String =

"SELECT COUNT(ID)" &

"FROM Golf"

selectcommand.CommandText = selectStatement

connection.Open()

btncount.Text = selectcommand.ExecuteScalar

connection.Close()

End Sub

Page 293: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 293 2013

Insert Command

The insert command inserts the data "VALUES ('40','title', 'fn', 'sn', 'F', 23/12/56,

'street', 'suburb','city',-1,'56')" into the table at the last row. The problem, as we will

find with the next set of data is that this is fixed.

Using the code in the Insert, Update, and Delete commands, create a way to add

code that is dynamic, using text boxes.

Private Sub btninsert_Click(sender As System.Object, e As System.EventArgs) Handles btninsert.Click

'Create the DB connection

Dim connection As New SqlConnection

Dim connectionString As String = "Data Source=localhost\sqlexpress;Initial Catalog=golf;" &

"Integrated Security=True"

connection.ConnectionString = connectionString

Dim insertcommand As New SqlCommand

insertcommand.Connection = connection

Dim insertStatement As String = "INSERT INTO Golf (ID, Title, Firstname, Surname, Gender, DOB, Street, Suburb, City, [Available week days], Handicap)" &

"VALUES ('40','title', 'fn', 'sn', 'F', 23/12/56, 'street', 'suburb','city',-1,'56')"

Using insertconnection As New SqlConnection(connectionString)

Dim adapter As New SqlDataAdapter()

Try

insertconnection.Open()

adapter.InsertCommand = insertconnection.CreateCommand

adapter.InsertCommand.CommandText = insertStatement

adapter.InsertCommand.ExecuteNonQuery()

MsgBox("Data Inserted !! ")

Catch ex As Exception

MsgBox(ex.ToString)

End Try

End Using

End Sub

Page 294: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 294 2013

Optimising your code by using Sub Routines You will find is that although the query might be working the listview is not updating.

That’s because so far it only updates on the Form Load event.

To change this rebuild the front of your Code, in the Form Load section so that you

can access it to refresh the listview. Here is the code below.

There is so much that can be optimised, but to date I have left it untouched. For

example you will see that the following exercises repeat the same code that is being

used at the beginning to load the database. This is so that you have a block of code

that can be used without much modifying, but in the real world would be cut right

down and integrated back into the program.

These have become Global to the program

Dim Golfconnection As New SqlConnection

Dim selectcommand As New SqlCommand

Dim connectionString As String

Form Load only holds the links to the new subs

Private Sub Form1_Load1(sender As Object, e As System.EventArgs) Handles Me.Load

'load updatlistview

updatelistview()

'load createdataset (not yet made so use later)

createdataset()

End Sub

LoadDB provides the connection string and is called in the next sub Sub

updatelistview().

Sub loadDB()

'Create the DB connection

connectionString = "Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=Golf;" & "Integrated Security=True"

Golfconnection.ConnectionString = connectionString

selectcommand.Connection = Golfconnection

End Sub

Now you can add updatelistview() to the next sections of code to see the listview

update with the changed data.

All code

Imports System.Data.SqlClient

Public Class Form1

'declare them as global so you can see them anywhere in the code

Dim Golfconnection As New SqlConnection

Dim selectcommand As New SqlCommand

Page 295: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 295 2013

Dim connectionString As String

'Form Load gets chopped up so you can get the listview to refresh

Private Sub Form1_Load1(sender As Object, e As System.EventArgs) Handles Me.Load

'load updatlistview

updatelistview()

'load createdataset (not yet made so use later)

createdataset()

End Sub

'name loadDB as a subroutine

Sub loadDB()

'Create the DB connection

connectionString = "Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=Golf;" & "Integrated Security=True"

Golfconnection.ConnectionString = connectionString

selectcommand.Connection = Golfconnection

End Sub

'update the listview with this new subroutine

Sub updatelistview()

loadDB()

'clear the listview of existing items first, otherwise it just adds it to esiting items.

LVgolf.Items.Clear()

Dim selectStatement As String =

"SELECT * " &

"FROM Golf ORDER by ID"

selectcommand.CommandText = selectStatement

'read in the data with a datareader

'open the data connection from above

Golfconnection.Open()

'instantiate a reader close the connection when the data reader is closed

Dim reader As SqlDataReader = selectcommand.ExecuteReader(CommandBehavior.CloseConnection)

Dim Golf As New Golf

'read the data into the class

Do While reader.Read()

Golf = New Golf

Golf.ID = reader("ID")

Golf.Title = reader("Title").ToString

Golf.Firstname = reader("Firstname").ToString

Golf.Surname = reader("Surname").ToString

Golf.Gender = reader("Gender").ToString

Golf.DOB = reader("DOB")

Golf.Street = reader("Street").ToString

Page 296: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 296 2013

Golf.Suburb = reader("Suburb").ToString

Golf.City = reader("City").ToString

Golf.Available = reader("Available week days")

Golf.Handicap = reader("Handicap")

With LVgolf.Items.Add(Golf.ID)

.SubItems.Add(Golf.Title)

.SubItems.Add(Golf.Firstname)

.SubItems.Add(Golf.Surname)

.SubItems.Add(Golf.Gender)

.SubItems.Add(Golf.DOB)

.SubItems.Add(Golf.Street)

.SubItems.Add(Golf.Suburb)

.SubItems.Add(Golf.City)

.SubItems.Add(Golf.Available)

.SubItems.Add(Golf.Handicap)

End With

Loop

reader.Close()

Golfconnection.Close()

End Sub

Page 297: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 297 2013

Update Command Made this SQL statement dynamic - able to be changed

We want to be able to update any field on any row. So number 20 John Smith

changes his firstname to Jane, the handicap goes from 23 to 52 and he has a sex

change to become Female.

How would you update all those fields at once using your text boxes?

"Update Golf set Firstname = 'Howard' where ID = 1"

Private Sub btnupdate_Click(sender As System.Object, e As System.EventArgs) Handles btnupdate.Click

Dim con As New SqlConnection

Dim cmd As New SqlCommand

cmd.Parameters.AddWithValue("@ID", txtid.Text)

Try

con.ConnectionString = "Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=golf;" & "Integrated Security=True"

con.Open()

cmd.Connection = con

cmd.CommandText = "Update Golf set Firstname = 'Howard' where ID = 10"

cmd.ExecuteNonQuery()

Catch ex As Exception

MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")

Finally

con.Close()

End Try

updatelistview()

End Sub

Page 298: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 298 2013

Delete Command Here is the Parameter Delete Golf where ID = @ID" being inserted into the code

Private Sub btndelete_Click(sender As System.Object, e As System.EventArgs) Handles btndelete.Click

Dim con As New SqlConnection

Dim cmd As New SqlCommand

'Here is the parameter being defined

cmd.Parameters.AddWithValue("@ID", txtid.Text)

Try

con.ConnectionString = "Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=golf;" & "Integrated Security=True"

con.Open()

cmd.Connection = con

cmd.CommandText = "Delete Golf where ID = @ID"

cmd.ExecuteNonQuery()

Catch ex As Exception

MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")

Finally

con.Close()

End Try

updatelistview()

End Sub

Page 299: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 299 2013

Inserting Data into your database Inserting data can be done in at least 4 ways. Direct via the text box (txtinput.text),

via a Class (golf.ID), via a variable. (intID) or via a parameter (@ID).

The first 3 ways are shown below, parameters are over the page.

Create a variable to hold the data, or use the golf.ID property from the Golf class to

hold data. And then insert it into the SQL by using ' " & ID & " '.

So try it with '" & Golf.ID & "'

'can also use

Dim ID As String = txtid.Text

"Values('" & ID & "', 'Mr', 'Howard', 'The Duck', 'm', '12/12/23', 'asd', 'sdf', 'City', '0', '56') "

Or in this case

Connect to your class

Dim golf As New Golf

Pass the data to the property

golf.ID = txtid.Text

Add the Property to the SQL - '" & golf.ID & "'

& "Values( '" & golf.ID & "', 'txtentry', 'Howard', 'The Duck', 'm', '12/12/23', 'asd', 'sdf', 'City', '0', '56') "

Page 300: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 300 2013

47. Using Parameters Placeholders are variables prefixed with an at @ sign in the SQL statement; they get

filled in by parameters. For example, if you wanted to update the Golf table but didn’t

know the values at design time, you would do put in parameters @ID instead of

values (23):

Here, instead of providing values, you provide placeholders. Placeholders, as

mentioned, always start with an @ symbol. They do not need to be named after the

database column that they represent, but it is often easier if they are, and it helps to

self-document your code. We are only discussing INPUT parameters, which hold

data going into a program; OUTPUT parameters are also easy, but not covered here.

You need to create parameters that will be used to insert the values into the

placeholders when the SQL statement is executed. You create and add parameters

to the Parameters collection of the SqlCommand object. After you access the

Parameters collection, you can use its properties and methods to create one or more

parameters in the collection.

The term parameters here refers to the parameters required to provide data to your

SQL statement or stored procedure, not to the parameters that are required to be

passed to a Visual Basic 2010 method.

Using Parameters to hold the data we can create text boxes that will allow us to input

our data to our database. In this example data from the txtID textbox is passed to the

@ID parameter

insertcommand.Parameters.AddWithValue("@ID", txtid.Text)

The AddWithValue method here accepts the name of the parameter and the object

that you want to add.

The ExecuteNonQuery Method

Finally, you can execute the command. To do this, the connection needs to be

opened. You can invoke the ExecuteNonQuery method of the SqlCommand object.

This method executes the SQL statement and causes the data to be inserted into the

database. It then returns the number of rows that were affected by the query, which

can be a useful way to check that the command worked as expected. To complete

your code fragment, you need to open the connection, execute the query, and close

the connection again:

connection.Open()

insertcommand.ExecuteNonQuery()

connection.close()

Page 301: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 301 2013

Golf using parameters

Add text boxes to your form to hold the values of the database.

Sub insert()

'INSERT

'Connect to the data source

Dim connectionString As String =

"Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=golf;" &

"Integrated Security=True"

'using that connection then

Using connection As New SqlConnection(connectionString)

'insert the SQL

Dim insertStatement As String = _

"INSERT INTO Golf (ID, Title, Firstname, Surname, Gender, DOB, Street, Suburb, City, [Available week days], Handicap)" _

& "Values( @ID, @Title, @FN, @SN, @Gender, @DOB, @Street, @Suburb, @City, @Available, @Handicap) "

Using insertcommand As New SqlCommand(insertStatement, connection)

connection.Open()

'create the parameters and pass the data from the textboxes

insertcommand.Parameters.AddWithValue("@ID", txtid.Text)

'Give a default input if you can't be bothered entering data through the textbox by using .value =

insertcommand.Parameters.AddWithValue("@title", txttitle.Text).Value = "Mr"

insertcommand.Parameters.AddWithValue("@FN", txtfn.Text).Value = "Harry"

insertcommand.Parameters.AddWithValue("@SN", txtsn.Text).Value = "Houdini"

insertcommand.Parameters.AddWithValue("@Gender", txtgender.Text).Value = "M"

insertcommand.Parameters.AddWithValue("@DOB", txtdob.Text).Value = "03/03/56"

insertcommand.Parameters.AddWithValue("@Street", txtstreet.Text).Value = "aa"

insertcommand.Parameters.AddWithValue("@Suburb", txtsuburb.Text).Value = "bb"

insertcommand.Parameters.AddWithValue("@City", txtcity.Text).Value = "cc"

insertcommand.Parameters.AddWithValue("@Available", txtavailable.Text).Value = 0

insertcommand.Parameters.AddWithValue("@Handicap", txthandicap.Text).Value = 45

insertcommand.ExecuteNonQuery()

MsgBox("Data Inserted !! ")

connection.close()

End Using

End Using

'Update the listview to see the new data

updatelistview()

End Sub

Page 302: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 302 2013

48. Golf Exercise using SQL Create a listbox to hold your items. The input code might look like

listbox.items.add(Firstname & “ “ & Surname)

Find the following

1. Which people have a handicap under 11

2. Which Golfers are from Spreydon?

3. Which Golfers are NOT from Christchurch?

4. How many people are male?

5. Order the handicap in ascending order

6. How many people are available to play on the weekday?

7. How many people live in a street?

8. How many people are born AFTER 1/1/50?

9. Without using the gender field, how many people are female?

10. How many people have a surname starting with B?

11. How many people are not from Christchurch or Rangiora?

Page 303: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 303 2013

49. The SQL Data Adapter The SqlDataAdapter acts as a bridge between the data source and the in-memory

DataSet object. To access the data source they use the command objects

associated with a connection.

The SqlDataAdapter has a number of command properties, including the

SelectCommand property. The SelectCommandProperty is used to hold a

SqlCommand that retrieves data for the data source. The result is then placed in the

DataSet or DataTable.

There are also properties for UpdateCommand, InsertCommand, and

DeleteCommand. These SqlCommand objects are used to write changes made to a

DataSet or DataTable back to the data source.

The SelectCommand Property – SQL String Used to fill a DataSet with data from a SQL Server database.

To read from a data store you must set the SelectCommand property of the

SqlAdapter object first.

Sub createdataset()

' Declare a SqlDataAdpater object.

Dim GolfDataAdapter As New SqlDataAdapter()

' Assign a new SelectCommand to the SelectCommand property.

GolfDataAdapter.SelectCommand = New SqlCommand()

Dim objConnection As SqlConnection = New SqlConnection("Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=golf;" & "Integrated Security=True")

' Set the SelectCommand properties.

GolfDataAdapter.SelectCommand.Connection = objConnection

GolfDataAdapter.SelectCommand.CommandText = "SELECT * " & "FROM Golf ORDER by ID"

End Sub

Page 304: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 304 2013

The SelectCommand Property – Stored Procedure Instead of writing SQL commands (Select Insert, Update, Delete) you could instead

execute a stored procedure - a group of SQL statements stored in the database

under a unique name and executed as a unit.

The benefits of Stored Procedures are reduced server/client network traffic, stronger

security, reusable code, easier maintenance and improved performance.

Sub storedprocedure()

' Declare a SqlDataAdapter object.

Dim GolfDataAdapter As New SqlDataAdapter()

' Assign a new SelectCommand to the SelectCommand property.

GolfDataAdapter.SelectCommand = New SqlCommand()

Dim objConnection As SqlConnection = New SqlConnection("Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=golf;" & "Integrated Security=True")

' Set the SelectCommand properties.

GolfDataAdapter.SelectCommand.Connection = objConnection

GolfDataAdapter.SelectCommand.CommandText = " "Count_ID"

GolfDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure

End Sub

The CommandText property now specifies the name of the stored procedure that you

want to execute instead of the SQL string that was specified in the previous example.

GolfDataAdapter.SelectCommand.CommandText = "Count_ID"

Also notice the CommandType property. It is set to a value of

CommandType.StoredProcedure, which indicates that the CommandText property

contains the name of a stored procedure to be executed.

GolfDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure

Go to your SQL Management program

and follow the path below. Right click on

Stored Procedures and Choose New

Stored Procedure

Page 305: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 305 2013

In a new template add the Select

statement.

select count(ID) from golf

Just put it at the end and comment

out all that you see in the image.

Use - - to comment out text.

Calling the Stored procedure from your code Accessing a stored procedure is more verbose (but not more difficult) than accessing

a normal SQL. The approach is as follows:

1. Create a SqlCommand object.

2. Configure it to access a stored procedure by setting the CommandType

property.

3. Add parameters that exactly match those in the stored procedure itself.

4. Execute the stored procedure using one of the SqlCommand object’s

ExecuteX methods.

Page 306: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 306 2013

50. Music Database in SQL Management Studio -

Relational Database This may only work in SQL Management Studio 2012.

Follow our first lessons to import the database tables from the file music.accdb.

Accdb is the new form of Microsoft Access Database file replacing MDB.

However as it is apparently too new for Microsoft’s own 2012 product you need to

choose All Files from the option to see it (Bottom right)

Import all three tables

Note: This will NOT work if you have SQL management Server 2008 because Accdb is a newer version and cannot be imported. (sigh). Nor can you save your Accdb file as an MDB.

Therefore you need to OPEN Music in Access, and then EXPORT out each table as an EXCEL file. This will give you 3 files. You then IMPORT those three files into your new Music database.

Even then you are not home safe, it might be impossible to create new columns in your new tables owing to limitations of the free SQL Express. The solution is to install the free 2012 version which allows the actions shown in this manual.

Either that or you can type in the new data into a new table.

Page 307: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 307 2013

Primary Key / Foreign Key relationships The Music database is a RELATIONAL database. A database with more than one

table and each table is connected to each other. This relationship scheme from

Access shows how the three tables are related.

Each table has a Primary Key, which indicates that the field is one that will never

repeat, it will always increment automatically 1, 2, 3, 4 etc. If you delete 3 then it will

never replace it, the next record will be 5, then 6 then 7.

Note that from the Primary keys of Owner and CD are two lines that go to CD and

CD Tracks. Those two lines are attached to other fields that are called Foreign keys.

Foreign keys are the alien invaders from the other primary key tables.

The Primary Key – Foreign Key connection establishes the relationship between the

tables in a One to Many relationship. For example ONE Owner (OwnerID in the

Owner Table) can have MANY CD’s. (Owner ID in the CD Table). ONE CD (CDID in

the CD Table) has MANY tracks (CDID in the CDTracks Table).

Thus by following the relationships you can easily see how many music tracks each

Owner has, and their name and duration.

To make the next section easier (it will hopefully avoid the problems you will read

later) go Tools / Options / Designers and UNTICK the Prevent saving changes that

require table re-creation. This is not recommended for a ‘real’ database as it could

mess up your data but for this practice it’s an easy workaround.

Page 308: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 308 2013

Setting the Primary key / Foreign Key Relationships Unfortunately when you import tables into SQL the tables move happily and the data

moves happily but the Primary keys and their relationship to the Foreign keys is lost

and we have to rebuild it by making a new Primary key. Sure it’s

messy but beats typing in 100 rows of data into a new table.

In SQL Server Management Studio Right click on the table and go

Design

Create a new Column Name CDID2. Scroll down the Column properties until you find

Identity Specification and change Is Identity to YES. See that it starts at 1 (Seed)

and increases by 1 for each entry.

The click on the Primary key on the tool bar to

add it.

Now make sure you SAVE it (Important)

Go to the first column, CDID and delete it

The drag the CDID2 column up to the top and rename it CDID.

When you try to save the changes it will throw a fit and say you can’t. Don’t worry just

cancel out and leave without saving, when you open up again it has worked!

Now repeat for the Primary key fields on the other two tables.

Now we need to build the connections back between the Primary Key and the

matching Foreign key.

Page 309: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 309 2013

Database Diagrams – Entity relationships

One of the most interesting resources is the creation of entity-relationship diagrams

(the database diagrams).

With all of the tables created, we need to add a database diagram to our database

and create all the necessary relationships between the tables. To do so, right click

over Database Diagrams and choose New Database Diagram.

It will open a blank diagram and ask which tables you wish to insert in the new

diagram. Select all the tables available, clicking the Add button to add them and then

the Close button. In your screen you will have all the tables and their respective

fields,

In case it is the first time you are using the database diagram resource in

Management Studio Express, you will be asked to install some files necessary to the

proper functioning of the diagrams module. Just click Yes so that these files are

installed.

To add a relation between two tables, select the table that contains the Foreign key

(in our case, the CD table) and click the Relations button located in the Database

Diagram toolbar. You have to choose the Foreign Key table first because the window

that opens won’t let you change it. You can only select the Primary key in the other

table.

Then Move to the right column and click the Table and Column Specific button

Then Choose the Owner for the Primary Key table

And choose OwnerID2 (or whatever you called it) and go OK, then Close

Page 310: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 310 2013

Click the CDTracks table and the Relationships button and add the other two

relationships.

Finally save it as Diagram1 (Or whatever you like)

Note that the relationship lines don’t point to the fields they are joined to.

Now you have a new Database Diagram.

Page 311: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 311 2013

Creating Database Views – Queries

CDs and Owners

Views are Queries, or questions that you make from your tables using SQL. Luckily

Views generate the SQL for you. The Views window is divided in four parts: Diagram

Panel, Criteria Panel, SQL Panel and Results Panel. Through these panels you can

assemble its views through SQL language or through mouse selection.

Create a new view

Add the Owner and CD tables

Click in the tables as shown to add the fields to the windows below. See how the

SQL is written for you. Hit the Execute/Run button to see the results generate at

the bottom of the screen.

Save as CDOwners

Page 312: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 312 2013

Tracks by CD

Lets make a more interesting View.

We want to count how many Tracks there are on each CD.

Add CD and CDTracks Table

Click on Name and TrackID

Click the GroupBy button then when the Group By column appears choose

Count for TrackID

You will now have the view below laid out Click the Run button and see what you

get.

Note that the column that shows how many tracks on each CD is called Expr1.

Change the name in the Alias column to read CountofTracks. Now run again and see

the new column name.

Save the View as CountOfTracks

Page 313: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 313 2013

Make a new view grouping all the records by Genre. Save as GroupByGenre.

Ignore the error message and Save.

Make a new View Save it as UniqueGenre – to show just unique names from the

Genre list instead of each entry

Page 314: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 314 2013

Who has the CD with the most Tracks?

To answer this question we need to first find the CD with the most Tracks and save it

as MaxTracks Save and close it.

Make a new View and add the following two views and two tables below.

Drag the MaxTracks field (the one with the tick) from its Table box over to

CountofTracks and drop it over the CountOftracks. This will show the program that

MaxTracks is related to CountofTracks and build the little connection.

Do the same for CountOftracks Name and CD Name. That will make a path all the

way to Owner showing John Smith owns the record Abba with the most tracks.

Save as OwnerMaxTracks

Page 315: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 315 2013

51. Music Database in Visual Studio Create a new Project in Visual Studio and add the connections to connect to the

Music database.

Imports System.Data.SqlClient

Public Class Form1

Dim Musicconnection As New SqlConnection

Dim selectcommand As New SqlCommand

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

loadDB()

End Sub

Sub loadDB()

Dim connectionString As String =

"Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=Music;" &

"Integrated Security=True"

Musicconnection.ConnectionString = connectionString

selectcommand.Connection = Musicconnection

End Sub

Using a Datagridview Add a Datagridview to your form and the following code. The DataGridView control

reads the schema information and creates the correct number of columns for your

data. It also uses the column names in the schema as the column names for the grid

and each column has the default width.

The SQLDataAdapter reads the data from the database and populates the Datatable

using the Fill method. Note that you don't have to actually open and close the

connection explicitly as the DataAdapter's Fill() method leaves the connection in the

same state as when the method was invoked.

Private Sub DisplayDataGridView()

DGVmusic.DataSource = Nothing

Dim da As SqlDataAdapter = Nothing ' create a dataadapter to pass the data

Dim dt As New DataTable 'create a datatable

Dim SQL As String = ""

Try

SQL = "select * from CD"

da = New SqlDataAdapter(SQL, Musicconnection) ''connect in to the DB and get the SQL

DGVmusic.DataSource = dt 'pass the datatable data to the DataGridView

Musicconnection.Open() 'open a connection to the DB

da.Fill(dt) 'fill the datatable from the SQL

Musicconnection.Close() 'close the connection

Catch ex As Exception

End Try

End Sub

Page 316: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 316 2013

Finally pop the Sub into the Form Load

DisplayDataGridView()

Using Views in the Form The Views are just like tables. So replace the SQL table with the View name like this

SQL = "select * from GroupByGenre"

After much pondering and experimentation I found that although you can name your

views Owner-CD in the Management Studio, Visual Studio or SQL doesn’t like the

Hyphen so rename the view to OwnerCD

SQL = "select * from OwnerCD"

Fill the Listbox from the Database Private Sub DisplayListBox()

' DGVmusic.DataSource = Nothing

lbgenre.DataSource = Nothing

Dim da As SqlDataAdapter = Nothing ' create a dataadapter to pass the data

Dim dt As New DataTable 'create a datatable

Dim SQL As String = ""

Try

SQL = "select * from UniqueGenre"

da = New SqlDataAdapter(SQL, Musicconnection) ''connect in to the DB and get the SQL

' DGVmusic.DataSource = dt 'pass the datatable data to the DataGridView

lbgenre.DataSource = dt

Dim ds As New DataSet ' make a dataset to hold the data

Musicconnection.Open() 'open a connection to the DB

da.Fill(ds, "UniqueGenre") 'fill the datatable from the SQL and the dataset

lbgenre.DataSource = ds.Tables("UniqueGenre").DefaultView

lbgenre.DisplayMember = "Genre"

Musicconnection.Close() 'close the connection

Catch ex As Exception

End Try

End Sub

Page 317: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 317 2013

52. Linking DataGridViews to each other In the image below you can see 3 datagrid views, each drawing from a different

table. Owners, CD’s and CD Tracks.

When you click on an owner in the Owners DGV the second DGV CD’s shows the

CD’s that the owner has. When you click on a CD in the second DGV you see the

tracks of the CD in the third DGV. A nice click based navigation system.

There are two parts to making this magic happen.

1. Fill a DGV with data from a table.

2. Create a click event so clicking on a record sets the next DGV. Both of these

are easy to create.

Lets create the Owner DGV. The other two DGVs’ Music and Tracks are virtually

identical so you will copy this and use it later changing the names of the datagrid in

the code. You will recognise the first DGV from the previous exercises.

'LOAD THE OWNER DATAGRID

Private Sub DisplayDataGridViewOwner()

DGVOwner.DataSource = Nothing

Dim da As SqlDataAdapter = Nothing ' create a dataadapter to pass the data

Dim dt As New DataTable 'create a datatable

Dim SQL As String = ""

Try

SQL = "select * from Owner "

da = New SqlDataAdapter(SQL, Musicconnection) 'connect in to the DB and get the SQL

DGVOwner.DataSource = dt 'pass the datatable data to the DataGridView

Musicconnection.Open() 'open a connection to the DB

da.Fill(dt) 'fill the datatable from the SQL

Musicconnection.Close() 'close the connection

Catch ex As Exception

Page 318: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 318 2013

End Try

End Sub

The heart of the Sub is the call to the database the other two DGV’s will have a

variation on this.

SQL = "select * from Owner "

Add the call to the Sub DisplayDataGridViewOwner() to the end of our

LoadDB() Subroutine. So that it loads at start up.

DataGridView Click Event Double click on the DGVOwner to load the code for the click event.

The code is nested in a Try Catch in case you click in a place that doesn’t return a

value, otherwise it will make an error.

The heart of this code is this line which is modified in the code

'Dim value As String = DGVmusic.Rows(e.RowIndex).Cells(e.ColumnIndex).Value

This passes to Value the contents of whatever cell you click on.

If you put this line, in your code, a testing line, you can see in the form title the

contents of the cell you click on.

Me.Text = "Row : " & e.RowIndex.ToString & " Col : " & e.ColumnIndex.ToString & " Value = " & value

However the problem is that you don’t want EVERY cell value, you only want the

value of the OwnerID cell to pass it to the next CD Datagrid.

The OwnerID is in the 3rd column, Columns start at 0, so its 0, 1, 2. We replace

e.ColumnIndex with the cell columns number, of 2.

Ownervalue = DGVOwner.Rows(e.RowIndex).Cells(2).Value

To get the number of the OwnerID to the next datagrid we pass the value into with a

ByVal.

FillWithOwnerCD(Ownervalue)

So adding this to the code passes the OwnerID from the click event to the next

datagrid as seen below.

Private Sub FillWithOwnerCD(ByVal Ownervalue)

Page 319: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 319 2013

Here is the code for the full DataGridView click event.

'CLICK EVENT FOR THE OWNER CELL

Private Sub DGVOwner_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVOwner.CellClick

Dim Ownervalue As String

Try

Ownervalue = DGVOwner.Rows(e.RowIndex).Cells(2).Value

If e.RowIndex >= 0 Then

‘show it on the Form bar to check if its working

Me.Text = "Row : " & e.RowIndex.ToString & " Col : " & e.ColumnIndex.ToString & " Value = " & Ownervalue

'Fill the next CD DGV with the OwnerID

FillWithOwnerCD(Ownervalue)

End If

Catch

End Try

End Sub

Note the different line here where it is passing the OwnerID Primary Key to the

OwnerID foreign key in the CD table.

Dim SQL As String = "select * from CD where OwnerID = '" & Ownervalue & "' "

'DISPLAY THE CD Fill event

Private Sub FillWithOwnerCD(ByVal Ownervalue)

DGVmusic.DataSource = Nothing

Dim da As SqlDataAdapter = Nothing ' create a dataadapter to pass the data

Dim dt As New DataTable 'create a datatable

Dim SQL As String = "select * from CD where OwnerID = '" & Ownervalue & "' "

da = New SqlDataAdapter(SQL, Musicconnection) 'connect in to the DB and get the SQL

DGVmusic.DataSource = dt 'pass the datatable data to the DataGridView

Musicconnection.Open() 'open a connection to the DB

da.Fill(dt) 'fill the datatable from the SQL

Musicconnection.Close() 'close the connection

End Sub

Next create the CD click event. Use the click event for the Owner cell and just

change the following code as well as change the name of your DataGridView to the

one for your CD grid.

Page 320: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 320 2013

Change the column index to 4, as the field is in the 5th column

value = DGVmusic.Rows(e.RowIndex).Cells(4).Value

Change the call to the Tracks Datagrid to the one below passing the value to that sub

DisplayDataGridViewTracks(value)

Finally create a DataGridview for the Tracks Table. Name it as below and remember

to name it with the name of your Tracks DGV in the code.

Private Sub DisplayDataGridViewTracks(ByVal value)

And use the following as the SQL statement.

SQL = "select Trackname from CDTracks where CDID = '" & value & "' "

In this way you have daisy chained together the three datagridviews to create a full

application. Finally it would be nice to be able to click on the track and have it play

but that is beyond the scope of this program.

Resizing Columns to fit contents

This seems to be a hit or miss issue but I found

DGVmusic.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells)

Or the following to have some success.

DGVmusic.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells

Page 321: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 321 2013

Passing data from a DataTable to text boxes for Updating Get the OwnerID and also get the Firstname and Lastname with the same method

earlier by selecting cells in the row and then just pass it to the text box.

(Ignore the buttons on the image at this stage only the text boxes are being used.

The SQL has been changed to show the values in the image. But you can easily do

that)

First use the click event of the Datagridview (in this case the Owners click event) to

select the row you need.

Ownervalue = DGVOwner.Rows(e.RowIndex).Cells(2).Value

OwnerFN = DGVOwner.Rows(e.RowIndex).Cells(0).Value

OwnerLN = DGVOwner.Rows(e.RowIndex).Cells(1).Value

Then pass the values from that row into the text boxes

txtFN.Text = OwnerFN

txtLN.Text = OwnerLN

TxtOwnerID.Text = Ownervalue

Full code.

'CLICK EVENT FOR THE OWNER CELL

Private Sub DGVOwner_CellClick (sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVOwner.CellClick

Dim Ownervalue, OwnerFN, OwnerLN As String

Try

Ownervalue = DGVOwner.Rows(e.RowIndex).Cells(2).Value

OwnerFN = DGVOwner.Rows(e.RowIndex).Cells(0).Value

OwnerLN = DGVOwner.Rows(e.RowIndex).Cells(1).Value

Page 322: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 322 2013

If e.RowIndex >= 0 Then

'Fill the next CD DGV with the OwnerID

FillWithOwnerCD(Ownervalue)

End If

txtFN.Text = OwnerFN

txtLN.Text = OwnerLN

TxtOwnerID.Text = Ownervalue

Catch

End Try

End Sub

Do the same for the CD and the Tracks DataGridViews

INSERT new Data using Parameters

Under the Button Click event for the Add Owner this code adds new owners to the

list. Note that you cannot add to the Primary key field OwnerID it does that

automatically.

'ADD NEW OWNER

Private Sub btnAddOwner_Click(sender As System.Object, e As System.EventArgs) Handles btnAddOwner.Click

'only run if there is something in the textboxes

If txtFN.Text <> "" And txtLN.Text <> "" Then

Try

Musicconnection.Open() ' open connection add in the SQL

Dim myCommand = New SqlCommand("INSERT INTO Owner (FirstName, LastName) " & "VALUES(@Firstname, @Lastname)")

myCommand.Connection = Musicconnection

With myCommand.Parameters 'use parameters to prevent SQL injections

.AddWithValue("Firstname", txtFN.Text)

.AddWithValue("Lastname", txtLN.Text)

End With

myCommand.ExecuteNonQuery()

MsgBox(txtFN.Text & " " & txtLN.Text & " has been inserted successfully")

Catch ex As Exception

MsgBox(ex.Message())

End Try

Musicconnection.Close()

'update the datagrid view to see new entries

DisplayDataGridViewOwner()

txtFN.Text = ""

txtLN.Text = ""

Else

MsgBox("Fill all the fields")

End If

End Sub

Page 323: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 323 2013

Use this as a template for the other Insert commands for the CD and the Tracks

tables. In them you will need to know and add the foreign keys for the OwnerID and

the CDID for each entry.

DELETE Data using Parameters

A variation on the INSERT template the delete code only needs the OwnerID2 to

delete an entire row.

'DELETE FROM OWNER

Private Sub btndeleteOwner_Click(sender As System.Object, e As System.EventArgs) Handles btndeleteOwner.Click

'only run if there is something in the textboxes

If TxtOwnerID.Text <> "" Then

Try

Musicconnection.Open() ' open connection add in the SQL

Dim myCommand = New SqlCommand("DELETE FROM Owner WHERE OwnerID2 = @ID")

myCommand.Connection = Musicconnection

With myCommand.Parameters 'use parameters to prevent SQL injections

.AddWithValue("ID", TxtOwnerID.Text)

End With

myCommand.ExecuteNonQuery()

MsgBox(txtFN.Text & " " & txtLN.Text & " has been deleted successfully")

Catch ex As Exception

MsgBox(ex.Message())

End Try

Musicconnection.Close()

'update the datagrid view to see new entries

DisplayDataGridViewOwner()

txtFN.Text = ""

txtLN.Text = ""

TxtOwnerID.Text = ""

Else

MsgBox("Fill all the fields")

End If

End Sub

Your program may look

something like this by

now.

Page 324: Intro to VB 7 March 2013

8 March 2013 Vision College Introduction to VB.Net

Page 324 2013