0% found this document useful (0 votes)
17 views41 pages

Notes

The document provides comprehensive notes on VB.NET, a high-level, object-oriented programming language developed by Microsoft, detailing its features, applications, and the .NET framework. It covers various components of Visual Studio, types of applications in VB.NET, and programming constructs such as decision-making and looping. Additionally, it explains the structure of Integrated Development Environments (IDEs) and includes examples of code for better understanding.

Uploaded by

Vêrmâ Sujâl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views41 pages

Notes

The document provides comprehensive notes on VB.NET, a high-level, object-oriented programming language developed by Microsoft, detailing its features, applications, and the .NET framework. It covers various components of Visual Studio, types of applications in VB.NET, and programming constructs such as decision-making and looping. Additionally, it explains the structure of Integrated Development Environments (IDEs) and includes examples of code for better understanding.

Uploaded by

Vêrmâ Sujâl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

MCA Sem V.

SXC Ranchi.

VB.Net notes:1.
-------------------------------------------------------------------------------------------------------------------------------

VB.NET
 It is a simple, high-level, object-oriented programming language developed by Microsoft
in 2002.
 It is a successor of Visual Basic 6.0, that is implemented on the Microsoft . NET
framework.
 It supports the OOPs concept, such as abstraction, encapsulation, inheritance, and
polymorphism.

 It is a Modern, general purpose.


 It is Object oriented.
 It is Component oriented.
 It is Easy to learn.
 It is a Structured language.
 It produces efficient programs.
 It can be compiled on a variety of computer platforms.
 Part of .Net Framework.
 Microsoft's integrated development environment (IDE) for developing in Visual Basic
is Visual Studio.
 Except all the other commericial editions of VS are Visual Studio Express and Visual Studio
Community, which are freeware.
 Everything in VB.NET is an object, including all of the primitive types (Short, Integer,
Long, String, Boolean, etc.) and user-defined types, events, and even assemblies. All
objects inherits from the base class Object.

 It's also possible to run VB.NET programs on Mono, the open-source alternative
to .NET, not only under Windows, but even Linux or Mac OSX.

1.
MCA Sem V.
SXC Ranchi.

Versions of .NET:

 .NET Framework from 1. To 4.8



o By late 2001 the first beta versions of .NET 1.0 framework were released.
o The first version of .NET Framework was released on 13 February 2002,
bringing managed code to Windows NT 4.0, 98, 2000, ME and XP.

 VS versions from 2002 to 2022.

NET Framework.
Software developers use . NET Framework to build many different types of applications—
websites, services, desktop apps, and more with Visual Studio.

The .Net framework consists of developer tools, programming languages, and libraries to build
desktop and web applications. It is also used to build websites, web services, and games.

Framework Main components:

 Common Language Runtime


 Class Library
 Languages

Net Framework Design Principle

 Interoperability
 Portability
 Security
 Memory management
 Simplified deployment

VS

 Visual Studio, also known as Microsoft Visual Studio and VS, is an integrated
development environment for Microsoft Windows.
 It is a tool for writing computer programs, websites, web apps, and web services.
 It includes
 a code editor
 debugger
 GUI design tool
 database schema designer

2.
MCA Sem V.
SXC Ranchi.

 and supports most major revision control systems.

*It is not backwards-compatible with VB6, and any code written in the old
version does not compile under VB.NET.
Types of application in VB.net

 Console applications.
 Windows forms applications.
 Web forms
 Class library.
 Windows control library.
 Windows services.
 Net website.
 Net web services.

Definition:
Console Applications allow us to write data to the console read data from the console,
and run in within a DOS Shell. They do not support Windows GUI's. Console Applications are
supported by the System.

Definition:
Windows Forms is a set of managed libraries in . NET Framework designed to develop rich
client applications. It is a graphical API to display data and manage user interactions with easier
deployment and better security in client applications.

Definition:
ASP.NET Web Forms is a web application framework and one of several programming models
supported by the Microsoft ASP.NET technology. Web Forms applications can be written in
any programming language which supports the Common Language Runtime, such
as C# or Visual Basic.

Definition:Web Forms was included in the original .NET Framework 1.0 release in 2002 as the
first programming model available in ASP.NET

* Unlike newer ASP.NET components, Web Forms is not supported by ASP.NET Core.

Definition:
NET Framework Class Library is the collection of classes, namespaces, interfaces
and value types that are used for . NET applications. It contains thousands of classes
that supports the following functions. Base and user-defined data types. Support for
exceptions handling.

3.
MCA Sem V.
SXC Ranchi.

IDE
(IDE), also known as integrated design environment and integrated debugging environment, is a
type of computer software that assists computer programmers to develop software.

facilitates application development

In the case of Visual Basic . NET, that IDE is Visual Studio.

4.
MCA Sem V.
SXC Ranchi.

NET Framework version

1.0 Visual Studio .NET Contained the first version of the CLR & base class libraries
1.1 Visual Studio .NET 2003
2.0 Visual Studio 2005
3.0 Visual Studio 2005
3.5 Visual Studio 2008
4 Visual Studio 2010
4.5 Visual Studio 2012
4.5.1 Visual Studio 2013
4.6.1 Visual Studio 2015
4.7.2 Visual Studio 2017
4.8 Visual Studio 2019
4.8 Visual Studio 2022

Visual Studio IDE Components

 Visual Studio has a code editor with IntelliSense as well as code


refactoring.
 The integrated debugger works not only as a source-level debugger but
also as a machine-level debugger.
 Forms designer provided in visual studio is used for building GUI
applications.
 Web designer
 Class designer
 Database schema designer.
 Toolbar.
 Menu bar.
 Project explorer.
 Properties window.
 Form layout window.
 Object designer.
 Form designer.
 Toolbox.
VB.NET features:-
VB.NET features are as follows

1- GUI interface:- VB.NET is a graphical user interface (GUI) language. This means that
users can interact and interact with the screen.

5.
MCA Sem V.
SXC Ranchi.

2- Object-oriented:- object-oriented is a programming language. That is, it supports the


concept of class and object and it supports other features of OOPS.

3- Auto-complete:- The code editor of vb.net provides the facility of auto-complete. By


which whenever the programmer writes the code, it is automatically completed which saves
the time of the programmer.

4- Windows form designer:- VB.net has windows form designer. By which the form can
be designed.

5- IDE (integrated development environment):- It is a software application that allows


developers to develop, run, test and debug the software.

6:- Assembly:-.DLI or.EXE file is an assembly that creates part of an application.

7:- Namespaces:- The namespace that is there organizes the objects present in the
assembly. An assembly can have more than one namespace.

8:- Attributes:- attributes which are tags are those which provide additional information
about the elements.

The attributes are most commonly used to explain the COM property of classes, interface,
and methods, to explain assemblies, and to specify the security of methods.

9- Inheritance:- Through inheritance, we can create such a class as derived from the base
class.
The advantage of inheritance is that we have to design only one bar in the class.

10- Multithreading:- Through multithreading, the application can handle many abstract
tasks simultaneously.

11- VB.NET is a component-oriented language.

12- It can be learned easily.

13- It is a structured language.

VB.net Variable & variable declarations


VB.net variable

Variable means the name of the storage area that our program can use. VB.Net has a
specific type of all Variable, which determines the size and memory layout of Variable.

Following are some basic data types of VB.Net:

6.
MCA Sem V.
SXC Ranchi.

1. Data type example


2. Integral types
3. Floating-point types
4. Decimal types
5. Boolean types
6. Date types

Arrays in VB.net
o An array is a linear data structure that is a collection of data elements of the
same type stored on a contiguous memory location.
o Each data item is called an element of the array.
o It is a fixed size of sequentially arranged elements in computer memory with
the first element being at index 0 and the last element at index n -
1, where n represents the total number of elements in the array.

Dim intData(30) ' an array of 31 elements


Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array

Dim intData() As Integer = {1, 2, 3, 4, 5}


Dim intData(5) As Integer
Dim array_name() As String = {"Peter", "John", "Brock", "James", "Maria"}
Dim misc() as Object = {"Hello friends", 16c, 12ui, "A"c}
Dim Emp(0 to 2) As String
Emp{0} = "Mathew"
Emp(1) = " Anthony"
Emp(2) = "Prince"

What is IDE ? and its components


IDE [Integrated Development Environment]
The full name of IDE is an integrated development environment. It is a software application
that allows developers to develop, run, test and debug software.

Generally, IDE consists of a code editor, a compiler, or an integrator and a debugger.

IDE has more features such as through this we can store the code online, format the code
and optimize the code and it has a lot of plugins and extensions which is very helpful in
creating a rich application.

The IDE's toolbar looks like a word processor. This is called IDE because we can access
the necessary tools to develop the software application.
IDE components
7.
MCA Sem V.
SXC Ranchi.

The components of the IDE are as follows: -

1- IDE project window


We call the window title project-project1 as project explorer and it contains the project file.
We usually call the project explorer window.

2- Toolbar
It provides quick access to most commonly used commands while programming, that is, we
can quickly access such commands which are used most often.

We can perform a task related to it by clicking a button in the toolbar. We can change the
settings of the toolbar from the View menu.

3- Form designer:- For a software application, form objects are like building blocks. This is
the window from which the user interacts at the beginning of the application. Forms have
their own properties, events, and methods that we can control. The form window is a
window where we draw our application.

4- Toolbox (toolbox):- The toolbox is a very large box with many different icons in it. This
is the selection menu for controls. These controls are used to customize forms.
Some of its controls are as follows:-

PictureBox - This control displays the image.


label- This control displays uneditable text to the user. the uneditable text means text
that cannot be edited.
textBox - This control is to accept user input.
commandButton - This displays the control button.
Listbox - It provides a list of control items
comboBox - This control provides a shortlist of items.

5- Property window
The property window which displays properties for forms or controls is properties attributes
like size, position, etc.

Like form, control also has its own unique properties. Some properties like width and height
are similar in both, but apart from this other properties are different.

6- Menu bar:- menu bar displays the commands that are required to create applications. It
is a horizontal strip that appears on top of the screen and it contains the names of menus.
o file- It contains options to open, close, print, etc. of the project.
o edit- It contains the options of cut, paste, undo, delete, find, etc.

8.
MCA Sem V.
SXC Ranchi.

o view- This IDE displays the options to display Windows and toolbar.
o project- It displays the options to add features to the project.
o format- It contains the options to align and lock the control of the form.
o debug - This includes debugging options.
o run- It contains options to execute, stop the program.
o diagram- It contains options to edit and view the design of the database.
o tools– It contains options for IDE tools.
o Add-ins- It contains the options to use, install, remove add-ins.
o windows- It contains options to arrange and display the windows.
o help- It contains options for taking the help.

7- form layout window


IDE form layout window:- The form layout window shows where your form will be displayed
on the monitor screen.

Decision Making constructs in VB.net


Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.

If ... Then statement


If...Then...Else statement
nested If statements
Select Case statement
You can use one select case statement inside another select case statement(s).
Looping constructs in VB.net
It repeats a group of statements a specified number of times and a loop index counts the
number of loop iterations as the loop executes. It repeats a group of statements for each
element in a collection. This loop is used for accessing and manipulating all elements in an
array or a VB.Net collection.

Do Loop
Do While
For...Next
For Each...Next
While... End While
Nested loops

9.
MCA Sem V.
SXC Ranchi.

Do Loop example.
Imports System
Module Do_loop
Sub Main()
' Initializatio and Declaration of variable i
Dim i As Integer = 1
Do
' Executes the following Statement
Console.WriteLine(" Value of variable I is : {0}", i)
i = i + 1 'Increment the variable i by 1
Loop While i <= 10 ' Define the While Condition

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module

DO While loop example:


Imports System
Module Nest_Do_While
Sub Main()
' Declare i and j as Integer variable
Dim i As Integer = 1
Do
' Outer loop statement
Console.WriteLine(" Execution of Outer loop is {0}", i & " times")
Dim j As Integer = 1
Do
'Inner loop statement
Console.WriteLine(" Execution of Inner loop is {0}", j)
j = j + 1 ' Increment Inner Counter variable by 1
Loop While j < 3
Console.WriteLine()
i = i + 1 ' Increment Outer Counter variable by 1
Loop While i < 4
Console.WriteLine(" Exit from the loop")
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module

For Next Loop Example.


Imports System

10.
MCA Sem V.
SXC Ranchi.

Module Number
Sub Main()
For i As Integer = 1 To 10 Step 1
Console.WriteLine(" Number is {0} ", i)
' after completion of each iteration, next will update the variable co
unter
Next
Console.WriteLine(" Press any key to exit... ")
Console.ReadKey()
End Sub
End Module

For Each loop example


Imports System
Module For_Each_loop
Sub Main()
Dim An_array() As Integer = {1, 2, 3, 4, 5}
Dim i As Integer 'Declare i as Integer
For Each i In An_array
Console.WriteLine(" Value of i is {0}", i)
Next
Console.WriteLine("Press any key to exit...")
Console.ReadLine()
End Sub
End Module

You can use one or more loops inside any another While, For or Do loop.
Exit Statement
In VB.NET, the Exit statement is used to terminate the loop (for, while, do, select case, etc.) or
exit the loop and pass control immediately to the next statement of the termination loop.
Furthermore, the Exit statement can also be used in the nested loop to stop or terminate the
execution of the inner or outer loop at any time, depending on our requirements.

Continue Statement
In VB.NET, the continue statement is used to skip the particular iteration of the loop and
continue with the next iteration.
Generally, the continue Statement is written inside the body of the For, While and Do While loop
with a condition.

Object orientation in vb.net


VB.NET is completely object oriented. This article uncovers some basic Object Oriented
Programming features of Visual Basic.

11.
MCA Sem V.
SXC Ranchi.

OOP is a philosophy and a way of thinking, designing and implementing solutions that focuses
on reusability. This approach is inspired by the industrial revolution - the invention of basic
components. For example, when we build our house, we don't burn our own bricks and forge
nails, we order them.

Attributes

Object attributes are properties or data that it stores, e.g. the human's name and age.
For the database object it could be the password or whatever the objects requires to
work.

Attributes are just like ordinary variables with which we've worked a hundred times.
Sometimes they're called the "object's internal state"

Methods

Methods are abilities that the object can perform. Human, for example, could have the methods
GoToWork(), Greet() or Blink().
Class

o We have already encountered the term "class".A class is a pattern that we use
to create objects. It defines their properties and abilities.

o An object created according to a class is called an instance.

o Each object in Visual Basic is defined by a class.

o A class describes the variables, properties, procedures, and events of an


object.

Objects

o Objects are instances of classes; you can create as many objects you need once
you have defined a class. ... The class is used to create objects.

o An object is a combination of code and data that can be treated as a unit.

o An object can be a piece of an application, like a control or a form.

o An entire application can also be an object

o When we create an application in Visual Basic, we constantly work with objects.

12.
MCA Sem V.
SXC Ranchi.

Interface

o In visual basic, Interface is same as a class but the only difference is class can
contain both declarations and implementation of methods, properties, and events
but Interface will contain only the declarations of methods, properties, and events
that a class or structure can implement.

Inheritance

o is the idea that one class, called a subclass, can be based on another class,
called a base class. Inheritance provides a mechanism for creating hierarchies of
objects.

o For example, a dog is a mammal and a collie is a dog.

Abstraction

o in Visual Basic.NET. Abstraction is the ability to generalize an object as a data


type that has a specific set of characteristics and is able to perform a set of
actions.

Encapsulation

o is the exposure of properties and methods of an object while hiding the actual
implementation from the outside world. In other words, the object is treated as a
black box—developers who use the object should have no need to understand
how it actually works.

Polymorphism

o is the ability to define a method or property in a set of derived classes with


matching method signatures but provide different implementations and then
distinguish the objects' matching interface from one another at runtime when you
call the method on the base class.

o Class Programming example in VB.NET

Module My_program
Sub Main()
Dim rect As Rectangle = New Rectangle() 'create an object
Dim rect2 As Rectangle = New Rectangle() 'create an object
Dim area, para As Integer
rect.setLength = (5)

13.
MCA Sem V.
SXC Ranchi.

rect.setBreadth= (6)

rect2.setLength = (5)
rect2.setBreadth = (10)

area = rect.length * rect.Breadth


'area = rect.GetArea()
Console.WriteLine(" Area of Rectangle is {0}", area)

'para = rect.GetParameter()
para = 2 (rect2.length + rect.Breadth)
Console.WriteLine(" Parameter of Rectangle is {0}", para)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()

End Sub
Public Class Rectangle
Public length As Integer
Public Breadth As Integer

Public Sub setLength(ByVal len As Integer)


length = len
End Sub

Public Sub setBreadth(ByVal bre As Integer)


Breadth = bre
End Sub
Public Function GetArea() As Integer
Return length * Breadth
End Function

Public Function GetParameter() As Integer


Return 2 * (length + Breadth)
End Function
End Class
End Module

Term used in Class level programming.

Access_Specifier: It defines the access levels of the class, such as Public,


Private or Friend, Protected, Protected Friend, etc. to use the method. (It is
an optional parameter).
MustInherit: It is an optional parameter that specifies that the class can
only be used as a base class, and the object will not directly access the base
class or the abstract class.
NotInheritable: It is also an optional parameter that representing the class
not being used as a base class.

14.
MCA Sem V.
SXC Ranchi.

Partial: As the name defines, a Partial represents the partial definition of the
class (optional).
Implements: It is used to specify interfaces from which the class inherits
(optional).
Public Class Bird
Public Sub Chirp()
Console.WriteLine("♫ ♫ ♫")
End Sub
Public Sub Peck()
Console.WriteLine("Peck, peck!")
End Sub
End Class

Public Interface IBird


Sub Chirp()
Sub Breathe()
End Interface

After the Interface is declared


This class code can be written as

Public Class Bird


Implements IBird
Public Sub Chirp() Implements IBird.Chirp
Console.WriteLine("♫ ♫ ♫")
End Sub
Public Sub Breathe() Implements IBird.Breathe
Console.WriteLine("Breathing...")
End Sub
Public Sub Peck()
Console.WriteLine("Peck, peck!")
End Sub
End Class

Exception Handling

An exception is a problem that arises during the execution of a program. An exception


is a response to an exceptional circumstance that arises while a program is running,
such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another.
VB.Net exception handling is built upon four keywords –
Unstructured Error Handling

15.
MCA Sem V.
SXC Ranchi.

Unstructured exception handling involves the use of the On Error statement. When an
exception is raised in a program, control of the program moves to the argument
specified in the On Error statement. You use an On Error statement at the beginning of
a set of statements, such as a procedure. There are four forms of the On Error
statement:

o On Error GoTo <Line> statement

o On Error Resume Next statement

o On Error GoTo 0 statement

o On Error GoTo -1 statement The subsequent sections describe


each form of the On Error statement.

o On Error GoTo <Line> Statement

Structured Error Handling


VB.Net supports structured exception handling. In structured exception handing,
we write code surrounded by blocks. If an exception occurs, the block throws the
execution control to a predefined handled code, the try, catch, finally statements define
these blocks. ... The catch block defines the handlers for the exception.]
Try, Catch, Finally and Throw.
 Try − A Try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more Catch blocks.
 Catch − A program catches an exception with an exception handler at the place
in a program where you want to handle the problem. The Catch keyword
indicates the catching of an exception.
 Finally − The Finally block is used to execute a given set of statements, whether
an exception is thrown or not thrown. For example, if you open a file, it must be
closed whether an exception is raised or not.
 Throw − A program throws an exception when a problem shows up. This is
done using a Throw keyword.
The following are the two exception classes used primarily in
VB.NET.
1. System.SystemException
2. System.ApplicationException

Exception Class Description


System.IO.IOException Handles I/O erro

System.IndexOutOfRangeException

16.
MCA Sem V.
SXC Ranchi.

Handles errors generated when a method refers to an array index out of range.

System.ArrayTypeMismatchException
Handles errors generated when type is mismatched with the array type.

System.NullReferenceException
Handles errors generated from deferencing a null object.

System.DivideByZeroException
Handles errors generated from dividing a dividend with zero.

System.InvalidCastException
Handles errors generated during typecasting.

System.OutOfMemoryException
Handles errors generated from insufficient free memory.

System.StackOverflowException
Handles errors generated from stack overflow.
Examples:

Examples UnStructured Error Handling


Module Module1
Sub Main()
On Error GoTo Handler
Dim intItem1 As Integer = 0
Dim intItem2 As Integer = 128
Dim intResult As Integer
intResult = intItem2 / intItem1
Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
Exit Sub
Handler:

End Sub
End Module

Examples Structured Error Handling


Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException

17.
MCA Sem V.
SXC Ranchi.

Console.WriteLine("Exception caught: {0}", e)


Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module

Example of User Defined Exception Handling


Module exceptionProg
Public Class TempIsZeroException : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Public Class Temperature
Dim temperature As Integer = 0
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If
End Sub
End Class
Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
End Module

Dialog Boxex in VB.net

18.
MCA Sem V.
SXC Ranchi.

1. Color Dialog Box: It is used to display the color dialog box that allows
the user to select a color from the predefined colors or specify the
custom colors.
2. Font DialogBox: It is used to create a Font dialog box that allows the
user to select the font, font size, color, and style to be applied to the
current text selection.
3. OpenFile Dialog Box: It is used to create a prompt box that allows the
users to select a file to open and allows the selection of multiple files.
4. Print Dialog Box: It is used to create a print dialog box that allows the
user to print documents by selecting the printer and setting of the
page printed through the Windows application.

Color Dialog class code example.


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ColorDialog1.ShowDialog <>Windows.Forms.DialogResult.Cancel Then
Label1.ForeColor = ColorDialog1.Color
End If
End Sub

Font Dialog class code example


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FontDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
RichTextBox1.ForeColor = FontDialog1.Color
RichTextBox1.Font = FontDialog1.Font
End If
End Sub

Open file dialog class code example


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
End Sub

19.
MCA Sem V.
SXC Ranchi.

Save file dialog class


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK
Then
My.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName, RichTextBox1.Text,
True)
End If
End Sub

Some more programs:

Function Overloading

Allowed :
Public Overloads Function add(ByVal a As Integer, ByVal b As Integer)
Public Overloads Function add(ByVal a As Long, ByVal b As Long)
Not Allowed :
Public Overloads Function add(ByVal a As Integer, ByVal b As Integer)
Public Overloads Sub add(ByVal a As Long, ByVal b As Long)
Don't repeat same parameters with same data types in parameter, it will show an error

Imports System.Console
Module Module1
Public Class demo
Public Overloads Function add(ByVal a As Integer, ByVal b As Integer)
WriteLine("You are in function add(integer, integer)")
Return a + b
End Function
Public Overloads Function add(ByVal a As Long, ByVal b As Long)
WriteLine("You are in function add(long, long)")
Return a + b
End Function
End Class
Sub Main()
Dim obj As New demo
WriteLine(obj.add(2147483640, 4))
WriteLine(obj.add(2147483648, 1))
WriteLine("press return to exit...")
Read()
End Sub
End Module

20.
MCA Sem V.
SXC Ranchi.

MustInherit example.

Module Module1
MustInherit Class Sample1
Sub Fun1()
Console.WriteLine("Fun1() called")
End Sub
End Class

Class Sample2
Inherits Sample1
Sub Fun2()
Console.WriteLine("Fun2() called")
End Sub

End Class

Sub Main()

Dim S2 As New Sample2()


S2.Fun1()
S2.Fun2()
End Sub
End Module

MustOverride example

Module Module1
MustInherit Class Sample1
MustOverride Sub Fun()
End Class

Class Sample2
Inherits Sample1
'Here we need to override the Fun() method
'otherwise it will generate the error.
Overrides Sub Fun()
Console.WriteLine("Override method Fun() called")
End Sub
End Class

Sub Main()
Dim S As New Sample2()
S.Fun()
End Sub
End Module

Working with an interface

Module Module1

21.
MCA Sem V.
SXC Ranchi.

Interface IName
Sub GetName(ByVal x As String)
End Interface
Interface ILocation
Sub GetLocation(ByVal x As String)
End Interface
Interface IAge
Sub GetAge(ByVal x As Integer)
End Interface
Class User
Implements IName, ILocation, IAge
Public Sub GetName(ByVal a As String) Implements IName.GetName
Console.WriteLine("Name: {0}", a)
End Sub
Public Sub GetLocation(ByVal a As String) Implements ILocation.GetLocation
Console.WriteLine("Location: {0}", a)
End Sub
Public Sub GetAge(ByVal a As Integer) Implements IAge.GetAge
Console.WriteLine("Age: {0}", a)
End Sub
End Class
Sub Main(ByVal args As String())
Dim u As User = New User()
u.GetName("Suresh Dasari")
u.GetLocation("Hyderabad")
u.GetAge(32)
Console.WriteLine(vbLf & "Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module

22.
MCA Sem V.
SXC Ranchi.

Some String based functions


ASC
Dim Str as String
Str=“Latin”
Asc(Str)
LCASE
Dim Uppercase as String = “HELLO WORLD”
Dim Lowercase as String = LCase(Uppercase)
LEFT
Dim CheckStr as string = “Hey Jim”
Dim ResultStr as string = Left(CheckStr, 3) Dim StrWords as String = “You are a hero!”
LEN
Dim StrWords as String = “You are a hero!”
Dim WordCount as Integer = Len(StrWords)
RIGHT
Dim CheckStr as string = “Hey Jim”
Dim ResultStr as string = Right(CheckStr, 3)
SPLIT
Dim CheckStr as String = “How are you?”
Dim OutputStr as String = Split(CheckStr)
STRREVERSE
Dim CorrectStr as String = “Apple”
Dim ReverseString as String = StrReverse(CorrectStr)
UCASE
Dim LowercaseStr as String = “Hello Jim”
Dim UppercaseStr as String = UCase(LowercaseStr)

Some array Functions.

reversedArray = System.Array.Reverse(arrayName)

System.Array.Copy(sourceArray, destinationArray, count))

sourceArray.CopyTo(destinationArray, sourceStart)

filteredArray = Filter(source, match, include, compare)

System.Array.FindAll(array, match)

Dim arr() As Integer = {10, 20, 30, 40, 50}


'Reset item in the array from index 2 to 3 by 0.
Array.Clear(arr, 2, 2)

Console.WriteLine(" Length of dimension({0:d}) = {1:d}", j, anArray.GetLength(j))

23.
MCA Sem V.
SXC Ranchi.

VB.NET ADO.NET Tutorial


ADO.NET is a data access technology from Microsoft .Net Framework ,
which provides communication between relational and non-relational
systems through a common set of components . ADO.NET was built for
a disconnected architecture , so it enables truly disconnected data
access and data manipulation through its Dataset Object, which is
completely independent from the Data Source.

The two key components of ADO.NET are

Data Providers and

DataSet .

The .Net Framework includes mainly three Data Providers for ADO.NET. The
Microsoft SQL Server , OLEDB and ODBC are the main Data Providers in
the .Net Framework.

24.
MCA Sem V.
SXC Ranchi.

Applications communicate with a database, firstly, to retrieve the data stored


there and present it in a user-friendly way, and secondly, to update the
database by inserting, modifying and deleting data.

Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net


framework that is used by the .Net applications for retrieving, accessing and
updating data.

ADO.Net Object Model

ADO.Net object model is nothing but the structured process flow through
various components. The object model can be pictorially described as:

The data residing in a data store or database is retrieved through the data
provider. Various components of the data provider retrieve data for the
application and update data.

An application accesses data either through a dataset or a data reader.

 Datasets store data in a disconnected cache and the application retrieves


data from it.
 Data readers provide data to the application in a read-only and forward-
only mode.

25.
MCA Sem V.
SXC Ranchi.

Data Provider

A data provider is used for connecting to a database, executing commands


and retrieving data, storing it in a dataset, reading the retrieved data and
updating the database.

The data provider in ADO.Net consists of the following four objects:

S.N Objects & Description

Connection
1
This component is used to set up a connection with a data source.

Command
2 A command is a SQL statement or a stored procedure used to retrieve, insert, delete or modify data in a data
source.

DataReader
3
Data reader is used to retrieve data from a data source in a read-only and forward-only mode.

DataAdapter
This is integral to the working of ADO.Net since data is transferred to and from a database through a data
4
adapter. It retrieves data from a database into a dataset and updates the database. When changes are made
to the dataset, the changes in the database are actually done by the data adapter.

There are following different types of data providers included in ADO.Net

o The .Net Framework data provider for SQL Server - provides access to
Microsoft SQL Server.

o The .Net Framework data provider for OLE DB - provides access to data
sources exposed by using OLE DB.

o The .Net Framework data provider for ODBC - provides access to data
sources exposed by ODBC.

o The .Net Framework data provider for Oracle - provides access to


Oracle data source.

o The EntityClient provider - enables accessing data through Entity Data


Model (EDM) applications.

26.
MCA Sem V.
SXC Ranchi.

DataSet

DataSet is an in-memory representation of data. It is a disconnected, cached


set of records that are retrieved from a database. When a connection is
established with the database, the data adapter creates a dataset and stores
data in it. After the data is retrieved and stored in a dataset, the connection
with the database is closed. This is called the 'disconnected architecture'.
The dataset works as a virtual database containing tables, rows, and
columns.

The following diagram shows the dataset object model:

The DataSet class is present in the System.Data namespace. The following


table describes all the components of DataSet:

S.N Components & Description

DataTableCollection
1
It contains all the tables retrieved from the data source.

DataRelationCollection
2
It contains relationships and the links between tables in a data set.

27.
MCA Sem V.
SXC Ranchi.

ExtendedProperties
3
It contains additional information, like the SQL statement for retrieving data, time of retrieval, etc.

DataTable
4 It represents a table in the DataTableCollection of a dataset. It consists of the DataRow and DataColumn
objects. The DataTable objects are case-sensitive.

DataRelation
5 It represents a relationship in the DataRelationshipCollection of the dataset. It is used to relate two DataTable
objects to each other through the DataColumn objects.

DataRowCollection
6
It contains all the rows in a DataTable.

DataView
7
It represents a fixed customized view of a DataTable for sorting, filtering, searching, editing and navigation.

PrimaryKey
8
It represents the column that uniquely identifies a row in a DataTable.

DataRow
It represents a row in the DataTable. The DataRow object and its properties and methods are used to
9
retrieve, evaluate, insert, delete, and update values in the DataTable. The NewRow method is used to create
a new row and the Add method adds a row to the table.

DataColumnCollection
10
It represents all the columns in a DataTable.

DataColumn
11
It consists of the number of columns that comprise a DataTable.

Connecting to a Database

The .Net Framework provides two types of Connection classes:

o SqlConnection - designed for connecting to Microsoft SQL Server.

o OleDbConnection - designed for connecting to a wide range of


databases, like Microsoft Access and Oracle.

28.
MCA Sem V.
SXC Ranchi.

Example 1

We have a table stored in Microsoft SQL Server, named Customers, in a


database named testDB. Please consult 'SQL Server' tutorial for creating
databases and database tables in SQL Server.

Let us connect to this database. Take the following steps:

1. Select TOOLS -> Connect to Database

Select a server name and the database name in the Add Connection dialog
box.

29.
MCA Sem V.
SXC Ranchi.

Click on the Test Connection button to check if the connection succeeded.

Add a DataGridView on the form.

30.
MCA Sem V.
SXC Ranchi.

Click on the Choose Data Source combo box.

Click on the Add Project Data Source link.

This opens the Data Source Configuration Wizard.

Select Database as the data source type

31.
MCA Sem V.
SXC Ranchi.

Choose DataSet as the database model.

32.
MCA Sem V.
SXC Ranchi.

Choose the connection already set up.

Save the connection string.

33.
MCA Sem V.
SXC Ranchi.

Choose the database object, Customers table in our example, and click the
Finish button.

Select the Preview Data link to see the data in the Results grid:

34.
MCA Sem V.
SXC Ranchi.

When the application is run using Start button available at the Microsoft Visual Studio tool bar, it will show the
following window:

Example 2
In this example, let us access data in a DataGridView control using code. Take the following steps:

1. Add a DataGridView control and a button in the form.


2. Change the text of the button control to 'Fill'.
3. Double click the button control to add the required code for the Click event of the button, as shown below:

Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
'TODO: This line of code loads data into the 'TestDBDataSet.CUSTOMERS' table.
You can move, or remove it, as needed.
Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

35.
MCA Sem V.
SXC Ranchi.

Dim connection As SqlConnection = New sqlconnection()


connection.ConnectionString = "Data Source=KABIR-DESKTOP; _
Initial Catalog=testDB;Integrated Security=True"
connection.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter _
("select * from Customers", connection)
Dim ds As DataSet = New DataSet()
adp.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
End Sub
End Class

When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window:

Clicking the Fill button displays the table on the data grid view control:

36.
MCA Sem V.
SXC Ranchi.

Creating Table, Columns and Rows

We have discussed that the DataSet components like DataTable,


DataColumn and DataRow allow us to create tables, columns and rows,
respectively.

The following example demonstrates the concept:

Example 3
So far, we have used tables and databases already existing in our computer.
In this example, we will create a table, add columns, rows and data into it
and display the table using a DataGridView object.

Take the following steps:

o Add a DataGridView control and a button in the form.

o Change the text of the button control to 'Fill'.

o Add the following code in the code editor.

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

37.
MCA Sem V.
SXC Ranchi.

' Set the caption bar text of the form.


Me.Text = "tutorialspont.com"
End Sub
Private Function CreateDataSet() As DataSet
'creating a DataSet object for tables
Dim dataset As DataSet = New DataSet()
' creating the student table
Dim Students As DataTable = CreateStudentTable()
dataset.Tables.Add(Students)
Return dataset
End Function
Private Function CreateStudentTable() As DataTable
Dim Students As DataTable
Students = New DataTable("Student")
' adding columns
AddNewColumn(Students, "System.Int32", "StudentID")
AddNewColumn(Students, "System.String", "StudentName")
AddNewColumn(Students, "System.String", "StudentCity")
' adding rows
AddNewRow(Students, 1, "Zara Ali", "Kolkata")
AddNewRow(Students, 2, "Shreya Sharma", "Delhi")
AddNewRow(Students, 3, "Rini Mukherjee", "Hyderabad")
AddNewRow(Students, 4, "Sunil Dubey", "Bikaner")
AddNewRow(Students, 5, "Rajat Mishra", "Patna")
Return Students
End Function
Private Sub AddNewColumn(ByRef table As DataTable, _
ByVal columnType As String, ByVal columnName As String)
Dim column As DataColumn = _
table.Columns.Add(columnName, Type.GetType(columnType))
End Sub

'adding data into the table


Private Sub AddNewRow(ByRef table As DataTable, ByRef id As Integer,_
ByRef name As String, ByRef city As String)

38.
MCA Sem V.
SXC Ranchi.

Dim newrow As DataRow = table.NewRow()


newrow("StudentID") = id
newrow("StudentName") = name
newrow("StudentCity") = city
table.Rows.Add(newrow)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ds As New DataSet
ds = CreateDataSet()
DataGridView1.DataSource = ds.Tables("Student")
End Sub
End Class

When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar,

it will show the following


window:

Clicking the Fill button displays the table on the data grid view control:

39.
MCA Sem V.
SXC Ranchi.

40.
MCA Sem V.
SXC Ranchi.

41.

You might also like