Wal Mart Online → Best Selection

Last Modified:


Visual Basic

Introduction to VB.NET

.NET Framework

VS2008 IDE

How VB is Compiled

Start Visual Studio

Windows Form App

Save Your Work

VB OOP Programming

Visual Basic Code

Exit Code

Button Event Code

Coding Recommendations


Error List Window

Comment Syntax

Help Window

Language Essentianl

Built-In Data Types

Declare Variables

Declare Constants

Code Arithmetic Expressions

Assignment Statements

Operator Precedence

Type Casting

Math Class

String Declaration

Conversion Functions

Conversion Methods

Formatting Functions

String Formatting

Variable Scope


Nullable Types

Loop Constructs

For Next Loop

Do While Loop

Do Until Loop



Exit Do | Exit For


Nested Loops


Array Declaration

Rnd( ) Function

Listbox Control


Parallel Arrays

Key Event Args

Dynamic Arrays

Redimension Array

Set Breakpoint

Start Debugger

ReDim Preserve

MultiDimensional Arrays

DataGridView Control

Length and Sort Methods


Pad Right

Split Method

IsNumeric Function

Multiform Projects

Add Form To Project

Form Object Methods

Form Show Method

ShowDialog Method

Form Close Method

Form Accept Button

Multiform Project Example

ASP.NET Web Programming

Create Data Source

Configure Access Data Source

Add Product Class

Extract Local Database Data

Order PageLoad VB Code

Add New Web Page

Set Start Page

Display Cart Aspx Code

Display Cart Design View

Sorted List Definition

VB.NET Session State

Create CartItem Class

GetCartContents Function

Add To Cart Event Handler

Remove Cart Item Event

Clear Cart Event Handler

How to use the Visual Basic Math Class

The .NET Math Class has several methods that allow the user to access several math functions. To help facilitate incorporation of these methods into your software development strategies, we will briefly cover 4 of the most common methods:

The Syntax of the Round Method:
Math.Round ( number [ , precision ] )

The Syntax of the Sqrt Method:
Math.Sqrt ( number )

The Syntax of the Min and Max Methods:
Math. { Min | Max } ( number1 , number2 )
Visual Basic Math Class Examples:

Statement Result
Math.Round (23.75) 24
Math.Round (23.5) 24
Math.Round (24.5) 24
Math.Round (23.754, 2) 23.75
Math.Round (23.755, 2) 23.76
Math.Sqrt (20.25) 4.5
Math.Max (23.75, 20.25) 23.75
Math.Min (23.75, 20.25) 20.25

Visual Basic Math Class Summary:
  • To use one of the static methods of the math class, use:
    1. The Class Name ( i.e. Sqrt )
    2. A dot ( . )
    3. One or more arguments in parentheses (i.e. ( 9 ) )

  • The arguments provide the values that are used by the method.

  • The Round method rounds a decimal argument to the specified precision.
    • If the precision is omitted, the number is rounded to the nearest whole number.

  • The Round method will round .5 to the nearest even whole number.
    • This is referred to as Banker's Rounding.

  • The Sqrt method returns the square root of the specified argument.
    • This argument can be any numeric data type.

  • The Min and Max methods return the Minimum and Maximum of two arguments.
    • These arguments must have the same data type.

Figure VB-41: Visual Basic Math Class Syntax, Examples and Description

How to work with Strings in Visual Basic

Technically, a string is text made up of a collection of characters. Typically, strings can be a single letter, a collection of letters, a word, a collection of words, a sentence, or a collection of sentences. Basically, it is up to the programmer how to decide how to organize the text. Below are several examples of how to use strings in Visual Basic:

How to Declare and Initialize a String:
Dim Message1 As String = "Invalid data entry."
Dim Message2 As String = ""
Dim Message3 As String = Nothing
How to Join Strings:
Dim FirstName As String = "Bob"
Dim LastName As String = "Smith"
Dim FullName As String = FirstName + " " + LastName
' FirstName is "Bob"
' LastName is "Smith"
' FullName is "Bob Smith"
How to Join a String and a Number:
Dim Price As Double = 39.99
Dim strPrice As String = "Price: " + Price

' strPrice = "Price: 39.99"
Visual Basic String Declaration Summary:
  • A String can consist of letters, numbers and special characters like: #&%!

  • A String's value is specified inside a pair of double quotes ("Like This").
    • This is known as a String Literal.

  • To assign a Null Value to a string, use the Nothing keyword.
    • This means that the value of the string is unknown.

  • To assign an empty string to a string use a pair of double quotes with nothing inside ("").

  • To join strings or strings and numbers use the '+' or '&' symbols.

Figure VB-42: Visual Basic String Declaration and Examples

Visual Basic Functions to Convert Data Types

Visual Basic requires that Data Types often be of the same type before they can be combined in an expression. If you have the number 65 and you want to add "ss" to 65 what do you have? In much the same way Visual Basic needs to know what format you wish to have the end result, so the proper computation can be carried out. For this reason, Visual Basic has several conversion functions that allow you to convert one data type to another:

Visual Basic Functions for Data Conversion
Function Description
CDbl ( expression ) Convert the expression to the Double Data Type
CDec (expression ) Convert the expression to the Decimal Data Type
CInt ( expression ) Integer Conversion. Any fractional portion is rounded to the nearest whole number.
CLng ( expression ) Converts the expression to the Long Data Type
CType ( expression, TypeName ) Converts the expression to any type of object
Data Conversion Function Examples:
Dim Grade As Integer = CInt( 93.75 )
' Grade = 94
Dim Subtotal As Decimal = CDec( txtSubtotal.Text )
' May throw exception
Dim A As Double = 6.5
Dim B As Integer = 6
Dim C As Integer = 10
Dim Ave As Integer = CInt( (CInt( A ) + B + C ) / 3 )

' Ave = 7
Dim SalesString As String = "$2,155.27"
Dim SalesDouble As Double = CDec( SalesString )
' CDec accepts → $ , .
Dim SalesString = CStr( SalesDouble )
' SalesString = 2155.27
Dim SalesString = CType( SalesDouble, String ) ' SalesString = 2155.27
Visual Basic Data Conversion Function Summary:
  • These functions are carrried out first, before any arithmetic operation.

  • To convert a variable to a string, you can use the CStr function or ToString method

  • The CType function can also be used to convert object types.

Figure VB-43: Visual Basic Conversion Functions Description and Examples

Visual Basic Methods to Convert Data Types

In the transition of Visual Basic to an Object Oriented Language, Data Conversion Methods were introduced for Data Conversion functionality. The Data Conversion Functions have been maintained to this point. Following is a list of some of the methods of the Convert Class for converting all of the built-in data types:

Visual Basic Methods for Data Conversion:
Method Description
ToString ( [ format ] ) Method converting the associated value to a string using the specified format.
Parse ( String ) A shared method which converts the string to an equivalent Data Type.
ToDecimal ( value ) Converts value to the Decimal Data Type
ToDouble ( value ) Converts value to the Double Data Type
ToInt32 ( value ) Converts value to the Integer Data Type
ToChar ( value ) Converts value to the Char Data Type
ToBool ( value ) Converts value to the Boolean Data type
Data Conversion Method Examples:
Dim Sales as Double = 1074.98
Dim strSales As String = Sales.ToString
Sales = Double.Parse( strSales )
' Double to String
' String to Double
Dim Price As Double = 29.55
Dim strPrice As String = "Price: $" + Price
' Automatic ToString Conversion
Dim Subtotal As Double
Subtotal = Convert.ToDouble ( txtSubtotal.Text )
Dim Months As Integer = Convert.ToInt32 ( txtMonths.Text )
txtSubtotal.Text = Convert.ToString ( Subtotal )
Dim intSubtotal As Integer = Convert.ToInt32 ( Subtotal )

' String to Double
' String to Integer
' Double to String
' Double to Integer
Visual Basic Data Conversion Method Summary:
  • The ToString and Parse methods are included in all of the data structures.

  • The compiler may automatically call the ToString method when required.
    • Best programming practices would be to call ToString explicity when required.

  • The Convert Class contains shared methods for all of the built-in types.

Figure VB-44: Visual Basic Data Conversion Methods - Description and Examples

Visual Basic Formatting Functions

The Visual Basic Formatting functions allow you to convert a numeric value to a formatted string. The first argument is the expression to be formatted, and the optional second argument is the number of decimal digits to be used. The following diagram illustrates the use of these functions:

Visual Basic Syntax for Formatting Functions:

FormatNumber ( expression [, NumberOfDigits ] )
FormatCurrency ( expression [, NumberOfDigits ] )
FormatPercent ( expression [, NumberOfDigits ] )

Visual Basic Formatting Functions Examples:

Expression Result
FormatNumber ( -.888 ) -0.89
FormatNumber ( -.888, 2) -0.89
FormatNumber ( -.888, 1) -0.9
FormatNumber ( 2100 ) 2,100.00
FormatCurrency ( 2100 ) $2,100.00
FormatPercent ( .777 ) 77.70%
FormatPercent ( .777, 1 ) 77.7%

Visual Basic Formatting Functions Summary:
  • Formatting functions are used to format a number for display purposes.

  • Typically, 1 or 2 arguments are used:
    • The expression to be formatted.
    • The optional number of digits to the right of the decimal.

Figure VB-45: Visual Basic Formatting Functions

Visual Basic String Formatting Methods

Visual Basic provides for several format specifiers which allow the programmer to use several string formatting options. Additionally, Visual Basic also provides the Format method of the string class to achieve similar results. Listed below is a synopis of these two methods:

Visual Basic Standard Formatting Codes:

Code Format Description
C or c Currency Formats the number as currency with the specified number of decimal places
P or p Percent Formats the number as a percent with the specified number of decimal places.
N or n Number Formats the number with thousands separators with specified decimal places.
F or f Float Formats the number as a decimal with the specified number of decimal places.
D or d Digits Formats an Integer with the specified number of Digits.
E or e Exponentiation Formats the number in scientific notation with specified number of decimal places.
G or g General Formats the number as a decimal or scientific notation - whichever is more compact.

Visual Basic ToString Method to Format a Number:

Statement Result
Dim strMonthlyAmount As String = Amount.ToString("c") $2,347.15
Dim strInterestRate As String = Interest.ToString("p1") 4.7%
Dim strQuantity As String = Quantity.ToString("n0") 35,000
Dim strPayment As String = Payment.ToString("f3") 542.188

Visual Basic String.Format Method to Format a Number:

Statement Result
Dim strMonthlyAmount As String = String.Format("{0:c}", 2347.15) $2,347.15
Dim strInterestRate As String = String.Format("{0:p1}", 0.047) 4.7%
Dim strQuantity As String = String.Format("{0:n0}", 35000) 35,000
Dim strPayment As String = String.Format("{0:f3}", 542.1877) 542.188

Visual Basic String Formatting Summary:

  • Placing a number after the D Formatting Code specifies the number of digits in the result.
    • If the Integer has fewer digits than specified - zeros are added to the beginning.

  • Including a number after the formatting codes specifies the number of decimal places in the result.
    • If the value has more decimal places, the result will be rounded.
    • If no number is specified, the default value is 2.

Figure VB-46: Visual Basic String Format Methods

Help Support this site

Thank you

No Selling Necessary
Technical Services Needed