Control Flow Statement or Conditional Statements

Decision structure 0r Control Structure

  1. If…..Then….Else Statement
  2. Select Case Statement

(A) If…..Then….Else Statement

Control flow statement or conditional statements are used to change the flow of the programme based on condition.

Condition is evaluated, & depending on the result of the condition, the block of code is executed.

Syntax :

If condition1 Then
 Statements
ElseIf condition2 Then
ElseifStatements
……………
……………
Else
ElseStatements
End If

When a multiple-line IfThenElse is encountered, First condition is tested. If condition is True, the statements following Then are executed. If condition is False, next ElseIf condition is tested. If that condition is true, the statements following the associated Then are executed. If no ElseIf condition evaluates to True, the statements following Else are executed. 

Example :

Dim No As Integer
 No = 55000
 If No < 10 Then
MsgBox("One Digit No.")
 ElseIf No < 100 Then
MsgBox("Two Digit No.")
 ElseIf No < 1000 Then
MsgBox("Three Digit No.")
 Else
MsgBox("More Than Three Digit No.")
 End If

Output will be More Than Three Digit No.

(B) Select Case Statement

It is used to execute one of several groups of statements, depending on the value of an expression.

In If…Then….Else statement every If & ElseIf condition is evaluated, while in Select Case statement initially only one-time TestExpression is evaluated, and the result of that TestExpression is compare for every case.

By using Select Case statement, code is easier to read & maintain as compare to If… Then…. ElseIf statement.

Syntax :

Select Case TestExpression
Case ExpressionList1
Statements…
Case ExpressionList2
 Statements…
 …………………
……………….
Case Else
 ElseStatements
End Select

Example :

Dim No As Integer
 No = 55000
 Select Case No
 Case 0 To 9
MsgBox("One Digit No.")
Case Is <= 99
 MsgBox("Two Digit No.")
Case 100 To 999
MsgBox("Three Digit No.")
Case Else
 MsgBox("More Than Three Digit No.")
 End Select

Output will be More Than Three Digit No.

Looping structure or Looping Statement

Looping statements are used to execute a series of statements repeatedly, until a specified condition is True or until a condition is False or a specified number of times.

VB .NET supports following Loop structure.

  1. For….Next Loop Statement
  2. Do….Loop Statement
  3. While….End While Statement
  4. For Each….Next Statement

For….Next Loop Statement :

For….Next Loop Statement is used to execute a series (block) of statements a specified number of times.

Syntax :

For counter [ As datatype ] = start To end [ Step step ]
 [ statements ]
 [ Continue For ]
 [ statements ]
 [ Exit For ]
 [ statements ]
Next [ counter ]

The Counter variable is originally set to start automatically when the loop begins. Each time through the loop, Counter is incremented or decrement by step and when Counter equals end, the loop ends. If you do not specify the step value, by default it is set to 1.

Exit For statement is used to immediately exits the For loop in which it appears. Execution continues with the statement following the Next statement. It Transfers control out of the For loop.

Example :

To print Odd numbers between 1 to 20.

Dim S As String
 For I As Integer = 1 To 20 Step 2
S = S &I & " "
 Next
 MsgBox(S)

Output will be 1 3 5 7 9 11 13 15 17 19

Do….Loop Statement

Repeats a block of statements while a Boolean condition is True or until the condition becomes True.

Use a Do…Loop structure when you want to repeat a set of statements an indefinite number of times, until a condition is satisfied. If you want to repeat the statements a set number of times, the  For…Next Statement is usually a better choice.

  Do While condition     [Statements]     [Exit Do] [Statements] Loop    Do Until condition     [Statements]     [Exit Do] [Statements] Loop  

 OR

  1. While : Repeat the loop till the condition is True.
  2. Until :  Repeat the loop till the condition is false.

Following Do…..loop statement checks the condition at the end of the loop, so that means so loop statements will executed at least once.

Do      [Statements]     [Exit Do] [Statements] LoopWhile condition   Do      [Statements]     [Exit Do] [Statements] Loop Until condition  

Exit Do statement is used to immediately exit the Do loop in which it appears (to escape the loop). Execution continues with the statement following the Loop statement.

While….End While Statement

It executes the series of statements as long as the given condition is True

While condition
[Statements]
[Exit While]
[Statements]
End While

Exit Whilestatement is used toimmediately exits the While loop in which it appears. Execution continues with the statement following the End While statement

For Each…Next Statement :

Repeats a group of statements for each element in a collection or array. You can use a For Each loop to iterate through every element of a collection or array. You need not to get loop indices.

For Each element [As datatype] In group
[Statements ]
[Exit For ]
[Statements ]
Next [element ]

element : Used to iterate through the elements of the collection.

group : Required. Object variable. Refers to the collection over which the statements are to be repeated.

Exit For statement is used to transfers control out of the For Each loop.Execution continues with the statement following the Next statement.

Example :

‘To disable all the textbox of the current form.
For Each C As Control In Me.Controls
If TypeOf C Is TextBox Then
C.Enabled = False
End If
 Next

With …End With statement

Using With….End With statement, you can refer to particular object only once, instead  of repeating reference to a single object. It is not a Loop.

For example, to change a number of different properties on a single object, place the property assignment statements inside the With…End With, referring to the object only once instead of for each property assignment.

WithButton1
 .Text = "Exit"
 .BackColor = Color.LightCyan
 .ForeColor = Color.Red
 .Height = 30
 .Width = 80
End With

VB .NET File Extension :

  1. .sln: Solution File, which stores the solution’s configuration. This contains one or more projects (similar to the VB6 group file).
  2. .vbproj: Represents a Visual Basic project.
  3. Vbproj.user: Contains project level user options.
  4. .vb: vForm’s code file. (Contains source code).
  5. AssemblyInfo.vb: It contains general information about an assembly, including version information. The AssemblyInfo.vb file contains extra information, or metadata, about your application.
  6. Bin: Directory for binary executables.
  7. Obj: Directory for debugging binaries.

What is a namespace?

Namespaces are a way to define the classes and other types of information into one hierarchical structure. System is the basic namespace used by every .NET code.

If we can explore the System namespace a little bit, we can see it has a lot of namespace user system namespace. For example, System.Io, System.Net, System. Collections, System.Threading, etc.

A namespace can be created via the Namespace keyword. Here is an example to create a “Books” namespace in VB.NET and C#.

VB.NET Code:

  • Namespace Books
  • Class Authors
  • ‘Do something
  • End Class
  • End Namespace
  • Namespace Books
  • Namespace Inventory
  • Imports System
  • Class AddInventory
  • Public Function MyMethod()
  • Console.WriteLine(“Adding Inventory via MyMethod!”)
  • End Function End Class
  • End Namespace
  • End Namespace

Imports Statement: 

You can use Imports statements to import a namespace so you don’t have to qualify items in that namespace by listing the entire namespace when you refer to item.

Imports [aliasname =] namespace OR Imports [aliasname =] namespace.element

VB.Net’s Built-in Functions  

String functions 

FunctionDescription
Mid (str, pos, n)Returns n characters from the text string referred to by str, starting at character position pos
Microsoft.VisualBasic.left (str, n)Returns the n left-most characters from the text string referred to by str.
Microsoft.VisualBasic.right (str, n)Returns the n right-most characters from the text string referred to by str.
Trim (str)Removes the white space (if any) at either end of the text string referred to by str, and returns the result.
LTrim (str)Removes the white space (if any) at the left-hand end of the text string referred to by str, and returns the result.
RTrim (str)Removes the white space (if any) at the right-hand end of the text string referred to by str, and returns the result.
InStr (n, str1, str2)Looks for an occurrence of the substring str2 within the string str1, starting at character position n. If successful, the function returns the character position at which the substring is found (or zero if the substring cannot be found).
UCase (str)Converts the string referred to by str to all upper-case characters, and returns the result.
LCase (str)Converts the string referred to by str to all lower-case characters, and returns the result.
Chr (charCode)Returns the ASCII character corresponding to the 8-bit character code charCode (note – some characters are non-printing characters, and will not be visible on screen).
Asc (character)Returns the 8-bit ASCII character code corresponding to character

Maths functions 

FunctionDescription
Math.Sqrt (n)Returns the square root of a number, n.
Math.Abs (n)Returns the absolute value of a number, n.
Math.Exp (n)Returns the exponential value of a number, n – i.e. e n. Note: e = 2.71828182
Fix (nReturns the integer part of a floating point number, n.
Int (nReturns the integer part of a floating point number, n, for positive numbers, or the next smallest integer value for negative numbers.
Math.Log (n)Returns the natural logarithm of a number, n.
Rnd () Returns a randomly generated value between 0 and 1.
Round (n,mRounds a number, n, up (or down) to m decimal places.

VB.NET Date & Time

In VB.NET, we use the Date and Time function to perform various operations related to date and time. Sometimes we need to display the date and time in our application or web application, such as when the last post edited, upgradation of new software version or patch-up details, etc.

In DateTime class, Date datatype stores date values, time values or date, and time values. Furthermore, to perform the date and time function, we need to import the System.DateTime class. The default value of DateTime is between 00:00:00 midnight, Jan 1, 0001 to 11:59:59 P.M., Dec 31, 9999 A.D.

Properties of Date Time :

  1. Date: It is used to return the date component of the DateTime Object.
  2. Day: It is used to return the day of the month represented by the DateTime object.
  3. DayOfWeek: It is used to return a particular day of the week represented by the DateTime object.
  4. Minute: The Minute property is used to return the minute component by the DateTime object.
  5. DateOfYear: It is used to return a day of the year represented by the DateTime object.
  6. Hour: It is used to return the hour of the component of the date represented by the DateTime object.
  7. Now: It is used to return the current date and time of the local system.
  8. Month: The Month property is used to return the month name of the Datetime object.
  9. Second: It is used to return the second of the DateTime object.
  10. Ticks: It is used to return the number of ticks that refer to the DateTime object.
  11. Today: It is used to return the current date of the system.
  12. Year: It is used to return the year of the date represented by the DateTime object.
  13. TimeOfDay: It is used to return the time of the day represented by the DateTime object.

Methods of DateTime :

The following are the most commonly used methods of the Date Time.

  1. DaysInMonth: The DaysInMonth method is used to return the total number of days in the specified month of the year.
  2. Add: It is used to return a new DateTime value by adding the timespan value to the DateTime object value.
  3. AddHours: It is used to return a new time by adding the hours to the value of the Datetime object.
  4. AddYears: It is used to return the year by adding the year to the value of the DateTime object.
  5. AddDays: It is used to return the new Day by adding the days to the value of the DateTime object.
  6. AddMinutes: It is used to display the new time by adding the minutes to the Datetime object.
  7. AddMonths: It is used to return the new time by adding the months to the value of the Datetime object.
  8. AddSeconds: It is used to return the new time by adding the seconds to the value of the Datetime object.
  9. IsLeapYear: It uses a Boolean value that represents whether the particular year is a leap year or not.

Other Date & Time function

àDateAdd : Returns a Date value to which a specified time interval has been added.

Example :

Dim DT1 As Date = #11/12/2009# ' Formate of Date is mm/dd/yyyy
 MsgBox(DateAdd(DateInterval.Month, 5, DT1))'
                                         Gives output :12/04/2010

DateDiff :Returns a value specifying the number of time intervals between two Date values.

Type Conversion Functions :

There are functions that we can use to convert from one data type to another. They include: 

  1. CBool (expression): converts the expression to a Boolean data type. 
  2. CDate(expression): converts the expression to a Date data type.
  3. CDbl(expression): converts the expression to a Double data type.
  4. CByte (expression): converts the expression to a byte data type. 
  5. CChar(expression): converts the expression to a Char data type.
  6. CLng(expression): converts the expression to a Long data type.
  7. CDec(expression): converts the expression to a Decimal data type.
  8. CInt(expression): converts the expression to an Integer data type.
  9. CObj(expression): converts the expression to an Object data type.
  10. CStr(expression): converts the expression to a String data type.
  11. CSByte(expression): converts the expression to a Byte data type.
  12. CShort(expression): converts the expression to a Short data type.

Type Checking Functions :

àIsNumeric : Returns True if the value is numeric.

Example : 

Dim STR As String = "hello"
 MsgBox(IsNumeric(STR))                         ‘ Output : False

àIsDate : Returns True if it is expression is valid date.

Example : 

Dim DT As Date = #11/12/2009#
 MsgBox(IsDate(DT))                    ‘ Output : True

àIsNothing : Returns True if the expression has not assigned a value.

Example :

Dim B1 As Byte
 MsgBox(IsNothing(B1))                         ‘ Output : False

àIsNothing : The System.DBNull value indicates that the Object represents missing or nonexistent data. DBNull is not the same as Nothing, which indicates that a variable has not yet been initialized. DBNull is also not the same as a zero-length string (“”) (null string).

Example :

Dim B1 As Object = 1
 MsgBox(IsDBNull(B1))     ‘ Output : False
 B1 = System.DBNull.Value
 MsgBox(IsDBNull(B1))     ‘ Output : True

àIsArray : Returns a Boolean value indicating whether a variable points to an array.

Dim MyArray(5) As Integer
 MsgBox(IsArray(MyArray))   ‘ Output : True
 Dim I As Integer
 MsgBox(IsArray(I))         ‘ Output : False

MsgBox

The message box is always used to provide information to the user and convey the information to the user. This dialog box is used according to the following formula (Syntax).

Syntax :

MsgBox(Prompt, Buttons + Icon + Default Button, Title) As MsgBoxResult

following are the arguments (parameters) for this function:

Prompt :It is a string message displayed in the message box. The maximum length is about 1,024 characters. You can separate the lines using a carriage return character Chr(13)

Buttons : (Optional). 

  • Typeofbuttons to display, for example, OKOnly, OKCancel, YesNoCancel, YesNo, AbortRetryIgnore
  • the icon style to use, for example, Information, Exclamation, Question, Critical
  • the identity of the default button, for example, DefaultButton1, DefaultButton2,DefaultButton3
  • and the modality of the message box. 

Title: It is a string displayed in the title bar of the dialog box. Note that if you omit the title, then the application’s name is displayed in the title bar.

Return Value: This function returns a value, which indicates on which button the user has clicked. For example, either OK, Cancel, Abort, Retry, Ignore, Yes, or No.

Example : 

Me.DialogResult = MsgBox("Do you want to Exit?", MsgBoxStyle.YesNo +
MsgBoxStyle.Question +
MsgBoxStyle.DefaultButton2, "Quit")
If Me.DialogResult = MsgBoxResult.Yes Then
Me.Close()
End If
image

InputBox

InputBox function is used to create a modal dialog box, that is used to get (retrieve) one piece of information (a string of text) from the user.

InputBox displays a dialog box with title, message, one textbox, one OK & Cancel button. 

 To get a multiple piece of information you have to create your own custom dialog box. 

Syntax :

InputBox(Prompt,Title, DefaultResponse, Xpos, YPos) As String

And here are the arguments (parameters) for this function:

Prompt :It is a string message displayed in the input box. You can separate the lines using a carriage return character Chr(13)

Title : (Optional) It is a string displayed in the title bar of the dialog box. Note that if you omit title, then the application’s name is displayed in the title bar.

DefaultResponse : (Optional) A string expression displayed in the text box as the default input if no other input is provided. Note that if you omit DefaultResponse, the displayed text box is empty.

XPos : (Optional)  The distance in pixels of the left edge of the dialog box from the left edge of the screen. Note that if you omit XPos, the dialog box is centered horizontally.

YPos : (Optional) The distance in pixels of the upper edge of the dialog box from the top of the screen. Note that if you omit YPos, the dialog box is positioned vertically about one-third of the way down the screen.

Example  :

Dim ans As String
 ans = InputBox("Please enter your name", "Demo", "OM", 300, 300)