Programming with VB using Visual Studio 2010

About this Tutorial –

Objectives –

Delegates will learn to develop web applications using VB 4.0. After completing this course, delegates will be able to:

  • Use Visual Studio 2010 effectively
  • Programming with VB using Visual Studio 2010

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of ASP.Net will also find the content beneficial.

Prerequisites

Before attending this workshop, students must:

  • Be able to manage a solution environment using the Visual Studio 2010 IDE and tools
  • Be able to program an application using a .NET Framework 4.0 compliant language

Contents

Copyright 20/12/12 – David Ringsell

Download Solutions

Java tutorial

Lab 1 – VB Language Fundamentals

Write statements that prompt and greet the user.

  1. Open Visual Studio 2010 and create a new Visual Basic Console Application:
    • Select the File menu, then New, then Project.
    • Make sure (if you are using the Professional Version) that Visual Basic and then Windows is selected at the left of the screen under Installed Templates.
    • Name the project and the solution: VBLanguageFundamentals.
    • Browse to the place on your computer where you wish Visual Studio to create the directory for your solution (keeping the tick box selected).
    • Select Console Application and then click OK.
  2. In Program.cs find the Main method and insert the following line:
    Dim myName As String
  3. Write a statement that prompts users for their name.
  4. Write another statement that reads the user’s response from the keyboard and assigns it to the myName string.
  5. Add one more statement that prints “Hello myName” to the screen (where myName is the name the user typed in).
  6. When completed, the Main method should contain the following:
    Dim myName As String
    Console.WriteLine("Please enter your name")
    myName = Console.ReadLine()
    Console.WriteLine("Hello {0}", myName)
    Console.ReadKey()
  7. Test and save your work.
  8. View code file.

Lab 2 – Branching

  1. Open Visual Studio and create a new Visual Basic Console Application.
  2. Write statements to input two positive integers and display the sum.
    Module Module1
       Sub Main()
          Dim valueOne As Integer
          Dim valueTwo As Integer
          Dim valueThree As Integer
          Try
             System.Console.WriteLine("Please Enter A Whole Number: ")
             valueOne = Integer.Parse(Console.ReadLine())
             System.Console.WriteLine("Please Enter Another Whole
             Number: ")
             valueTwo = Integer.Parse(Console.ReadLine())
             valueThree = valueOne + valueTwo
             If (valueThree > 0) Then
                System.Console.WriteLine("The Sum of ValueOne: {0} and
             ValueTwo: {1} is Equal to: {2}", valueOne, valueTwo,
             valueThree)
             Else
                System.Console.WriteLine("Both Values were Zero!")
             End If
          'Handle exception generated by user input entered in
          'the wrong format
          Catch ex As System.FormatException
             Console.WriteLine("You didn't enter a Whole Number!")
          End Try
          Console.WriteLine(vbCrLf + "Please Press any Key to Exit")
          Console.ReadKey()
       End Sub
    End Module
  3. View code file.
  4. Write statements to input three numbers and display the largest using if statements. Aim to use the minimum number of statements.
    'Compare the numbers to find out which is the highest number
    intMax = intFirst
    If (intSecond > intMax) Then
       intMax = intSecond
    End If
    If (intThird > intMax) Then
       intMax = intThird
    End If
    'Show the largest
    Console.WriteLine("The largest is {0}", intMax)
    End If
  5. View code file.
  6. Write a switch statement to input a country and display its capital.
    Dim strMyCountry As String
    System.Console.WriteLine("Please Enter A Country: ")
    strMyCountry = Console.ReadLine()
    'Use switch to compare the myCountry string to the choices of country
    Select Case (strMyCountry)
       Case "England"
          Console.WriteLine("Your Capital is London." + vbCrLf)
       Case "France"
          Console.WriteLine("Your Capital is Paris." + vbCrLf)
       Case "Germany"
          Console.WriteLine("Your Capital is Munich." + vbCrLf)
       Case Else
          Console.WriteLine("The Capital is Unknown." + vbCrLf)
    End Select
  7. View code file.
  8. Write statements that to display the sequence 10, 20, 30, 40 … 100. Use a for loop.
    Dim counter As Integer = 0
    Dim counterb As Integer = 0
    'Use for loop to generate values from 1 to 100
    For counter = 1 To 100
       'Use another counter variable to count from 1 to 10
       'Print out counter when counterb reaches 10
       counterb += 1
       If (counterb = 10) Then
          Console.WriteLine("counter: {0} ", counter)
          counterb = 0
       End If
    Next counter
  9. View code file.
  10. Write statements that to display the sequence 1, 2, 3, … 100, as 10 rows of 10 numbers. Use a for loop.
    'Use for loop to count from 1 to 100
    For counter = 1 To 100
       'Use nextCounter variable to count from 1 to 10
       counterb += 1
       If (counter < 11) Then
          strNumberRow += Convert.ToString(counter) + " "
       Else
          strNumberRow += Convert.ToString(counter) + " "
       End If
       'When nextCounter reaches 10 print out the line of numbers
       If counterb = 10 Then
          Console.WriteLine(strNumberRow)
          strNumberRow = " "
          counterb = 0
       End If
    Next counter
  11. View code file.
  12. Test the application and save your work.
  13. When testing this solution please make sure the code module you want to test is set as the startup object:
    • Go to the Project menu and select Branching (the project name) Properties.
    • Select the module you want to test within the listbox under ‘Startup object’.

Lab 3 – Operators

  1. Open Visual Studio and create a new Visual Basic Console Application.
  2. Write statements using the multiplication operator to display the twelve-times table. Enter a number from 1 to 12, then display the number multiplied by 12.
    Dim valueOne As Integer
    Dim valueTwo As Integer
    'A const variable to hold the value that each number will be
    'multiplied by
    Const multiplyer As Integer = 12
    Console.WriteLine("Please enter a number between 1 and 12")
    valueOne = Integer.Parse(Console.ReadLine())
    'Use And operator to determine whether the number entered
    'by the user is between 1 and 12
    If (valueOne > 0 And valueOne < 13) Then
       valueTwo = valueOne * multiplyer
    Console.WriteLine("{0} x {1} = {2}", valueOne, multiplyer, valueTwo)
    Else
       Console.WriteLine("You didn't enter a number between 1 and 12")
    End If
  3. View code file.
  4. Write statements to input two numbers and use logical operators to output if the result of multiplying them will be positive or negative. For example, a negative number multiplied by a negative number, gives a positive result.
    valueThree = valueOne * valueTwo
    'Use the And operator to determine whether the two numbers are
    'both positive numbers - more than 0
    If (valueOne > 0 And valueTwo > 0) Then
       Console.WriteLine("The answer is a Positive Number. The answer
       is: {0}", valueThree)
    'Use the And operator to determine whether the two numbers are
    'both negative numbers - less than 0
    ElseIf (valueOne < 0 And valueTwo < 0) Then
       Console.WriteLine("The answer is a Positive Number. The answer
       is: {0}", valueThree)
    'Use the OR operator to determine whether one of the numbers is
    'less than 0
    ElseIf (valueOne < 0 Or valueTwo < 0) Then
       Console.WriteLine("The answer is a Negative Number. The answer
       is: {0}", valueThree)
    Else
       Console.WriteLine("Both numbers are not greater or less than 0")
    End If
  5. Test the application and save your work.
  6. View code file.

Lab 4 – Debugging

For all remaining lab exercises throughout this course, examine and debug your code by:

  1. Setting breakpoints in lines of code by clicking in the margin. When run the code will pause at the first beakpoint.
  2. Stepping through lines of code when a breakpoint is hit by pressing F11. The code will execute line by line. Hover the mouse pointer over a variable to show its current value.
  3. Using these debug windows to understand and fix code:
    • Watch
    • Locals
    • Immediate
    • Call Stack
  4. Debug windows are available only when the code is paused in break mode. Use the Debug>Windows command to show them.

Lab 5 – Structs

  1. Open Visual Studio and create a new Visual Basic Console Application.
  2. Define a structure called Colour, with a constructor and a ToString() method.
    'Declare a struct named Colour
    Public Structure Colour
       'Constructor
       Public Sub New(ByVal rVal As Integer, ByVal gVal As Integer, _
       ByVal bVal As Integer)
          red = rVal
          green = gVal
          blue = bVal
       End Sub
       'Display the Struct as a String
       Public Overrides Function ToString() As String
          Return String.Format("{0}, {1}, {2}", red, green, blue)
       End Function
    End Structure
  3. Add three integer properties to represent the red, green and blue component of the colour.
    'The Struct has properties
    Public Property Red() As Integer
    Public Property Green() As Integer
    Public Property Blue() As Integer
  4. Test the structure.
    Public Class Tester
       Public Sub Run()
          'Create an instance of the struct
          Dim colour1 As Colour = New Colour(100, 50, 250)
          'Display the values in the struct
          Console.WriteLine("colour1 colour: {0}", colour1)
          'Invoke the default constructor
          Dim colour2 As Colour = New Colour()
          Console.WriteLine("colour2 colour: {0}", colour2)
          'Pass the struct to a method
          MyMethod(colour1)
          'Redisplay the values in the struct
          Console.WriteLine("colour1 colour: {0}", colour1)
       End Sub
       'Method takes a struct as a parameter
       Public Sub MyMethod(ByVal col As Colour)
          'Modify the values through the properties
          col.Red = 200
          col.Green = 100
          col.Blue = 50
          Console.WriteLine("colour1 colour: {0}", col)
       End Sub
    End Class
    Sub Main()
       Dim t As Tester = New Tester()
       t.Run()
       Console.ReadLine()
    End Sub
  5. View code file.
  6. Save your work.

Lab 6 – Interfaces

  1. Open Visual Studio and create a new Visual Basic Console Application.
  2. Define an interface called IClient.
    'Define the interface
    Interface IClient
  3. Add properties for name and address details and a method called Order(), to the interface.
    Sub Order(ByVal orderNum As Integer)
    Property Name() As String
    Property Address() As String
  4. Create a second class called Customer that implements all the interface’s members.
    'Create a Customer class that implements the IClient interface
    Public Class Customer
    Implements IClient
       Public Sub New(ByVal s As String)
          Console.WriteLine("Creating a New Customer ID: {0}", s)
       End Sub
       'Implement the Order method
       Public Sub Order(ByVal newOrder As Integer) Implements _
       IClient.Order
          Console.WriteLine("Implementing the Order Method for IClient.
          The Order Number is: {0}", newOrder)
       End Sub
       'Implement the properties
       Public Property Name As String Implements IClient.Name
       Public Property Address As String Implements IClient.Address
    End Class
  5. Test the Customer class.
    Class Tester
       Public Sub Run()
          Dim cust As Customer = New Customer("H56388")
          cust.Name = "Brian Ferry"
          cust.Address = "23 Orange Lane, Clifton, Bristol, BS6 5FH"
          Console.WriteLine("The Name of the Customer is: {0}",
          cust.Name)
          Console.WriteLine("The Address of the Customer is: {0}",
          cust.Address)
          cust.Order(1234)
       End Sub
    End Class
  6. Test the application and save your work.
  7. View code file.

Lab 7 – Arrays

  1. Open Visual Studio and create a new Visual Basic Console Application.
  2. Create a two dimensional array of integers.
    'Declare the multi-dimensional array
    Dim intArray(,) As Integer
    'Initialise the mutli-dimensional array
    intArray = New Integer(9, 9) {}
  3. Use looping statements to populate the array.
  4. Use looping statements to display its elements.
    'Populate the int multi-dimensional array using a nested for loop
    For j = 0 To intArray.GetLength(1) - 1
       For k = 0 To intArray.GetLength(1) - 1
          'The intValue variable will count from 1 to a 100
          'Each of these numbers will be stored in each member
          'of the multi-dimensional array
          intValue += 1
          intArray(j, k) = intValue
          If (intValue < 10) Then
             'Convert each number to a string and append it to the
             'String variable
             numberRow += intArray(j, k).ToString + " "
          Else
             numberRow += intArray(j, k).ToString + " "
          End If
       Next k
       'Print out the row of numbers
       Console.WriteLine(numberRow)
       numberRow = " "
    Next j
  5. Test the application and save your work.
  6. View code file.

Lab 8 – Collection Interfaces and Types

  1. Open Visual Studio and create a new Visual Basic Console Application.
  2. Create an ArrayList of integers. Use looping statements to populate this with multiples of 10. Print each member of the list. Experiment with the ArrayLists methods, including the Sort(), Reverse() and Clear() methods.
    Dim intArray As ArrayList = New ArrayList()
    'Populate the Arraylist
    For i = 0 To 4
       intArray.Add((i + 1) * 10)
    Next i
    'Print each member of the ArrayList
    For Each j As Integer In intArray
       Console.Write("{0} ", j.ToString())
    Next j
  3. View code file.
  4. Create a Queue of integers. Use looping statements to populate this. Experiment with the Queues methods, including the Dequeue(), Enqueue () and Peek() methods.
    Dim intQueue As Queue = New Queue()
    'Populate the Queue
    For i = 0 To 4
       intQueue.Enqueue((i + 1) * 10)
    Next i
  5. View code file.
  6. Create a Stack of integers. Use looping statements to populate this. Experiment with the Stacks methods, including the Pop(), Push () and Peek() methods.
    Dim intStack As Stack = New Stack()
    'Populate the Stack
    For i = 0 To 5
       intStack.Push((i + 1) * 10)
    Next i
  7. View code file.
  8. Test the application and save your work.

Lab 9 – Strings

  1. Open Visual Studio and create a new Visual Basic Console Application.
  2. Input a string representing a URL, e.g. http://www.bbc.co.uk .
  3. Experimenting with extracting substrings, e.g. “bbc”.
    'Create some strings to work with
    Dim s1 As String = "http://www.bbc.co.uk"
    Dim s2 As String
    Dim s3 As String
    Dim index As String
    'Search for first substring
    s2 = s1.Substring(0, 4)
    Console.WriteLine(s2)
    'Search for next substring
    index = s1.LastIndexOf("/")
    s2 = s1.Substring(index + 1, 3)
    Console.WriteLine(s2)
    'Search for next substring
    index = s1.IndexOf(".")
    s2 = s1.Substring(index + 1)
    s3 = s2.Substring(0, 3)
    Console.WriteLine(s3)
  4. View code file.
  5. Experimenting with splitting the URL, e.g. using the dot (.) and forward slash (/) separators.
    'Create some strings to work with
    Dim s1 As String = "http://www.bbc.co.uk"
    'Constants for the space and comma characters
    Const Space As Char = "/"
    Const Fullstop As Char = "."
    Const Colon As Char = ":"
    'Array of delimiters to split the sentence with
    Dim delimiters() As Char = New Char() {Space, Fullstop, Colon}
    Dim output As String = ""
    Dim ctr As Integer = 0
    'Split the string and then iterate over the
    'Resulting array of strings
    Dim resultArray() As String = s1.Split(delimiters)
    For Each subString As String In resultArray
       If (subString <> "") Then
          ctr += 1
          output += ctr.ToString()
          output += ": "
          output += subString
          output += vbCrLf
       End If
    Next subString
    Console.WriteLine(output)
  6. Test the application and save your work.
  7. View code file.

Lab 10 – Throwing and Catching Exceptions

  1. Create a console application to enter two integers, then divide the numbers.
    'Do the division if legal
    Public Function DoDivide(ByVal a As Double, ByVal b As Double) As _
    Double
       If (b = 0) Then
          Throw New System.DivideByZeroException()
       End If
       If (a = 0) Then
          Throw New System.ArithmeticException()
       End If
       Return a / b
    End Function
  2. Add exception handling with multiple catch statements.
  3. Catch and respond to division by zero and other exceptions.
    'Most derived exception type first
    Catch e As System.DivideByZeroException
       Console.WriteLine(vbCrLf + "DivideByZeroException! Msg: {0}",
       e.Message)
    Catch e As System.ArithmeticException
       Console.WriteLine(vbCrLf + "ArithmeticException! Msg: {0}",
       e.Message)
    'Generic exception type last
    Catch
       Console.WriteLine("Unknown exception caught")
  4. Include a finally statement.
    Finally
       Console.WriteLine("Close file here.")
  5. Test the application and save your work.
  6. View code file.

Lab 11 – Delegates

  1. Open Visual Studio and create a new Visual Basic Console Application.
  2. Create a class Pair and include a delegate called WhichisFirst, a constructor, and methods called Sort() and ReverseSort().
    'A simple class to hold two items
    Public Class Pair
       'Private array to hold the two objects
       Private thePair(2) As Object
       'The delegate declaration
       Public Delegate Function WhichIsFirst(ByVal obj1 As Object, _
       ByVal obj2 As Object) As comparison
       'Passed in constructor takes two objects,
       'Added in order received
       Public Sub New(ByVal firstObject As Object, ByVal secondObject _
       As Object)
          thePair(0) = firstObject
          thePair(1) = secondObject
       End Sub
       'Public method that orders the
       'two objects by whatever criteria the objects like!
       Public Sub Sort(ByVal theDelegatedFunc As WhichIsFirst)
          If (theDelegatedFunc(thePair(0), thePair(1)) = _
          comparison.theSecondComesFirst) Then
             Dim temp As Object = thePair(0)
             thePair(0) = thePair(1)
             thePair(1) = temp
          End If
       End Sub
       'Public method that orders the
       'two objects by the reverse of whatever criteria the
       'objects likes!
       Public Sub ReverseSort(ByVal theDelegatedFunc As WhichIsFirst)
          If (theDelegatedFunc(thePair(0), thePair(1)) = _
          comparison.theFirstComesFirst) Then
             Dim temp As Object = thePair(0)
             thePair(0) = thePair(1)
             thePair(1) = temp
          End If
       End Sub
    End Class
  3. The sort methods will take as a parameters an instance of the WhichisFirst delegate.
    'Instantiate the delegate
    Dim theDogDelegate As Pair.WhichIsFirst = New Pair.WhichIsFirst _
    (AddressOf Dog.WhichDogComesFirst)
    'Sort using the delegate
    dogPair.Sort(theDogDelegate)
    dogPair.ReverseSort(theDogDelegate)
  4. Test the Pair class by creating a Dog class. This implements methods that can be encapsulated by the delegate.
    'Dogs are sorted by weight
    Public Shared Function WhichDogComesFirst(ByVal o1 As Object, _
    ByVal o2 As Object) As comparison
       Dim d1 As Dog = DirectCast(o1, Dog)
       Dim d2 As Dog = DirectCast(o2, Dog)
       If (d1.weight > d2.weight) Then
          Return comparison.theSecondComesFirst
       Else
          Return comparison.theFirstComesFirst
       End If
    End Function
  5. Test the application and save your work.
  6. View code file.

Lab 12 – Generics

  1. Open Visual Studio and create a new Visual Basic Console Application.
  2. Create a class that is generic.
  3. Add generic methods to the class.
    'Generic class
    Public Class Generics(Of T)
       'Generic method
       Public Sub Swap(Of K)(ByRef lhs As K, ByRef rhs As K)
          Dim temp As K 'Local generic data type
          temp = lhs
          lhs = rhs
          rhs = temp
       End Sub
  4. Test the application and save your work.
  5. View code file.

Back to the beginning

If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top