visual basic notes

some of these notes may have been created from other online sources.

they are just my home schooling notes.


comments begin with an ‘

Dim strFirstName As String    //create a variable named strFirstName of type String
Dim variableName As DataType

Dim myDate As Date
myDate = #1/20/1920#   //date assigned to variable of type date

10 ^ 2   //10 to the second power (100) (10*10)
10 mod 5 //modulus of 10 / 5
when operators have the same precedence they are evaluated from left to right
visual basic uses -1 to = true, and 0 to = false

The keyword Sub is used to declare a procedure that doesn’t return a value. It looks like this:
Public Sub MyProcedure()
‘ The procedure’s code goes here.
End Sub

The keyword Function is used to delare a procedure that returns a value. In addition,
it has a data type specified at the end of the procedure, which denotes the type of
data returned by the procedure:
Public Function MyProcedure() As String
‘ The procedure’s code goes here.
End Function

When referencing properties in code, you specify the object’s name first, followed by a
period (.), and then the property name, as in the following syntax:

btnClickMe.Left = 90   //assign 90 to variable btnClickMe’s Left


the keyword Me is shorthand for referencing the current form

you have to clean up after object to free the memory using “Dispose()”

multi-line code: (_), also known
as a line continuation character. It tells the Visual Basic compiler that the statement
immediately following the character is a continuation of the current statement.

know, the name of an event procedure is defined by
the control’s name, followed by an underscore and then the event name

displaying a window:
OptionsForm.Show()  //when added to onlick event it shows a window called OptionsForm. options form is the name
in the file/folder list (the file name)

To show a form as a modal form, you call the form’s ShowDialog() (modal = ontop of all windows and keeps focus)
You can display one modal form from another modal form, but you cannot display
a nonmodal form from a modal form.

to close a window: Me.Close()
to hide a window: Me.Visible = False

setting the icon for a child window to be the same as the main window:
Me.Icon = ViewerForm.Icon   //ViewerForm has the original icon set


creating a multi document interface:
set IsMdiContainer property to True on main container
double click main container to access the Load event and put:
Child1Form.MdiParent = Me  //Child1Form is the name of the child form
Child1Form.Show()          //Child1Form is the name of the child form calls the form when the application opens


to use a password field you create a text box and select the PasswordChar property. Change this property
to * or what ever char you want it to mask with.

closing a window : Me.Close()  // add to a button or event to close the current window


mylistbox.Items.Insert(0,”OptiontTextToAdd”) //0 is the index at where to place the item
lstChemicalEchoSongs.Items.Remove(“OptiontTextToAdd”)  //removes the option text
To clear the contents of a list box, use the Clear() method.

The SelectedItem method returns the text of the currently selected item.
If no item is selected, the method returns an empty string.
find the index of the selected item by using the SelectedIndex property


MessageBox.Show() is a Visual Basic function used to show a message to the user.
MessageBox.Show(“You selected “ & mylistbox.SelectedItem & “, which has an index of “ & mylistbox.SelectedIndex)


strResult = InputBox(“Please enter your age.”, “Enter Age)  //enter age is the name at the top, please etc is the message that pops up


The Interval property is specified in milliseconds, so a setting of 1,000 is equal to 1 second

lblClock.Text = TimeOfDay   //sets the text property of label lblClock to the time of day every second
make sure the timer is enabled (it is off by defualt)


add an item using
lstMyListView.Items.Add(“Mike Saklar”)

create an item and add sub item to it
Dim objListItem As ListViewItem
objListItem = lstMyListView.Items.Add(“Mike Hartman”, 0)

If lstMyListView.SelectedItems.Count > 0 Then
End If

lstMyListView.Items.Remove(lstMyListView.SelectedItems(0))  //remove first selected item (item 0)

lstMyListView.Items.Clear()  //remove all items


The ampersand, when used in the Text property of a menu item, tells Visual
Basic to underline the character immediately following it.
typing F&ile would underline the i in File
Sub  // function which doesnt return a value
Function //   function which does return a value

Public Function myfunction(myInt As Int) As DataType  //function which returns a type of Datatype (int, etc)
End Function

by default variables are passed by value (a copy of the variable is created inside the function)
to pass by reference (to work on the original) you use the ByRef keyword
public Function (ByRef myint) As Int

to force vb to pass by value the ByVal keyword is used.

Exit Sub           //used to exit current sub
Exit Function    //used to exit current Function


Const myConstVariable As Int = 18
Dim myarray(10) As String  //creates 10 buckets each capable of holding a string
myarray(0) = “My String”   //assigns string to myarray

multi dimensional arrays:

Dim myArray(10,10) As String  //create 10 x 10 array of string containers
myarray(0,0) = “My String”
Global Variables:
Public Const myVariable As Integer = 31     //creates a global constant
Public MyVariable As String                 //notice the missing Dim keyword

global variables are declared inside a modules Declarations section.
Double click the module, then in the right hand side up top click to find Declarations section

Static VAriables:
The keyword Static can be used so that variables retain information after a function is called.
Static myVariable as Integer

String Concatenation:

The & operator is used to join strings:
“TEST” & “TEST2” //equals TESTTEST2

The final result is that the variable strFullName contains the string James Foxall

Dim strFirstName as String
Dim strFullName as String
strFirstName = “James”
strFullName = strFirstName & “ “ & “Foxall”

The Len() function accepts a string (variable or literal) and returns the number of
characters in the string.
Debug.WriteLine(Len(“Pink Floyd reigns supreme.”))  //prints 26

another way to get the length of a string is to use the Length method:

The Microsoft.VisualBasic.Left() function always retrieves text starting with the
leftmost character

The Microsoft.VisualBasic.Left() function accepts two parameters:
. The string from which to retrieve a portion of the left side
. The number of characters to retrieve
Debug.WriteLine(Microsoft.VisualBasic.Left(“Queen to Queen’s Level 3.”, 5))

The Microsoft.VisualBasic.Right() function is the sister of the
Microsoft.VisualBasic.Left() function
it starts at the rightmost character, counts back the number of characters you
specify, and returns that many characters from the right side of the string

Debug.WriteLine(Microsoft.VisualBasic.Right(“Duct tape fixes everything.”, 5))

The Mid() function enables you to
specify where in the string to begin retrieving text, as well as how many characters to
The Mid() function accepts the following three parameters:
. The string from which to retrieve a portion of text
. The character at which to begin retrieving text
. The number of characters to retrieve

Debug.WriteLine(Microsoft.VisualBasic.Mid(“You look like you could “ & “use a monkey.”, 5, 7))
//output = look li

you can omit the last parameter. When you do, the
Mid() function returns everything from the starting character to the end of the string

Trim() Removes all leading and trailing spaces from the supplied string.
LTrim() Removes only the leading spaces from the supplied string.
RTrim() Removes only the trailing spaces from the supplied string.

Replace() function call has the following syntax:
Replace(expression, findtext, replacetext)

Dim strText As String = “Give a man a fish”
strText = Replace(strText, “fish”, “sandwich”)  //searches “strText” for fish and replaces it with sandwich


Working with dates:

Dim dteMyBirthday As Date = #7/22/2010#

Dim dteToday As Date = DateTime.Today  //returns current system date
Dim dteToday As Date = DateTime.Now    //returns current system date and time

Conditional expressions

If expression Then
… ‘ code to execute when expression is True.
End If

If expression Then

ElseIf expression2 Then

End If

Select Case expression
Case value1

Case value2

Case value3

Case Else

End Select

Select Case strColor
Case “Red”,”Purple”,”Orange”
‘ The color is a warm color.
Case “Blue”,”Green”,”Blue Violet”
‘ The color is a cool color.
End Select

Select Case lngAge
Case 1 To 7
‘ Code placed here executes if lngAge is 1, 7 or any number in between.
End Select

The FOR Loop:
The loop initializes intCounter at 1, prints the value of
intCounter, increments intCounter by 1, and continues looping
This loop would execute 100 times, printing the numbers 1 through 100 to
the Immediate window. the next statement continues the loop

Dim intCounter As Integer
For intCounter = 1 To 100  //start loop from 1 to 100 count intCounter is init to 1
Next intCounter       //what loop is to be continued in this case intcounter

Dim intCounter As Integer
For intCounter = 1 To 100 Step 4  //the Step keyword changes the increment count by 4 instead of 1
Next intCounter

Dim intCounter As Integer
For intCounter = 1 To 100
If condition Then Exit For  //en exit statement. if the condition is met it breaks (same as break)
Next intCounter

For countervariable = 1 to 1000
If expression Then
Continue For // Acts just like the Next statement
End If
‘ Other code…
Next countervariable

The DO loop:


If expression Then Exit Do  //exit clause


using go to:

intCounter = intCounter + 1
If intCounter < 5000 Then GoTo IncrementCounter
End Sub
Structured Execption Handling

Try  //code that may cause an error, the code to watch

Catch ex As Exception  //code that executes if there is an error

Finally                //code that always executes after the code in the try

End Try                //end the try
Debug.WriteLine(“Done Trying”)

getting information about the error that has occured:
the format is as below
Catch variablename As Exception  // variable to hold a reference to an Exception object

you then use the new variable to access its Message method
as shown below

Catch ex As Exception  //ex is variable name
MessageBox.Show(“An error has occurred: “ & ex.Message)  // using ex.Message to grab the error message


values exposed by an object are called properties.
Instead of exposing public variables, you should use property procedures to create class properties.
Public procedures are visible outside the application.
Procedures declared as Friend, on the other hand, behave like Public
procedures, with the exception that they are not available outside the application.

Public Property propertyname() As datatype // Public Property myproperty() as Integer

Get                                        //function for reading the property
Return myvariable
End Get

Set(ByVal Value As datatype)               //code to set the property
myvariable = Value
End Set

End Property

if you set the readonly keyword when creating you property you can skip the set function.
(the set function is not needed as the property is read only)

Public ReadOnly Property Height() As Integer
Return m_intHeight
End Get
End Property

functions and subs are defined inside the class and are called methods.
they are declared the same in or out of a class.

creating an object from a class:

late binding:

Dim objMyObject As Object
objMyObject = New clsMyClass()

early binding
Dim objMyObject As clsMyClass       //creates an object of type clsMyClass
Dim objMyObject = New clsMyClass()  //creates an object of type clsMyClass

To explicitly release an object, set the object variable equal to Nothing, like this:
objMyObject = Nothing
here txtSource is a control which has a text box for a file name. the Text property is simply the file name typed
into this text box. (thus the .Text part is referenced)

so the syntax would be:
System.IO.File.Move(sourcefile, destinationFile)

System.IO.File.Delete(txtSource.Text)  //deletes a file
System.IO.File.Move(txtSource.Text, txtDestination.Text)  //moves a file
System.IO.File.Copy(txtSource.Text, txtDestination.Text)  //copies a file

to rename a file just move it and change the name in the destination part

checking if a file exists:
Private Function SourceFileExists() As Boolean
If Not (System.IO.File.Exists(txtSource.Text)) Then  //the real part, System.IO.File.Exists()
MessageBox.Show(“The source file does not exist!”)
Return False
Return True
End If
End Function

checking file properties on page 422 sams teach yourself visual basic 2010 in 24 hrs

create a directory:
System.IO.Directory.CreateDirectory(“c:my new directory”)

checking if a directory exists:

move a directory:
System.IO.Directory.Move(“c:current directory name”, “c:new directory name”)

delete a directory:

to send a directory to the recycle bin:
My.Computer.FileSystem.DeleteDirectory(“D:OldDir”, FileIO.UIOption.AllDialogs, FileIO.RecycleOption.SendToRecycleBin, FileIO.UICancelOption.ThrowException)

creating registry keys:
if you have a path to a key and a folder does not exist it will be created

My.Computer.Registry.CurrentUser.CreateSubKey (“SoftwareCleverSoftwarePictureViewer”)  //creates PictureViewer under HKEY_CURRENT_USERSoftwareCleverSoftwarePictureViewer

My.Computer.Registry.CurrentUser.DeleteSubKey (“SoftwareCleverSoftwarePictureViewer”)

to set the value of an existing value item, you use
My.Computer.Registry.SetValue(). The SetValue()method has the following syntax:

SetValue(keypath, itemname, value)

My.Computer.Registry.SetValue (“HKEY_CURRENT_USERSoftwareCleverSoftwarePictureViewer”, “RegistrationName”, “James Foxall”) //sets value for RegistrationName

to get the value of a key:

GetValue(keypath, itemname, defaultvalue)

MessageBox.Show(My.Computer.Registry.GetValue (“HKEY_CURRENT_USERSoftwareCleverSoftwarePictureViewer”, “RegistrationName”, ““))

working with files:

Dim objFile As New System.IO.StreamWriter(“c:test.txt”, True)  //writes to test.txt and appends data to it. the true setting tells it to append if there is already a file existing

an example session writing a file:

Dim objFile As New System.IO.StreamWriter(“c:test.txt”)

This snippet would produce the following data in the text file:

It’s vital that you close a text file
when you’re finished with it, and the Close() method does this. In addition, you
should also call objFile.Dispose() to make sure that the file is fully released.

Now, consider the same code snippet that uses Write() instead of WriteLine():
Dim objFile As New System.IO.StreamWriter(“c:test.txt”)

This snippet produces a text file that contains the following:

when you reach the end of the file the return result will be “Nothing”
you can use “Do Until myVariable Is Nothing ” loops with it. it will loop unti myVariable = “Nothing”

Do Until strAlbumName Is Nothing       //loops until strAlbumName = “Nothing”
lstAlbums.Items.Add(strAlbumName)      //adds the current line fed in into a list box (an imaginary one)
strAlbumName = objFile.ReadLine()      //reads one line into variable strAlbumName
Loop                                   //instructs VB to loop

Dim objFile As New System.IO.StreamReader(“c:test.txt”)

reading the whole file at once into a variable:

Dim objFile As New System.IO.StreamReader(“c:test5.txt”)  //select file name
Dim strContents As String                                  //create string variable
strContents = objFile.ReadToEnd()                          //read whole contents of file into variable
objFile.Close()                                            //close the file being written
objFile.Dispose()                                          //make sure variable is deleted

reading one line at a time:

Dim objFile As New System.IO.StreamReader(“c:albums.txt”)
Dim strAlbumName As String
strAlbumName = objFile.ReadLine()


. SqlConnection is used to establish a connection to a SQL Server data source.
. DataSet is a memory-resident representation of data. There are many ways of
working with a DataSet, such as through DataTables.
. DataTable holds a result set of data for manipulation and navigation.
. DataAdapter is used to populate a DataReader.

Dim cnADONetConnection As New SQLConnection()  //

page 376

Leave a Reply