Professional Documents
Culture Documents
Intro To VB 7 March 2013 PDF
Intro To VB 7 March 2013 PDF
1.
2.
If Statements ...............................................................................................................27
Grades Project .................................................................................................................. 27 Learning to code defensively -Use Try / Catch for error Checking ................................... 29
3.
4.
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.
7.
8.
9. 10.
Picture Viewer using containers ..................................................................................66 Changing Control Panel setting using the SystemParametersInfo ...............................70
Changing the desktop wallpaper in the Picture viewer ..................................................... 70
Page 1
Contact Stuffucanuse.com for more resources and files for this manual
8 March 2013
11. 12.
13.
14.
Do WhileLoop ..........................................................................................................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 DoLoop While ................................................................................................................ 93 DoLoop Until .................................................................................................................. 93
15.
16.
Structures..................................................................................................................120
Heap and Stack Performance ..................................................................................... 121 Structures- Customer Exercise ....................................................................................... 122 Cheque processing using Structure ................................................................................ 125
20. 21.
Using Snippets for VB.net to auto create the Class properties ..................................129 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
Encapsulation............................................................................................................137
Dice program with Classes - revisited............................................................................. 139
Inheritance Is a ....................................................................................................141
Weapons Practice Class, Inheritance, Constructor ..................................................... 142
Page 2
Contact Stuffucanuse.com for more resources and files for this manual
8 March 2013
The Coffee machine Class Inheritance and Constructor .............................................. 150 Create the drink from the ingredients Classes ................................................................ 154
25.
29. 30.
31. 32.
Page 3
Contact Stuffucanuse.com for more resources and files for this manual
8 March 2013
Sorting Socks project ................................................................................................222 The T shirt algorithm .................................................................................................223 Search and Sort Algorithms.......................................................................................225
Bubble Sort ..................................................................................................................... 225 Sort a list of words using Bubble sort ......................................................................... 227 Selection Sort .................................................................................................................. 228 Sequential Searching ...................................................................................................... 231
36.
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. 46.
Practical Creating queries with the Cars Database .................................................278 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 4
Contact Stuffucanuse.com for more resources and files for this manual
8 March 2013
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
Golf Exercise using SQL ...........................................................................................302 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.
51.
52.
Page 5
Contact Stuffucanuse.com for more resources and files for this manual
8 March 2013
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 6
Contact Stuffucanuse.com for more resources and files for this manual
8 March 2013
If Else
If(<expression>) Then <statement 1> Else <statement 2> End If Inline If variable = IIf( condition, value_if_false, value_if_true )
<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
For Loop
For <initialize> (Relational Operator) <condition> <statement> Next
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
While Loop
While <expression> <statement> End While
Do-While Loop
Do <statement> Loop While <expression>
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
Page 7
Contact Stuffucanuse.com for more resources and files for this manual
Vision College
ADO.Net
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
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 IfElse and switch/Select Case; reading flowcharts; decision tables; evaluating expressions
This objective may include but is not limited to: For loops, While loops, Do..While loops, and recursion
This objective may include but is not limited to: structured exception handling Understanding Object-Oriented Programming (19 percent)
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 8
2012
Vision College
ADO.Net
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)
This objective may include but is not limited to: phases of application life cycle management; software testing
This objective may include but is not limited to: reading application specifications and translating them into prototypes, code, and components
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)
This objective may include but is not limited to: HTML, Cascading Style Sheets (CSS), JavaScript
This objective may include but is not limited to: page life cycle; event model; state management; client-side vs. server-side programming
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
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)
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 9 2012
Vision College
ADO.Net
This objective may include but is not limited to: characteristics and capabilities of console-based applications
This objective may include but is not limited to: characteristics and capabilities of Windows Services Understanding Databases (17 percent)
This objective may include but is not limited to: characteristics and capabilities of database products; database design; Entity Relationship Diagrams (ERDs); normalization concepts
This objective may include but is not limited to: structured query language (SQL), creating and accessing stored procedures, updating data and selecting data
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 10 2012
Vision College
ADO.Net
This objective may include but is not limited to: Windows Forms, Windows Presentation Foundation (WPF), Windows Services, and Win32 applications
This objective may include but is not limited to: core user interface design principles for creating graphical-based applications
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
This objective may include but is not limited to: methods for creating events in an application; handling events raised in an application
This objective may include but is not limited to: implementing forms inheritance in applications for visual inheritance
This objective may include but is not limited to: creating a new GUI control or inheriting functionality from an existing control
Page 11
2012
Vision College
ADO.Net
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
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
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
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
This objective may include but is not limited to: connecting to a database
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
This objective may include but is not limited to: different methods of deploying Windows applications; choosing the appropriate method for deployment
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 12 2012
Vision College
ADO.Net
- 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 13
2012
Vision College
ADO.Net
Page 14
2012
Vision College
ADO.Net
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 15 2012
Vision College
ADO.Net
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 forms code and layout information. From the ToolBox in Common Controls drag on .. 1 Button - named btngo Set Text field to GO 1 listbox named lboutput Set Multicolumn to true btn = button
lb = listbox
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 Set Text field to empty txt = textbox
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 wont 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 DONT 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 16
2012
Vision College
ADO.Net
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 dont 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 17
2012
Vision College
ADO.Net
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 18
2012
Vision College
ADO.Net
Variables Its 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 fullfledged 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 dont 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 19
2012
Vision College
ADO.Net
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 distinctionin fact, they are just two different names for the same base data type (in this case, its 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
Byte Int16 Int32 Int64 Single
VB Name
Byte Short Integer Long Single
C# Name
byte short int long float
Contains
An integer from 0 to 255. An integer from 32,768 to 32,767. An integer from 2,147,483,648 to 2,147,483,647. An integer from about 9.2e18 to 9.2e18. 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). 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). A 128-bit fixed-point fractional number that supports up to 28 significant digits. A single Unicode character. A variable-length series of Unicode characters. A True or False value. 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. Represents a period of time, as in ten seconds or three days. The smallest possible interval is 1 tick (100 nanoseconds). The ultimate base class of all .NET types. Can contain any data type or object. (Youll take a much closer look at objects in Chapter 3.)
Double
Double
double
TimeSpan
Object
Object
object
Page 20
2012
Vision College
ADO.Net
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
intmyage = intmyage + 1 intyear = intyear + 1 lboutput.Items.Add(intmyage & " in " & intyear)
Page 21
2012
Vision College
ADO.Net
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
+ * / Mod
Description
Addition Subtraction Multiplication Division Gets the remainder left after integer division
Example
1+1 52 2*5 5/2 7 Mod 3
Result
2 3 10 2.5 1
Here are the Comparison operators (these values yield true or false valuesfor example, 5 > 4 yields a value of True): < (Less than) <= (Less than or equal to) > (Greater than)
Page 22
True if operand1 is less than operand2 True if operand1 is less than or equal to operand2 True if operand1 is greater than operand2
2012
Vision College
ADO.Net
>= (Greater than or equal to) = (Equal to) <> (Not equal to) Is Like
True if operand1 is greater than or equal to operand2 True if operand1 equals operand2 True if operand1 is not equal to operand2 True if two object references refer to the same object 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 its 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). Multiply MyValue by 3 (the same as MyValue = MyValue * 3). Divide MyValue by 12 (the same as MyValue = MyValue / 12). MyValue += 10 MyValue *= 3 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 thats 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 = Math.Round(42.889, 2) MyValue = Math.Abs(10)
Page 23
Vision College
ADO.Net
negative a positive MyValue = Math.Log(24.212) MyValue = Math.PI MyValue = 3.18.. (and so on) 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 Microsofts 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). 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. 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). 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). Operator A "short circuited" And operator; if the first operand is False, the second operand is not tested. Operator A "short circuited" Or operator, if the first operand is True, the second is not tested. Gets the address of a procedure Gets information about a type
Not Or
Xor
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 24
2012
Vision College
ADO.Net
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.
Using My
My is the speed dial of the dot net framework. Its 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 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 25
2012
Vision College
ADO.Net
My isnt used much in the exercises as its platform dependant, but many exercises could be rewritten to incorporate it. Its a good tool that is so far unexploited. Maybe we need to get a book on it.
Vision College
ADO.Net
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. Heres an example of an If block that features two conditions:
If MyNumber > 10 Then ' Do something. ElseIf MyString = "hello" Then ' Do something. Else ' Do End If something.
An If block can have any number of conditions. If you test only a single condition, you dont 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
' lbgrade.Items.Add(txtgrade.Text & " ElseIf txtgrade.Text < 60 Then lblgrade.Text = "C"
2012
Vision College
ADO.Net
' lbgrade.Items.Add(txtgrade.Text & " Pass") ElseIf txtgrade.Text < 70 Then lblgrade.Text = "B" End If
I know this isnt a full program we will finish it later. Lets create a variable to hold the grade and use that instead of txtgrade.text. Its 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
Exercise: Add a way so that the persons 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 28
2012
Vision College
ADO.Net
Page 29
2012
Vision College
ADO.Net
Page 30
2012
Vision College
ADO.Net
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.
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 31
2012
Vision College
ADO.Net
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.
Private Sub btncaclulate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncaclulate.Click Try
Page 32
Vision College
ADO.Net
number
intmin = grade End If If grade > intmax Then ' if the grade is bigger than the 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 33
2012
Vision College
ADO.Net
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 34
2012
Vision College
ADO.Net
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 35
2012
Vision College
ADO.Net
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 doesnt 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 36 2012
Vision College
ADO.Net
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 37
2012
Vision College
ADO.Net
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, dont 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 38
2012
Vision College
ADO.Net
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 39
2012
Vision College
ADO.Net
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 40
2012
Vision College
ADO.Net
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 41
2012
Vision College
ADO.Net
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 42
2012
Vision College
ADO.Net
Page 43
2012
Vision College
ADO.Net
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 44 2012
Vision College
ADO.Net
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 45
2012
Vision College
ADO.Net
Page 46
2012
Vision College
ADO.Net
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, Case 2 'Paper MessageBox.Show("Your choice: Rock, Case 3 'Scissors MessageBox.Show("Your choice: Rock, Case Else MessageBox.Show("Error, something went wrong with the computer generated choice") 'Not nessesarily needed, just here to catch errors End Select Computer choice: Scissors, You win!") Computer choice: Paper, You lost.") Computer choice: Rock, You tied.")
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 47
2012
Vision College
ADO.Net
Using the instructions that follow, add 3 images to your program to show the choices of the players.
Page 48
2012
Vision College
ADO.Net
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
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 49
2012
Vision College
ADO.Net
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, Mydialogform.Show() You tied."
Page 50
2012
Vision College
ADO.Net
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 51
2012
Vision College
ADO.Net
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 52
2012
Vision College
ADO.Net
Employee wages
Calculate employee wages based on hours. Use tax rates, and overtime rates
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 53
2012
Vision College
ADO.Net
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 54
2012
Vision College
ADO.Net
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 55
2012
Vision College
ADO.Net
This sub takes the number in the intcounter variable and shows it on the label.
Page 56
2012
Vision College
ADO.Net
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 57
2012
Vision College
ADO.Net
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 dont 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
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 doesnt need to be the same is the variables in your main sub. The important thing is that you keep the same order.
Vision College
ADO.Net
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 justificationand then shouldnt 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 theres one argument, its 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 59
2012
Vision College
ADO.Net
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 60 2012
Vision College
ADO.Net
ByRef or ByVal Example Create this little example to see the difference between Byref and ByVal. To run 1. 2. 3. 4. Enter two numbers in the text boxes, Load the numbers to the variables, Pass them to functions that just add 10 using the Byref and ByVal buttons. 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/bestpractice-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 61 2012
Vision College
ADO.Net
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 62
2012
Vision College
ADO.Net
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
Page 63
2012
Vision College
ADO.Net
'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 sngYourAnswer = txtanswer.Text 'add 1 to the counter '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 Else strcorrect = " wrong" End If End Sub 'make the string equal wrong 'make the correct counter increase by 1
Page 64
2012
Vision College
ADO.Net
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 65
2012
Vision College
ADO.Net
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 66
2012
Vision College
ADO.Net
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
Vision College
ADO.Net
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 68
2012
Vision College
ADO.Net
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
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
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 69
2012
Vision College
ADO.Net
Here are the formal arguments to the function: uAction uParam lpvParam fuWinIni system parameter to query or set depends on system parameter depends on system parameter 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 70
2012
Vision College
ADO.Net
'combines two paths and returns a properly formatted path the image is saved as text.bmp imageLocation = My.Computer.FileSystem.CombinePath(My.Computer.FileSystem.SpecialDirecto ries.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 71
2012
Vision College
ADO.Net
sngIncminutes
Non-stop text 500MB 59c/min 20c/MB 20c per call 500MB 59c/min 20c/MB 20c per call 1GB 59c/min 20c/MB 20c per call 1GB 59c/min 20c/MB 0 2GB 59c/min 20c/MB 0
SngIncdata sngAddminutes
sngAdddata
sngvoicemail
You need to use TablelayoutPanels, Flowlayoutpanels to group stuff 3 text boxes to input your data How many minutes you talked How many Voice messages you received How much data you used A label to show what your cost will be A Combo Box to make your choice txtMinutesUsed txtvoice txtDataUsed lblplancost CbxPlan
3 labels to show the data, Minutes, and Voicemail used. (at the bottom of the form)
Page 72 2012
Vision College
ADO.Net
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 dont 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 73 2012
Vision College
ADO.Net
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 74 2012
Vision College
ADO.Net
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 75
2012
Vision College
ADO.Net
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 76
2012
Vision College
ADO.Net
'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 77
2012
Vision College
ADO.Net
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 78 2012
Vision College
ADO.Net
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
Click on View Application Events and add a time to wait for, otherwise its 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 79
2012
Vision College
ADO.Net
Page 80
2012
Vision College
ADO.Net
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 81 2012
Vision College
ADO.Net
Set the transparency key color to one that is the same as your background which isnt 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 82 2012
Vision College
ADO.Net
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
Vision College
ADO.Net
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 If Me.Opacity = 0 Then Me.Close() End If End Sub End Class 'make it more transparent When its totally transparent 'this actually closes the form
blncancelClose = False
Page 84
2012
Vision College
ADO.Net
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-offyour-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&cslang=vb#code-snippet-1
Page 85
2012
Vision College
ADO.Net
ForNext 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
Page 86
2012
Vision College
ADO.Net
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 87
2012
Vision College
ADO.Net
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 88
2012
Vision College
ADO.Net
14. Do WhileLoop
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
Page 89
2012
Vision College
ADO.Net
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 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 = txtyearenter.Text
Page 90
2012
Vision College
ADO.Net
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 .
Page 91
2012
Vision College
ADO.Net
This code doesnt 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 Dim Num2 As Integer = 1 Dim NumSum As Integer = 0 'First number 'Second Number '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 92
2012
Vision College
ADO.Net
DoLoop 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.
DoLoop 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
Page 93
2012
Vision College
ADO.Net
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 94
2012
Vision College
ADO.Net
Page 95
2012
Vision College
ADO.Net
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 96
2012
Vision College
ADO.Net
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 97 2012
Vision College
ADO.Net
' 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 98
2012
Vision College
ADO.Net
Create her login system. From: Microsoft training 361.pdf in Goodies folder.
Page 99
2012
Vision College
ADO.Net
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
2012
Page 100
Vision College
ADO.Net
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: 2nd year: 3rd year: 4th year: 5th year: $100,000 (less 40%) (less 20%) (less 20%) (less 20%) $60,000 $48,000 $38,400 $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 101
2012
Vision College
ADO.Net
In the tag properties of the 4 radio buttons set them to 1, 12, 52, 365 the radiobuttons are in a Groupbox but thats 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 102
2012
Vision College
ADO.Net
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 103
2012
Vision College
ADO.Net
This project uses 2 text boxes, a button and a label for data.
Page 104
2012
Vision College
ADO.Net
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 105 2012
Vision College
ADO.Net
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 106
2012
Vision College
ADO.Net
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 107 2012
Vision College
ADO.Net
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 108
2012
Vision College
ADO.Net
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 109
2012
Vision College
ADO.Net
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 dont 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 110 2012
Vision College
ADO.Net
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 its 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 cant 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
Vision College
ADO.Net
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 112
2012
Vision College
ADO.Net
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 havent 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 113
2012
Vision College
ADO.Net
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. Dont 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 114
2012
Vision College
ADO.Net
Page 115
2012
Vision College
ADO.Net
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 timeconsuming 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 116 2012
Vision College
ADO.Net
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 117
2012
Vision College
ADO.Net
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 118
2012
Vision College
ADO.Net
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 119
2012
Vision College
ADO.Net
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 customers 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 dont 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) Dont 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.
2012
Page 120
Vision College
ADO.Net
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 121
2012
Vision College
ADO.Net
Here are the names of the objects and controls on the form and the shape of the Structure .
Vision College
ADO.Net
_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
Vision College
ADO.Net
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.
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 124
2012
Vision College
ADO.Net
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 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 125 2012
---------------
Vision College
ADO.Net
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 126
2012
Vision College
ADO.Net
'------------- 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 127 2012
Vision College
ADO.Net
' 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 128
2012
Vision College
ADO.Net
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 Type in get underneath it Press the Enter key Voodoo happens - all the properties self generate Property Firstname() As String
Page 129
2012
Vision College
ADO.Net
http://msmvps.com/blogs/deborahk/archive/2010/04/11/auto-implementedproperties.aspx
Page 130
2012
Vision College
ADO.Net
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 131 2012
Vision College
ADO.Net
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 didnt 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/enus/library/zzh9ha57.aspx OOP terms Class Object Constructor
Destructor
Properties
Page 132
A container for data and code. The data within the class can be accessed with properties. The code is referred to as methods. An instance of a class in memory. An instance is created using a Dim statement and the New keyword. 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. 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. A routine exposed by an object to expose data, and to allow
2012
Vision College
ADO.Net
Method
code outside the object to affect the objects data. An action that can be performed by an object. In Visual Basic .NET, methods are defined as Subs and Functions.
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 133
2012
Vision College
ADO.Net
Public Class temperature These are private variables, they are only workers for use within the class, you dont 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 134
2012
Vision College
ADO.Net
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 dont want this line temp.snginput = txttemp.Text in our class in case in the future the text box changes name. Its just like plugging in a new system to an existing one.
Page 135
2012
Vision College
ADO.Net
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 End Get Set
Page 136
Starts a Get property procedure used to return the value of a property. Get blocks are optional unless the property is ReadOnly. Ends a Get property procedure. Starts a Set property procedure used to set the value of a property. Set
2012
Vision College
ADO.Net
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 classs 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 classs 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 classs 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 classs public interface and makes the programmers job more difficult.
Page 137
2012
Vision College
ADO.Net
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 Private Protected Gives variables public access, which means there are no restrictions on their accessibility. Gives variables private access, which means they are accessible only from within their class, including any nested procedures. 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. 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. 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.
Friend
Protected Friend
Page 138
2012
Vision College
ADO.Net
Vision College
ADO.Net
' 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 & " ' check if it's a double If newdice1 = newdice2 Then storage &= " 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 Double!" " & newdice2
Take all of the variables from the form, and turn them into fields in the class so that there are no Dims on the form at all.
Page 140
2012
Vision College
ADO.Net
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 parents properties, methods, and events, so the child class gets to reuse the parents 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.
Page 141
2012
Vision College
ADO.Net
Before you code the form you need to create the classes and their Fields, Properties, and Methods.
Page 142
2012
Vision College
ADO.Net
Vision College
ADO.Net
_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() _fullLoad = 6 _defaultSound = "Blam" _bullets = _fullLoad _name = "Revolver" _sound = "Blam" End Sub End Class ' set the defaults
Vision College
ADO.Net
_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 145 2012
Vision College
ADO.Net
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 146
2012
Vision College
ADO.Net
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 147
2012
Vision College
ADO.Net
Page 148
2012
Vision College
ADO.Net
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 isnt 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 149
2012
Vision College
ADO.Net
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 Protected _spoon As Boolean Protected _cup As Boolean - User choice ' do they want sugar? - User choice 'do they get a spoon? If they have sugar - Default 'do people need a cup? - override size for personal cup 'does it need grinding? - Default Protected _whitener As Integer ' whitener - fake milk - 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 150
2012
Vision College
ADO.Net
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 151
2012
Vision College
ADO.Net
Derived Classes Name Portion Coffee Long Black 2 Short Black 2 Latte 2 Cappuccino 1 Vienna 2 Chocolate 0
Whitener
Water 2 1 2 2 2 2
Chocsprinkle Milkfroth
Grinder T T
2 1 2
T T T
T T T T
Vision College
ADO.Net
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 153
2012
Vision College
ADO.Net
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 154
2012
Vision College
ADO.Net
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 155
2012
Vision College
ADO.Net
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
Page 156
'catch errors
2012
Vision College
ADO.Net
Page 157
2012
Vision College
ADO.Net
Page 158
2012
Vision College
ADO.Net
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 159
2012
Vision College
ADO.Net
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 Dim strtext As String ' path to the file '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 Try STREAMREADER BELOW 'copy the file into the textbox strtext = File.ReadAllText(strpath) lbltext.Text = strtext Catch ex As Exception correct") End Try strm.Close() End If End Sub End Class 'close the streamreader 'catch errors MsgBox("Check that the filename is
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 160
2012
Vision College
ADO.Net
Make sure you use error protection. Code that you might need
lbclientlist.Items.Add(lbmasterlist.SelectedItem)
Page 161
2012
Vision College
ADO.Net
Its That easy!!!! Add Toolstrip by dragging it to the form, then Right click, choose Insert Standard items, and edit them as you wish
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 162 2012
Vision College
ADO.Net
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() Me.Hide() 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 Worlds Greatest Rock and Roll Band" If MessageBox.Show("Do you like The Rolling Stones?", "The Rolling Stones Survey", MessageBoxButtons.YesNo) = DialogResult.Yes Then
Page 163 2012
'Opens the About Form 'Hides the Main form for later use.
Vision College
ADO.Net
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 164
2012
Vision College
ADO.Net
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 its 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. Heres 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 165
2012
Vision College
ADO.Net
MEMBER DESCRIPTION Gets the character at a specified position in the string. Chars Compare Copy CopyTo Empty EndsWith IndexOf Insert Join LastIndexOf Length
Compares two strings. Creates a new string by copying a string. Copies a specified number of characters from a specified position in this string to a specified position in an array of characters. A constant representing the empty string. Tells you whether the specified string matches the end of this string. Returns the index of the first occurrence of a substring within the string. Returns a new string with a substring inserted at the specified place. Lets you join together an array of strings with a specified separator. Gives the index of the last occurrence of a specified character or string within the string. Gets the number of characters in the string
FUNCTION DESCRIPTION Right-aligns the characters in this string, padding on the left with spaces or PadLeft
a specified character to a specified total length.
PadRight Remove Replace Split StartsWith Substring ToCharArray ToLower ToUpper Trim
Left-aligns the characters in this string, padding on the right with spaces or a specified character to a specified total length. Deletes the specified number of characters from this string, beginning at the specified location. Replaces all occurrences of a substring with a different substring. Splits a string into an array of substrings. Determines whether a specified substring starts the string. Returns a substring from the current string from the position indicated. Copies the characters in this string to a character array. Returns a lowercase copy of this string. Returns an uppercase copy of this string. 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. Either removes spaces or all occurrences of a set of characters specified in a Unicode character array from the end of the string. Either removes spaces or all occurrences of a set of characters specified in a Unicode character array from the beginning of the string
TrimEnd TrimStart
Page 166
2012
Vision College
ADO.Net
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 Lets 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(",")
There is one more parameter we can pass to the Split methodthe 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)
Vision College
ADO.Net
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 168 2012
Vision College
ADO.Net
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 169
2012
Vision College
ADO.Net
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. Heres 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 170
2012
Vision College
ADO.Net
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 171 2012
Vision College
ADO.Net
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 172 2012
Vision College
ADO.Net
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 173
2012
Vision College
ADO.Net
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 'Checks to 'Checks to If Not String.IsNullOrEmpty(strInput1) Then see that the string isnt empty If Not String.IsNullOrEmpty(strInput2) Then see that the string isnt empty Return True Else textbox") MessageBox.Show("Please enter a string in the second 'User Debug Return False End If Else textbox") MessageBox.Show("Please enter a string in the first 'User Debug Return False End If End Function End Class
Page 174
2012
Vision College
ADO.Net
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
Page 175
2012
Vision College
ADO.Net
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 176 2012
Vision College
ADO.Net
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 dont want it to, leading to it being called a greedy operator.
Page 177 2012
Vision College
ADO.Net
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 178
2012
Vision College
ADO.Net
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 Dim intatsymbol As Integer 'there has to be a dot '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 Dim intSpace As Integer Dim intcount As Integer = 0 'There can't be a .. 'there can't be a space '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 179 2012
Vision College
ADO.Net
'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. a@a.a 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 180
2012
Vision College
ADO.Net
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 Private _intDotDot As Integer 'there can't be a space 'There can't be a .. 'there can't be a .@
Private _intDotAtSymbol As Integer 'this holds the string Private _stremail As String 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 181
2012
Vision College
ADO.Net
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 182 2012
Vision College
ADO.Net
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 its 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)
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 183
2012
Vision College
ADO.Net
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
Page 184
2012
Vision College
ADO.Net
Page 185
2012
Vision College
ADO.Net
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 186 2012
Vision College
ADO.Net
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
Page 187
2012
Vision College
ADO.Net
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 188 2012
Vision College
ADO.Net
_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 189
2012
Vision College
ADO.Net
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 190
2012
Vision College
ADO.Net
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 191
2012
Vision College
ADO.Net
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, dont ask me, I would think it was 3). Strmetservice.replace(, String.Empty)
Page 192 2012
Vision College
ADO.Net
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>°C</span> Dim inttempleft as integer
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. Its that easy! Then pass the strmetservice to strfeelslike and look for
<div class="feel-likes"><strong>Feels like 15<span class="temp">°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/wxicons/" & strimage
Vision College
ADO.Net
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 194 2012
Vision College
ADO.Net
End Sub
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 195
2012
Vision College
ADO.Net
Page 196
2012
Vision College
ADO.Net
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 197 2012
Vision College
ADO.Net
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 198
2012
Vision College
ADO.Net
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
Page 199
2012
Vision College
ADO.Net
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 Dim MyDate As DateTime = DateTime.Now MyDate As = MyDate.AddDays(100)
DateString
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) Difference = = Dim Difference As TimeSpan MyDate2.Subtract(MyDate1) Dim NumberOfMinutes As Difference.TotalMinutes
Double NumberOfMinutes
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
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 200
2012
Vision College
ADO.Net
Now
Gets the current date and time. You can also use the UtcNow property to change the computers 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. Gets the current date and leaves time set to 00:00:00.
Today
Year, Date, Month, Returns one part of the DateTime object as an integer. For Hour, Minute, example, Month will return 12 for any day in December. Second, and Millisecond 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. Subtracts a TimeSpan or DateTime from another DateTime. Returns a TimeSpan that represents the difference. 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.
Subtract() AddYears(), AddMonths(), AddDays(), AddHours(), AddMinutes(), AddSeconds(), AddMilliseconds() DaysInMonth() IsLeapYear() ToString()
Returns the number of days in the specified month in the specified year. Returns True or False depending on whether the specified year is a leap year. 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() dont change a DateTime object. instead, they return a new DateTime or TimeSpan object.
Page 201
2012
Vision College
ADO.Net
Useful TimeSpan Members Member Description Days, Hours, Returns one component of the current TimeSpan. For Minutes, Seconds, example, the Hours property can return an integer from 23 Milliseconds to 23. TotalDays, Returns the total value of the current TimeSpan as a number TotalHours, of days, hours, minutes, and so on. The value is returned as a TotalMinutes, double, which may include a fractional value. TotalSeconds, For example, the TotalDays property might return a number TotalMilliseconds such as 234.342. Add() and Combines TimeSpan objects. For convenience, these Subtract() operations are mapped to the + and operators, so you can use them instead when performing calculations with times. FromDays(), Allows you to quickly create a new TimeSpan. For example, FromHours(), you can use TimeSpan.FromHours(24) to create a TimeSpan FromMinutes(), object exactly 24 hours long. FromSeconds(), FromMilliseconds() 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 202
2012
Vision College
ADO.Net
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, youd 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, youd do this:
strName(2) = "George"
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, its 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 203
2012
Vision College
ADO.Net
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}
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(" ")
Vision College
ADO.Net
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.
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 ArrayList BitArray Hashtable Queue
Page 205
Description Implements an array whose size increases automatically as elements are added. Manages an array of Booleans that are stored as bit values. Implements a collection of values organized by key. Sorting is done based on a hash of the key. Implements a first in, first out collection.
2012
Vision College
ADO.Net
SortedList Stack
Implements a collection of values with associated keys. The values are sorted by key and are accessible by key or index. 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)
As you specify a T in this case String then everything that enters the itemlist is considered a string. As a result you cant 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 typesafety benefits of being strongly typed.
Page 206
2012
Vision College
ADO.Net
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 207 2012
Vision College
ADO.Net
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
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 208 2012
Vision College
ADO.Net
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 209
2012
Vision College
ADO.Net
* The 20% depreciation loading doesnt apply to assets acquired after 20 May 2010.
Page 210
2012
Vision College
ADO.Net
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 211
2012
Vision College
ADO.Net
' 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 212
2012
Vision College
ADO.Net
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 213
2012
Vision College
ADO.Net
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 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 214 2012
Vision College
ADO.Net
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 215
2012
Vision College
ADO.Net
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 3 When the search starts with the first letter it will look for that letter anywhere in the word. 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 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 216
2012
Vision College
ADO.Net
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 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 'adds a single letter
Page 217
2012
Vision College
ADO.Net
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 218 2012
Vision College
ADO.Net
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 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 219 2012
Vision College
ADO.Net
'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 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 turn listbox ON and show on menubar ListboxViewToolStripMenuItem.Text = "Listbox ON"
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 220 2012
Vision College
ADO.Net
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.
Page 221
2012
Vision College
ADO.Net
Page 222
2012
Vision College
ADO.Net
Page 223
2012
Vision College
ADO.Net
http://www.programmableweb.com/api/amazon-ecommerce http://aws.amazon.com/visualstudio/
Page 224
2012
Vision College
ADO.Net
Page 225
2012
Vision College
ADO.Net
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 outer & ", 'end display Next Next
Page 226 2012
"
lbxSorted.Items.Add("Inner " & inner & ", Outer " & " & strArray)
Vision College
ADO.Net
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 227
2012
Vision College
ADO.Net
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 228
2012
Vision College
ADO.Net
'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 229
2012
Vision College
ADO.Net
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 230
2012
Vision College
ADO.Net
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 youre 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 231 2012
"
Vision College
ADO.Net
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 232
2012
Vision College
ADO.Net
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 233
2012
Vision College
ADO.Net
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 234 2012
Vision College
ADO.Net
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 wont 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 235 2012
Vision College
ADO.Net
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 236
2012
Vision College
ADO.Net
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 237
2012
Vision College
ADO.Net
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
Vision College
ADO.Net
'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 239 2012
Vision College
ADO.Net
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 240
2012
Vision College
ADO.Net
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:
Studies have shown that using this strategy can reduce the running time of the algorithm by about 5%
Page 241
2012
Vision College
ADO.Net
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 sizea 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 242
2012
Vision College
ADO.Net
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 243
2012
Vision College
ADO.Net
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
Vision College
ADO.Net
= 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 245
2012
Vision College
ADO.Net
1 of 21
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. Lets go for something that will translate a string from one thing to another. Im 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, theres little going on here at all. Ive 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 246 2012
Vision College
ADO.Net
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. Heres mine:
Page 247
2012
Vision College
ADO.Net
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
Page 248 2012
Vision College
ADO.Net
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 Ive created a global variable called Trans of type Translator. Then, we dont want people to click into the textbox txtresult so Ive put a bit of code there that says when focus enters this control, send it back to txtNorm Finally, theres 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 End If 'this is the false
We could have left out the code handling the Boolean and it still would have used the second Process method to be used. Ive used True for upper-case and False for lower-case. But we could add whatever code we required. Heres three runs of the program. First just the first button and then the second button.
Page 249
2012
Vision College
ADO.Net
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
So here we can see that each of the possible outcomes has been tested to ensure that everything worked as planned.
Page 250
2012
Vision College
ADO.Net
Smallint Money
Varchar
Text
Nvarchar
Ntext
Image Table
Varbinary Xml
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
Page 251
2012
Vision College
ADO.Net
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 252
2012
Introduction to VB.Net
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.
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 253
2013
Introduction to VB.Net
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 254
2013
Introduction to VB.Net
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 OLEDB 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 databasethey 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 databaseand 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 adapterssee "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 255
2013
Introduction to VB.Net
3. and datasets to store the dataas returned from data adaptersthat 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.
Page 256
2013
Introduction to VB.Net
DataSet The DataSet is a cache of data that is stored in memory. Its 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 257 2013
Introduction to VB.Net
TableAdapter Theres 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 System.Data.OleDb (e.g. ACCESS) for accessing SQL Server databases for accessing OLE DB-compliant databases
Page 258
2013
Introduction to VB.Net
Go Browse to find your database (assuming you have put it somewhere easy to find like C Drive first)
Page 259
2013
Introduction to VB.Net
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 its 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 wont
Page 260
2013
Introduction to VB.Net
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 261 2013
Introduction to VB.Net
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 arent 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()
ends the editing on that row and allows it to be saved. Data on a row cant be saved until the next row is selected.
Me.ShipsBindingSource.EndEdit() Me.TableAdapterManager.UpdateAll(Me._4shipsDataSet).
database
Page 262
2013
Introduction to VB.Net
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 263
2013
Introduction to VB.Net
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)
Page 264
2013
Introduction to VB.Net
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 265
2013
Introduction to VB.Net
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
Page 266
2013
Introduction to VB.Net
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 267
2013
Introduction to VB.Net
Back in the dataset Schema you can see the Query you have created
Page 268
2013
Introduction to VB.Net
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
Page 269
2013
Introduction to VB.Net
Page 270
2013
Introduction to VB.Net
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
Page 271
2013
Introduction to VB.Net
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
Page 272
2013
Introduction to VB.Net
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 273
2013
Introduction to VB.Net
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'
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.
Page 274
2013
Introduction to VB.Net
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 275
2013
Introduction to VB.Net
Create a button on the Form to show the Data in the same table.
Create a new Query to find all people whos 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)
Page 276
2013
Introduction to VB.Net
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 FROM GROUP BY Boat Boat, COUNT(Boat) AS People Ships
Note: this query doesnt output correctly back on the form. I am not sure why. However the design is still important.
Page 277
2013
Introduction to VB.Net
Page 278
2013
Introduction to VB.Net
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. 2. 3. 4. 5. List the make and model of cars that have 2 Doors Count the number of automatic cars in the database. List the make and model of automatic cars that have two doors. Count the number automatic cars that have two doors. 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 279
2013
Introduction to VB.Net
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 280
2013
Introduction to VB.Net
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 DONT see this then you need to do the following. Go to the SQL Server Configuration Manager back on your Start Menu bar
Page 281
2013
Introduction to VB.Net
If you see nothing in that window, you are really screwed. Try this.
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-4291BCAD-FD500F6027FF&displaylang=en
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 282 2013
Introduction to VB.Net
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 QUIT and close the command-prompt
10. 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 283
2013
Introduction to VB.Net
In this exercise we will create an empty Database and import data for it. Call your DB GOLF and click OK< we dont need to create tables for it.
Page 284
2013
Introduction to VB.Net
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 285
2013
Introduction to VB.Net
After another window you will see the table to choose, just choose the Golf table, the others are queries.
Success! Data has been imported into your Database. This is really handy on a number of levels, firstly you dont have to add data by hand to your database and secondly you can change from Access to SQL easily for small databases.
Page 286
2013
Introduction to VB.Net
Check that your data has arrived safely by running a simple SQL query
You should have Query Executed Successfully and 32 rows at the bottom of the screen
Page 287
2013
Introduction to VB.Net
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 arent 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 288
2013
Introduction to VB.Net
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
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 289
2013
Introduction to VB.Net
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 290
2013
Introduction to VB.Net
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 cant 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 291
2013
Introduction to VB.Net
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 292
2013
Introduction to VB.Net
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 293
2013
Introduction to VB.Net
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 294 2013
Introduction to VB.Net
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 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 295 2013
as a subroutine
Introduction to VB.Net
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 296
2013
Introduction to VB.Net
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 297
2013
Introduction to VB.Net
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 298
2013
Introduction to VB.Net
& "Values( '" & golf.ID & "', 'txtentry', 'Howard', 'The Duck', 'm', '12/12/23', 'asd', 'sdf', 'City', '0', '56') "
Page 299
2013
Introduction to VB.Net
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 300
2013
Introduction to VB.Net
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 301
2013
Introduction to VB.Net
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 302
2013
Introduction to VB.Net
Page 303
2013
Introduction to VB.Net
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 304
2013
Introduction to VB.Net
Just put it at the end and comment out all that you see in the image. Use - - to comment out text.
Page 305
2013
Introduction to VB.Net
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 306
2013
Introduction to VB.Net
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 CDs. (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 its an easy workaround.
Page 307
2013
Introduction to VB.Net
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 cant. Dont 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 308
2013
Introduction to VB.Net
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 wont 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
And choose OwnerID2 (or whatever you called it) and go OK, then Close
Page 309 2013
Introduction to VB.Net
Finally save it as Diagram1 (Or whatever you like) Note that the relationship lines dont point to the fields they are joined to.
Page 310
2013
Introduction to VB.Net
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 311
2013
Introduction to VB.Net
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 Count for TrackID then when the Group By column appears choose
You will now have the view below laid out Click the Run 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.
Introduction to VB.Net
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 313
2013
Introduction to VB.Net
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 314 2013
Introduction to VB.Net
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 315 2013
Introduction to VB.Net
After much pondering and experimentation I found that although you can name your views Owner-CD in the Management Studio, Visual Studio or SQL doesnt like the Hyphen so rename the view to OwnerCD
SQL = "select * from OwnerCD"
Page 316
2013
Introduction to VB.Net
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 317 2013
Introduction to VB.Net
The heart of the Sub is the call to the database the other two DGVs 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.
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 & " e.ColumnIndex.ToString & " Value = " & value Col : " &
However the problem is that you dont 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 318
2013
Introduction to VB.Net
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 319 2013
Introduction to VB.Net th
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)
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.DisplayedCell s)
Page 320
2013
Introduction to VB.Net
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 321
2013
Introduction to VB.Net
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 322
2013
Introduction to VB.Net
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 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 'use parameters to prevent SQL injections .AddWithValue("ID", TxtOwnerID.Text)
Page 323
2013
Introduction to VB.Net
Page 324
2013