Unit 3-5
Unit 3-5
Introduction to VB.NET
Important Questions:
01) What is VB.NET? [2 marks]
VB.NET is a simple, multi-paradigm object-oriented programming language
designed to create a wide range of Windows, Web, and mobile applications built on the
.NET Framework.
It is not a case sensitive language like C, C++, Java or C#.
Everything in the VB.NET language is an object, including:
❖ All primitive data types (Integer, String, char, long, short, Boolean, etc.)
❖ User-defined data types, events, and all objects that inherit from its base class.
If Else Statement:
In Visual Basic, If Else statement or condition has an optional Else statements, the Else
statements will be executed whenever the If condition fails to execute. If Else statement,
whenever the boolean expression returns true, the If statements will be executed;
otherwise, the Else block of statements will be executed.
Syntax:
If boolean_expression Then
// Statements to Execute if boolean expression is True Else
// Statements to Execute if boolean expression is False End If
Example:
Dim x As Integer = 20
If x >= 10 Then
Console.WriteLine("x is Greater then10")
Else
Console.WriteLine("x is less than 10")
End If
If-Else-If Statement:
In Visual Basic, the If-Else-If statement or condition is useful for defining the multiple
conditions and executing only the matched condition based on our requirements. If we
have multiple conditions to validate and execute only one block of code, then the IfElse-If
statement is useful in our application.
Syntax:
If condition_1 Then
// Statements to Execute if condition_1 is True
ElseIf condition_2 Then
// Statements to Execute if condition_2 is True
....
Else
// Statements to Execute if all conditions are False
End If
Example:
Dim x As Integer = 5
If x = 10 Then
Console.WriteLine("x value equals to 10")
ElseIf x > 10 Then
Console.WriteLine("x value greater than 10")
Else
Console.WriteLine("x value less than 10")
End If
Syntax:
If condition Then
If nested_condition_1 Then
// Statements to Execute
Else
// Statements to Execute
End If
Else
If nested_condition_2 Then
// Statements to Execute Else
// Statements to Execute
End If
End If
Example:
Module Module1
Sub Main()
Dim x As Integer = 5, y As Integer = 20
If x > y Then
If x >= 10 Then
Console.WriteLine("x value greater than or equal to 10")
Else
Console.WriteLine("x value less than 10")
End If
Else
If y <= 20 Then
Console.WriteLine("y value less than or equal to 20")
Else
Console.WriteLine("y value greater than 20")
End If
End If
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
Example:-
Module Module1
Sub Main()
Dim x As Integer = 20
Select Case x
Case 10
Console.WriteLine("x value is 10")
Case 15
Console.WriteLine("x value is 15")
Case 20
Console.WriteLine("x value is 20"
Case Else
Console.WriteLine("Not Known")
End Select
Console.WriteLine("Press Enter Key to Exit..") Console.ReadLine()
End Sub
End Module
___________________________________________________________________________
05. Explain Arrays in VB.NET [5marks]
Ans: - Visual Basic Arrays: Arrays are useful to store multiple elements of the same data
type at contiguous memory locations and arrays will allow us to store the fixed number of
elements sequentially based on the predefined number of items.
Arrays Declaration: Arrays can be declared by specifying the type of elements followed by
the brackets () like as shown below−
Syntax: Dim array_name As [Data_Type]();
Example:
' Store only int values
Dim numbers As Integer()
You can also create and initialize an array, as shown –
Example: ' Declaring and Initializing an array with size of 5
Dim array As Integer() = New Integer(4) {}
' Defining and assigning an element at the same time
Dim array2 As Integer() = New Integer(4) {1, 2, 3, 4, 5}
Multidimensional Arrays:
In visual basic, a multidimensional array is an array that contains more than one dimension
to represent the elements in a tabular format like rows and columns.
Multidimensional arrays can support either two or three-dimensional series. To create
multi-dimensional arrays, we need to use comma (,) separator inside of the brackets.
To create a 2D & 3D array, add each array within its own set of curly braces, and insert a
comma (,) inside the square brackets.
Syntax: ' Two-Dimensional Array
Dim arr As Integer(,) = New Integer(3, 1) {}
' Three-Dimensional Array
Dim arr1 As Integer(,,) = New Integer(3, 1, 2) {}
Multi-Dimensional Array Initialization:
In visual basic, we can initialize arrays upon declaration. Following are the different ways of
declaring and initializing the multidimensional arrays in visual basic programming language.
Examples, we declared and initialized two-dimensional array with 3 rows and 2 columns
and three-dimensional array with 2, 2, 3 dimensions.
Syntax: ' Two Dimensional Array
Dim intarr As Integer(,) = New Integer(2, 1) {{4, 5}, {5, 0}, {3, 1}}
' Three-Dimensional Array
Dim array3D As Integer(,,) = New Integer(1, 1, 2) {{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}}
Jagged Arrays:
In visual basic, Jagged Array is an array whose elements are arrays with different
dimensions and sizes. Sometimes the a jagged array called as “array of arrays” and it can
store arrays instead of a particular data type value.
The jagged array can be initialized with two brackets ()(). The first bracket will specify the
size of an array and the second one will specify the dimension of an array which is going to
be stored as value.
Syntax: ' Jagged Array with Single Dimensional Array
Dim jarray As Integer()() = New Integer(1)() {}
' Jagged Array with Two-Dimensional Array
Dim jarray1 As Integer()(,) = New Integer(2)(,) {}
Jagged Array Initialization:
The following are the different ways of declaring and initializing the jagged arrays in a visual
basic programming language.
In jagged arrays the size of elements is optional. So, for some elements we didn’t mention
the size to store single or multidimensional arrays with different sizes based on our
requirements.
Syntax: ' Jagged Array with Single Dimensional Array
Dim jarray As Integer()() = New Integer(2)() {}
jarray(0) = New Integer(4) {1, 2, 3, 4, 5}
jarray(1) = New Integer(2) {10, 20, 30}
jarray(2) = New Integer() {12, 50, 60, 70, 32}
___________________________________________________________________________
06.Explain different access modifiers in VB.Net. [5 marks]
Access Modifiers:
In visual basic, Access Modifiers are the keywords and those are useful to define an
accessibility level for all the types and type members.
By specifying the access level for all the types and type members, we can control whether
they can be accessed in other classes or in current assembly or in other assemblies based
on our requirements.
The following are the different types of access modifiers available in a visual basic:
• Public
• Private
• Protected
• Friend(internal in C#)
Class user
Public Name As String
Public Location As String
Public Sub GetUserDetails()
Console.WriteLine("Name: {0}", Name)
Console.WriteLine("Location: {0}", Location)
End Class
By using these four access modifiers, we can specify a following six levels of accessibility for
all types and type members based on our requirements.
__________________________________________________________________________
07.Explain visual basics delegates with Example. [2 marks]
Ans: - In visual basic, the delegate is a type that defines a method signature and it is useful
to hold the reference of one or more methods that is having the same signatures.
By using delegates, we can invoke the methods and send methods as an argument to other
methods.
In visual basic, the delegate is a reference type and it’s type-safe and secure. The delegates
are similar to function pointers in C++.
Syntax:
<access_modifier>Delegate<return_type><delegate_name>(<parameters>)
Example:
Public Delegate Sub UserDetails(ByVal name As String);
__________________________________________________________________________
Exit Statement:
In visual basic, the Exit statement is useful to terminate the execution of loops (for, while,
do-while, etc.) and transfers the control immediately to the next statements that follow a
terminated loops or statements.
➢ Following is the Syntax of defining the Exit statement in a visual basic programming
language. Exit {Do | For | Function | Property | Select | Sub | Try | While}.
❖ Example of terminating the execution of for loop with Exit statement
Sub Main()
For i As Integer = 1 To 4
If i = 3 Then Exit For
Console.WriteLine("i value: {0}", i)
Next
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
Continue Statement:
In visual basic, the Continue statement is useful to transfer the control immediately to the
next iteration of loops such as For, While, Do-While from the specified position by skipping
the remaining code.
➢ The main difference between the Exit statement and Continue statement is, the Exit
statement will completely terminate the loop or statement execution but the Continue
statement will transfer the control immediately to the next iteration of the loop
➢ Following is the Syntax of defining the Continue statement in the visual basic
programming language.
Continue {Do | For | While} For i As Integer = 1 To 4
If i = 3 Then Continue For
Console.WriteLine("i value: {0}", i)
Next
GoTo Statement:
In visual basic, the GoTo statement is useful to transfer the program control to the
specified labelled statement. It is useful to get out of the loop or exit from deeply nested
loops based on our requirements.
➢ We can also define the multiple GoTo statements in our application to transfer the
program control to the specified labelled statement.
➢ Syntax: GoTo labelled_statement;
For i As Integer = 1 To 10 - 1
If i = 5 Then GoTo endloop
End If
Console.WriteLine("i value: {0}", i)
Next
endloop: Console.WriteLine("The end")
Return Statement:
In visual basic, the Return statement is useful to terminate the execution of the method in
which it appears and return the control back to the calling method.
➢ The Return statement is useful whenever we want to value the other methods. We can
also omit the usage of return statement in our methods by using void as a return type.
➢ Syntax:
Return return_val;
Example: Public Function SumofN(ByVal a As Integer, ByVal b As Integer) As Integer
Dim x As Integer = a + b
Return x
End Function
String Methods:
In visual basic, the string class contains various methods to manipulate the string objects
data based on our requirements.
➢ String Split Method: Is useful to split a string into substrings based on the characters in
an array.
❖ Syntax: Public Function Split(ByVal separator As Char()) As String()
➢ String Concat method: is useful to concatenate or append one string to the end of
another string and return a new string.
❖ Syntax: Public Function Concat(ByVal string1 As String, ByVal string2 As String) As String
➢ String Replace method: is useful to replace the specified string or a character in all
occurrences of a given string. ❖ Syntax: Dim x As String = "aaaaa“
Dim nx As String = x.Replace("a", "b").Replace("b", "c")
➢ String Compare method: is useful to compare two specified strings and return an integer
value that indicates their relative position in the sort order.
❖ Syntax: Public Function Compare(ByVal string1 As String, ByVal string2 As String) As
Integer
➢ String Format method: is useful to insert the value of variable or an object or expression
into another string.
❖ Syntax: Public Function Format(ByVal _ As String, ByVal _ As Object) As String
➢ String Copy method: is useful to create a new instance of string object with the same
content of the specified string object.
❖ Syntax: Public Shared Function Copy(ByVal str As String) As String
__________________________________________________________________________
Method Overriding:
Method Overriding means override a base class method in the derived class by creating a
method with the same name and signatures to perform a different task.
➢ The Method Overriding in visual basic can be achieved by using Overridable & Overrides
keywords along with the inheritance principle...
➢ Method Overriding is also called as run time polymorphism or late binding.
➢ Example
' Base Class
Public Class Users
Public Overridable Sub GetInfo()
Console.WriteLine("Base Class")
End Sub
End Class
'Derived Class
Public Class Details
Inherits Users
Public Overrides Sub GetInfo()
Console.WriteLine("Derived Class")
End Sub
End Class
__________________________________________________________________________
11. What is exception Handling. Explain different types of exception classes.
In visual basic, the Exception class further classified into two other classes called
SystemException and ApplicationException to handle the exceptions.
➢ In visual basic, the Exception class further classified into two other classes called:
❖ SystemException
❖ ApplicationException
__________________________________________________________________________
For- Loops: In Visual Basic, For loop is useful to execute a statement or a group of
statements repeatedly until the defined condition returns true.
➢ For loop is useful in Visual Basic applications to iterate and execute a certain block of
statements repeatedly until the specified number of times.
➢ Syntax : For variable As [Data Type] = start To end
// Statements to Execute
Next
➢ Example: Module Module1
Sub Main()
For i As Integer = 1 To 4
Console.WriteLine("i value: {0}", i)
Next
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
Nested For Loop: In visual basic, we can create one For loop within another For loop
based on our requirements.
➢ Following is the example of creating a nested For loop in Visual Basic.
➢ Example:
Module Module1
Sub Main()
For i As Integer = 1 To 4
For j As Integer = i To 3 - 1
Console.WriteLine("i value: {0}, j value: {1}", i, j)
Next
Next
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
While Loop: In Visual Basic, While loop is useful to execute the block of statements as long
as the specified condition is true.
➢ In case we are unknown about the number of times to execute the block of
statements, then While loop is the best solution.
➢ Syntax : While boolean_expression
// Statements to Execute
End While
➢ Example:
Module Module1
Sub Main()
Dim i As Integer = 1
While i <= 4
Console.WriteLine("i value: {0}", i)
i += 1
End While
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
While Loop with Exit Statement: In Visual Basic, we can exit or terminate the execution of
While loop immediately by using Exit keyword.
➢ Following is the example of using Exit keyword in While loop to terminate the
execution of loop in Visual Basic programming language.
➢ Syntax : While boolean_expression
// Statements to Execute
If <cond> Then Exit While
End While
➢ Example:
Module Module1
Sub Main()
Dim i As Integer = 1
While i < 4
Console.WriteLine("i value: {0}", i)
i += 1
If i = 2 Then Exit While
End While
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
Do While Loop: In Visual Basic, the do-while loop is same as the while loop, but the only
difference is while loop will execute the statements only when the defined condition
returns true.
➢ The do-while loop will execute the statements at least once because first it will
execute the block of statements and then it will checks the condition.
➢ In Visual Basic, we can exit or terminate the execution of the Do-While loop
immediately by using Exit keyword also.
➢ Syntax : Do
// Statements to Execute
Loop While boolean_expression
Example: Sub Main()
Dim i As Integer = 1
Do
Console.WriteLine("i value: {0}", i)
i += 1
Loop While i <= 4
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
For Each Loop: In Visual Basic, For Each loop is useful to loop through items in an array or
collection object to repeatedly execute the block of statements.
➢ In Visual Basic For Each loop will work with the collection objects such as an array,
list, etc., to execute the block of statements for each element in the array or
collection.
➢ In Visual Basic, we can use Exit, Continue statements within For Each loop to exit or
continue to the next iteration of the loop based on our requirements.
➢ Syntax : For Each var_name As [Data_Type] In Collection_Object
// Statements to Execute
Next
➢ Example: Dim names As String() = New String(2) {
«Prajwal", «Sunny", «Shailu"}
For Each name As String In names
Console.WriteLine(name)
Next
_____________________________________________________________________
Unit-05
1.Explain about Datareader with an example.
➢ A data reader provides an easy way for the programmer to read data from a
database.
➢ The data reader is also called firehose a cursor or forward read-only cursor because
it moves forward through the data.
➢ The DataReader class represents a data reader in ADO.NET.
➢ For example, use the following line of code:
SqlCommand cmd = new SqlCommand(SQL, conn);
// Call ExecuteReader to return a DataReader
SqlDataReader reader = cmd.ExecuteReader();
Once you're done with the data reader, call the Close method to close a data reader:
reader.Close();
_____________________________________________________________________
2.What is a connection string?
➢ Connection String is a normal String representation which contains Database
connection information to establish the connection between Database and the
Application.
➢ The Connection String includes parameters such as the name of the driver, Server
name and Database name , as well as security information such as user name and
password.
➢ Example: connectionString="Data Source=ServerName;Initial
Catalog=Databasename; User ID=UserName;Password=Password".
_____________________________________________________________________
EXAMPLE:-
using System.Data.SqlClient;
using Microsoft.VisualBasic;
Declarations:
SqlConnection con;
SqlDataAdapter da;
SqlCommandBuilder cb;
DataSet ds;
int rno = 0;
Under Form Load:
con = new SqlConnection("User Id=sa;Password=123;Database=mydb");
da = new SqlDataAdapter("Select Empno,Ename,Job,Sal from Emp", con);
ds = new DataSet();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds, "Emp");
ShowData();
private void ShowData()
{
textBox1.Text = ds.Tables[0].Rows[rno][0].ToString();
textBox2.Text = ds.Tables[0].Rows[rno][1].ToString();
textBox3.Text = ds.Tables[0].Rows[rno][2].ToString();
textBox4.Text = ds.Tables[0].Rows[rno][3].ToString();
}
//Updating an existing record of DataTable: To Update an existing record of data table re-assigns
modified values back to the row under data table, so that old values get changed to new.
//Deleting an existing record of DataTable: To delete a record under data table call delete method
on DataRowCollection pointing to the row that has to be deleted.