Download - Vb.net Material
-
Prepared by: Noel Anonas
Visual Basic .NET
-
Prepared by: Noel Anonas
Day 1 Programming language syntax, declarations,
operators, statement, classes
Day 2 VB Form and Common Controls
Day 3 More VB Controls and other Features
-
Prepared by: Noel Anonas
Objectives of this Lesson
Elements in the Visual Studio Environment
(GUI)
Object-oriented programming
Concepts of classes, objects, properties,
methods and events
-
Prepared by: Noel Anonas
Programming Languages Overview
Procedural older, traditional, sequential
style
(Cobol, RPG, Pascal, etc.)
Event-Driven (Visual Basic 6.0 & earlier) Contain some elements of OOP but not all
Object-Oriented Programming (OOP) Visual Basic .NET (2005 or later)
-
Prepared by: Noel Anonas
OOP and VB.NET Objects have properties, methods and events
Each object is based on a class (a blueprint which all objects
are based upon)
Objects Examples Forms which are windows within the VB environment
Controls are components contained inside a form
Properties Examples Name (each object has a name )
Text ( what the user sees inside the control)
Methods Examples Open (methods perform an action)
-
Prepared by: Noel Anonas
Close
Events Examples User clicks a mouse button
User selects an item from a list
Classes
Classes are like blueprints ( or
templates) used to create objects
Classes contain the definition of all available
properties, methods and events for that
objects
Each new object created is based on a class
-
Prepared by: Noel Anonas
Creating three new labels makes each label an instance of the Label class
Object Model Analogy
A car belongs to the Car Class
The make, model, and color of the car are the
properties of the car
Each car is an object of the Car Class. This is
called an instance of the Car Class
When the car starts, stops or turns, these are
methods belonging to the Car.
-
Prepared by: Noel Anonas
An event occurs when the car pulls to the gas
station.
Objectives of this Lesson
Basic steps for writing a VisualBasic project
Explore the files that make up a Visual Basic
project
Define design time, run time and debug time
Error types: syntax errors, run-time errors and
logic errors
Launching Visual Basic .NET
-
Prepared by: Noel Anonas
Writing Visual Basic Projects
1. Design the UI (including the controls)
2. Set up the Properties for the controls
3. Code following the language syntax rules
Syntax Rules that MUST be followed such as
punctuation, spelling, use of special symbols
and keywords.
-
Prepared by: Noel Anonas
VB Application Files
Many files make up one VB application
Solution File (.sln) this is the one file that the
programmer interacts with. Avoid opening all
other files that are automatically created with
each solution!
Executable File (.exe) this is the file that the
end user ultimately runs (executes)
-
Prepared by: Noel Anonas
Various Modes of VB
Design Time used when designing the user
interface and writing code
Run Time used when running the application
(from the users perspective)
Break Time occurs when and error or other
condition occurs
More Terminology
Each user action causes an event to occur
-
Prepared by: Noel Anonas
Event procedures code written by the
programmer to react to events
VB will ignore events for which you don not write
code
Errors
Syntax Errors (must be fixed)
Sometimes called a compile error
VBs editor will detect and correct many
A blue squiggly line appears under code that
the editor does not understand
-
Prepared by: Noel Anonas
Mouse over the code to receive more details
The Error List window shows errors and more
details
Errors
Logic Errors (produces incorrect results)
Easy to overlook
Check calculations and other logic against
known test data results
VB editor can not detect logic errors
-
Prepared by: Noel Anonas
Debugging tools
Launch Visual Basic
Click Start
All Programs
MS Visual Studio 20xx
MS Visual Studio 20xx (again)
This will launch Visual Studio and we will now
be able to work with Visual Basic .NET within
Visual Studio
-
Prepared by: Noel Anonas
Launching VB Demo
DEMO Create a Console Application
Most commonly used VB function MsgBox()
InputBox()
Naming Rules
Begin with letters
No spaces
Avoid special symbols
-
Prepared by: Noel Anonas
Use camel casing Examples
messageLabel
exitButton
firstNameTextBox
Question Which of the following local variable names are allowed in VB, and which
have the correct style?
volume
AREA
Length
3sides
-
Prepared by: Noel Anonas
side1
lenth
Mysalary
your salary
screenSize
Dim
Answers: volume allowed, correct style;
AREA allowed, but area preferred;
Length allowed, but lower-case l preferred;
3sides not allowed, starts with a digit;
side1 allowed, correct style;
lenth allowed, even with incorrect spelling of length;
-
Prepared by: Noel Anonas
Mysalary allowed, but capital S is preferred;
your salary not allowed (no spaces allowed in middle of a
name);
screenSize allowed, correct style; Dim not allowed it is a
keyword.
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
Question
In the following, what are the values of the
variables after each statement?
-
Prepared by: Noel Anonas
Dim a, b, c, d As
Integer d = -8 a = 1 *
2 + 3 b = 1 + 2 * 3 c =
(1 + 2) * 3 c = a + b d
= -d
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
Double.Parse Sample String to number conversion
for arithmetic operation
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
Sample String to Number
Conversion
-
Prepared by: Noel Anonas
Sample Number to Number
Conversion
What is Operator
Operators determine behavior of statements
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
Exercise 1
Using Double types, write a program which converts a
Fahrenheit temperature to its Celsius (centigrade)
equivalent. The formula is:
c = (f - 32) * 5 / 9 Note:
-
Prepared by: Noel Anonas
Use InputBox() to get the fahrenheight value from the
user.
Display the value of c (centigrade)
Exercise 2 Calculate and display the series resistance, given by:
series = r1 + r2
and the parallel resistance, given by:
Use InputBox() to get the value or r1 and r2 from the user.
Use your calculator to check the output.
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
If Statement Sample
-
Prepared by: Noel Anonas
If Else statement
-
Prepared by: Noel Anonas
ElseIf keyword
-
Prepared by: Noel Anonas
IsNumeric() function
Exercise
Cinema (movie theatre) price
Write a program to work out how much a person pays
to go to the cinema. The program should input an
-
Prepared by: Noel Anonas
age from an InputBox() and then decide on the
following basis: under 5, free;
aged 5 to 12, half price;
aged 13 to 54, full price; aged 55, or over, free.
Exercise
Betting A group of people are betting on the outcome of three throws
of the dice. A person bets P1 on predicting the outcome of the
three throws. Write a program that uses the random number
method (VBMath.Rnd()) to simulate three throws of a die and
displays the winnings according to the following rules:
-
Prepared by: Noel Anonas
all three throws are sixes: win P20;
all three throws are the same (but not sixes): win P10;
any two of the three throws are the same: win P5.
Sample Using Date
Date syntax
-
Prepared by: Noel Anonas
Sample Using Date 2
Formatting the Date Display
-
Prepared by: Noel Anonas
Sample Using Date 3
Adding day and month
VB Windows Form
DEMO
Sample code using Windows Form
-
Prepared by: Noel Anonas
Demo
-
Prepared by: Noel Anonas
Output
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
-
Prepared by: Noel Anonas
Exercise The calculator Write a program which simulates a simple desk calculator (See Figure) that
acts on integer numbers. It has one button for each of the 10 digits, 0 to 9. It
has a button to add and a button to subtract. It has a clear button, to clear
the display, and an equals (=) button to get the answer.
-
Prepared by: Noel Anonas
When the clear button is pressed the display is set to zero and
the (hidden) total is set to zero.
When a digit button is pressed, the digit is added to the right
of those already in the display (if any).
When the + button is pressed, the number in the display is
added to the total (and similarly for the button).
When the = button is pressed, the value of the total is
displayed.
Exercise
Rock, scissors, paper game In its original form, each of the two players
simultaneously chooses one of rock, scissors or
-
Prepared by: Noel Anonas
paper. Rock beats scissors, paper beats rock and
scissors beats paper. If both players choose the same,
it is a draw. Write a program to play the game. The
player selects one of three buttons, marked rock,
scissors or paper. The computer makes its choice
randomly using the random number generator. The
computer also decides and displays who has won.
-
Prepared by: Noel Anonas
Select case sample
-
Prepared by: Noel Anonas
For Next / While
-
Prepared by: Noel Anonas
Do Loop
For Each
-
Prepared by: Noel Anonas
Exercise Saw-tooth pattern
Write a program to display a saw-tooth pattern, as
shown in a Figure, in a text box.
-
Prepared by: Noel Anonas
Use do loop statement.
Array
Array Data that is grouped together
into a collection of
information
Example: Telephone directory, flight schedule.
Sample Array
Array of Numbers
-
Prepared by: Noel Anonas
Array of Names
Array and indices
-
Prepared by: Noel Anonas
Creating an Array
Dim ages(5) As Integer indices going from 0 to 5.
Dim band(3) As String
Input a value for an element of an array: ages(2) =
CInt(TextBox1.Text) band(2) =
TextBox2.Text output
values: TextBox3.Text = "the first age is " & CStr(ages(0))
TextBox4.Text = "the 4th band member is " & band(3)
-
Prepared by: Noel Anonas
Length of an Array
Use of the Ubound() (upper bound) Dim length As Integer length = UBound(table)
Use of the Length
table.Length
ReDim
Array can be rebuilt to a different size using ReDim Dim table(19) As Integer
ReDim table(39)
-
Prepared by: Noel Anonas
Use Preserve as not to destroy the data: ReDim Preserve table(24)
Exercise - Array
Write a program that inputs a series of integers into an
array. The numbers are in the range 0 to 100. Calculate
and display: the largest number; the smallest number; the sum
of the numbers; the mean of the numbers. Apply looping (while or do statement) to store values into
array.
-
Prepared by: Noel Anonas
ArrayList
ArrayList - Dynamic array.
ArrayList Example:
Dim collection As ArrayList = New ArrayList()
-
Prepared by: Noel Anonas
ArrayList Properties & Methods
Properties
Count - The number of items in the array list.
Methods
Add -Add a new object to the array list. The new item is added at the end of
the list.
RemoveAt - Return and remove the object at the specified index from the
array list. Any remaining items are moved up to fill the gap created.
Remove - Remove the object from the array list.
Insert - Insert a new object into the array list at the index position specified.
Any items are moved down to make space for the new item. Parameters: index As Integer, newItem As Object
Clear - Empty the complete array list.
-
Prepared by: Noel Anonas
Exercise - ArrayList String ArrayList Write a program that uses an arraylist of 10 strings.
Write methods that carry out each of the following
operations: 1. Input values from the keyboard via a text box.
2. Display the values.
3. Input a word from a text box and search to see whether
it is present in the array.
4. Display a message to say whether it is present in the
array or not.
-
Prepared by: Noel Anonas
ListBox Adding Items to a list
ListBox1.Items.Add()
Removing Item from a list ListBox1.Items.RemoveAt(3)
Inserting items within a list ListBox1.items.Insert(5,tea)
Length of a List : ListBox1.Items.Count
Indices: ListBox1.selectedIndex
ListBox1.items returns an ArrayList
-
Prepared by: Noel Anonas
Exercise Write a program in which an item selected in a list box (by
clicking on it) is immediately deleted. Alternatively, provide a
'delete' button to delete the item that is currently selected.
Add another button so that items in the list box are
automatically sorted into alphabetical order.
Add a button that causes the list box to be emptied, using the
method Clear
Write a program that allows items to be inserted or removed
from any position within a list box, using suitable buttons.
-
Prepared by: Noel Anonas
Inserting single quote to a String
Use two quotes to stand for a single one: TextBox1.Text = "The word ""Object""" which displays:
The word "Object"
NewLine
End-of-line markers within a string. Imports Microsoft.VisualBasic.ControlChars
-
Prepared by: Noel Anonas
Dim s As String = "Tom" & NewLine & "Jerry" Or
vbCrLf
ToLower
string1 = "Version 1.1"
resultString = string1.ToLower()
-
Prepared by: Noel Anonas
ToUpper
string1 = "Basic"
resultString = string1.ToUpper()
-
Prepared by: Noel Anonas
Trim
string1 = " Center "
resultString = string1.Trim()
-
Prepared by: Noel Anonas
insert
This method lets us insert characters into a
string at a specified position, as in: string1 = "Visual programming"
resultString = string1.Insert(7, "Basic ") The result is "Visual Basic programming".
remove
This method removes a given number of
characters at a given position, as in:
-
Prepared by: Noel Anonas
string1 = "Deadline" resultString =
string1.Remove(1, 4) The result is "Dine"
Substring
string1 = "position"
resultString = string1.Substring(2, 3)
We have selected from s (which is at index 2)
for 3 characters, hence the result is sit.
-
Prepared by: Noel Anonas
Exercise
Palindrome
Write a program which inputs one string and
determines whether or not it is a palindrome.
A palindrome reads the same backwards and
forwards, so 'abba' is a palindrome. Assume
that the string contains no spaces or
punctuation.
-
Prepared by: Noel Anonas
Exception Handling
Try main task
Catch exceptionObject As FormatException display an error message
Catch exceptionObject As Exception Throw a new Exception
Throw new Exception(Wrong input)
Finally termination code
End Try
-
Prepared by: Noel Anonas
Exercise
Write a program which provides two textboxes for the
input of integer values a and b.
Display the result of a\b and b\a.
(Recall that \ performs integer division.) Incorporate exception handling for zero and
nonnumeric input textbox values.
File
Stream
-
Prepared by: Noel Anonas
a stream of data flowing in or out of the program
Note:
The file classes are in the System.IO namespace.
This is not automatically imported, so use: Imports System.IO
Read and write lines of text The ReadLine() of StreamReader.
This reads a whole line of text into a string, excluding the end-of-line
marker.
The WriteLine() of The StreamWriter class. This writes a string to a file.
-
Prepared by: Noel Anonas
The OpenText() and CreateText() of the File class. These are shared methods, and provide us with a new instance of a
text stream.
File Output Example ' write some lines of text to the file
Dim outputStream As StreamWriter = _
File.CreateText("c:\myfile.txt")
outputStream.WriteLine("This file will")
outputStream.WriteLine("contain 3")
outputStream.WriteLine("lines of text.")
outputStream.Close()
File input 'read the file line-by-line
-
Prepared by: Noel Anonas
Dim inputStream As StreamReader = _ File.OpenText("c:\myfile.txt")
Dim line As String line = inputStream.ReadLine()
While line Nothing
TextBox1.AppendText(line &
vbCRLF) line = inputStream.ReadLine()
End While inputStream.Close()
Using file dialogs
OpenFileDialog
Ex: If OpenFileDialog1.ShowDialog() = DialogResult.OK Then MessageBox.Show(OpenFileDialog1.FileName)
End If
-
Prepared by: Noel Anonas
Using file dialogs
SaveFileDialog
Ex: If SaveFileDialog1.ShowDialog() = DialogResult.OK Then MessageBox.Show(SaveFileDialog1.FileName)
End If
Exercise - File
Write a program which puts your name and
address in a file named address.txt. Use an editor to check that the file has the expected contents.
-
Prepared by: Noel Anonas
Write a program to count the number of lines
in a file. Ensure that it works for an empty file
(producing a value of zero).
Color Dialog
Demo for ColorDialog
-
Prepared by: Noel Anonas
Font Dialog
Demo for FontDialog
-
Prepared by: Noel Anonas
Exercise
Create a list of movies titles (5 movies) using
ListBox. Change the background color of the
list of movies to yellow and the foreground
color of the list to red.
Creating Splash Screen
Demo
-
Prepared by: Noel Anonas
Creating About Form
Demo
-
Prepared by: Noel Anonas
Creating a Menu
MenuStrip
-
Prepared by: Noel Anonas
Exercise - Menu
Create a Editor Menu that will implement the
following:
File Open, File Save, Welcome Screen, Help,
About and Exit
Creating a Module
Exercise
Write a program which produces a random
number between 200 and 400 each time a
-
Prepared by: Noel Anonas
button is clicked. The program should display
this number, and the sum and average of all
the numbers so far.
Use Random class
Creating a Class
-
Prepared by: Noel Anonas
Creating Constructor
Creating an instance
Exercise - Class
Bank account Write a program that simulates a bank account.
A text box allows deposits (a positive number) to be made into
the account and withdrawals (a negative number) to be made.
The state of the account is continually displayed and, if the
account goes into the red (negative balance), a suitable message
is displayed. Create a class named Account to represent bank
accounts. It has methods Deposit and Withdraw, and a property
Currentbalance.
-
Prepared by: Noel Anonas
Exercise Class 2
Scorekeeper Design and write a class that acts as a scorekeeper for a
computer game. It maintains a single integer, the score. It
provides a method to initialize the score to zero, a method to
increase the score, a method to decrease the score, and a
method to return the score. Write instructions to create a
single object and use it.
Creating Subroutine and Function
Demo
-
Prepared by: Noel Anonas
Exercise
Balloons Add to the class Balloon some additional data, a String
that holds the name of the balloon and a variable
that describes its colour. Add code to initialize these
values using a constructor method and add the code
to display them.
Enhance the balloon program with buttons that move
the balloon left, right, up and down.
-
Prepared by: Noel Anonas
Timer
Properties
Enabled Set to True to switch the timer on. Interval The
frequency of Tick events in milliseconds (1/1000
seconds).
Events
Tick
Called when the timer ticks every Interval milliseconds.
Graphics
-
Prepared by: Noel Anonas
Graphics Constructor
Created from a picture box object using CreateGraphics. For
example:
Dim paper As Graphics = PictureBox1.CreateGraphics() Methods
Clear - Clear the graphics area and fill it with the colour provided
as the parameter.
DrawLine - Draw a line. Parameters: myPen As Pen, x, y, width, height
DrawEllipse -Draw an ellipse. Parameters: myPen As Pen, x, y, width, height
-
Prepared by: Noel Anonas
DrawImage - Draw an image. Parameters: myImage As Image, x, y, width, height
Graphics Methods:
DrawRectangle - Draw a rectangle. Parameters: myPen As Pen, x, y, width, height
FillEllipse - Draw a filled ellipse. Parameters: myBrush As SolidBrush, x, y, width, height
FillRectangle - Draw a filled rectangle. Parameters: myBrush As SolidBrush, x, y, width, height
-
Prepared by: Noel Anonas
Sample
Dim paper As Graphics
paper = PictureBox1.CreateGraphics() Dim
myPen As Pen = New Pen(Color.Black)
paper.DrawRectangle(myPen, 10, 10, 100, 50)
paper.DrawRectangle(myPen, 10, 75, 100,
100)
Exercise Steps Write a program to draw a set of
steps made from bricks, as shown in Figure.
-
Prepared by: Noel Anonas
Use the library method DrawRectangle to
draw each brick.
(Use for loop)
Exercise -
Graphics 1 Write a program which displays
changing minutes and seconds,
representing them by two long
rectangles: make the maximum width of the rectangles equal
to 600 pixels to simplify the arithmetic (10 pixels for each
minute and each second). Redraw the two rectangles every
-
Prepared by: Noel Anonas
second. The Figure shows a representation of 30 minutes and
15 seconds.
Exercise
Scorekeeper
-
Prepared by: Noel Anonas
Design and write a class that acts as a
scorekeeper for a computer game. It
maintains a single integer, the score. It
provides a method to initialize the score to
zero, a method to increase the score, a
method to decrease the score, and a method
to return the score. Write instructions to
create a single object and use it.