DOT NET
DOT NET
DOT NET
NET
What is Microsoft .NET?
Microsoft .NET (pronounced “dot net”) is a software component that runs on the
Windows operating system. .NET provides tools and libraries that enable developers to
create Windows software much faster and easier. .NET benefits end-users by providing
applications of higher capability, quality and security. The .NET Framework must be
installed on a user’s PC to run .NET applications.
.NET technology provides the ability to quickly build, deploy, manage, and use
connected, security-enhanced solutions with Web services
What is VB.Net?
Visual Basic .NET (VB.NET), is an object-oriented computer programming language that
can be viewed as an evolution of the classic Visual Basic (VB), which is implemented on
the .NET Framework
It is the next generation of the visual Basic language.
It supports OOP concepts such as abstraction, inheritance, polymorphism, and
aggregation.
.NET Framework Architecture :-
A programming infrastructure created by Microsoft for building, deploying, and running
applications and services that use .NET technologies, such as desktop applications and
Web services
1) It is a platform for application developers.
2) It is tiered, modular, and hierarchal.
3) It is a service or platform for building, deploying and running applications.
4) It consists of 2 main parts: Common language runtime and class libraries.
The common language runtime is the bottom tier, the least abstracted.
The .NET Framework is partitioned into modules, each with its own distinct
responsibility.
The architectural layout of the .NET Framework is illustrated in following figure:
Page 1 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Page 2 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
3) Framework Class Library ( FCL ): It is also known as a base class library. The FCL is a
collection of over 7000 reusable classes, interfaces, and value types that enable .NET
applications to :
a) read and write files,
b) access databases,
c) process XML,
d) display a graphical user interface,
e) draw graphics,
f) use Web services, etc.
The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is
divided into Namespaces. Namespaces is a logical grouping of types for the purpose of
identification. Framework class library (FCL) provides the consistent base types that are
used across all .NET enabled languages. The Classes are accessed by namespaces, which
reside within Assemblies.
Other name of FCL is BCL – Base Class Library
4) Common Type System ( CTS )
1) CTS allows written in different programming to easily share to information.
2) A class written in C# should be equivalent to a class written in VB.NET.
3) Languages must agree on the meanings of these concepts before they can integrate
with one and other.
4) CLS forms a subset of Common type system this implies that all the rules that for
apply to Common type system apply to common language specification.
5) It defines rules that a programming language must follow to ensure that objects
written in different programming languages can interact which each other.
6) Common type system provide cross language integration.
The common type system supports two general categories of types:
a) Value Type
b) Reference Type
a) Value Type: Stores directly data on stack. In built data type. For ex. Dim a as integer.
b) Reference Type: Store a reference to the value’s memory address, and are allocated on
the heap. For ex: dim obj as new oledbconnection.
The Common Language Runtime (CLR) can load and execute the source code written in
any .Net language, only if the type is described in the Common Type System (CTS)
The CLS is a common platform that integrates code and components from multiple .NET
programming languages. In other words, a .NET application can be written in multiple
programming languages with no extra work by the developer (though converting code between
languages can be tricky).
Page 3 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
.NET includes new object-oriented programming languages such as C#, Visual Basic .NET, J# (a
Java clone) and Managed C++. These languages, plus other experimental languages like F#, all
compile to the Common Language Specification and can work together in the same application.
CLS includes basic Language features needed by almost all the application
It serves as a guide for Library Writers and Compiler Writer.
The Common Language Specification is a subset of the common type system (CTS).
The common language specification is also important to application to who are writing
codes that will be used by other developers.
CLS a series of basic rules that are required for language integration.
Page 4 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Figure: 2 shows what happens to your code from its inception in Visual Studio to
execution.
Page 5 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Just In Time (JIT) compilation preserves memory and save time during initialization of
application.
Just In Time (JIT) compilation is used to run at high speed, after an initial phase of slow
interpretation.
Just In Time Compiler (JIT) code generally offers far better performance than
interpreters.
There are three types of JIT:
1) Pre JIT
2) Econo JIT
3) Normal JIT
1) Pre JIT: It converts all the code in executable code in a single cycle and it is slow.
2) Econo JIT: It will convert the called executable code only. But it will convert code every
time when a code is called again.
3) Normal JIT: It will only convert the called code and will store in cache so that it will not
require converting code again. Normal JIT is fast.
.NET Languages
.Net languages are CLI computer programming languages that may also optionally use
the .NET Framework Base Class Library and which produce programs that execute
within the Microsoft .NET Framework. Microsoft provides several such languages,
including C#, F#, Visual Basic .NET, and Managed C++.
Generally .NET languages call into two main categories, TypeSafe Languages (such as
C#) and Dynamic Languages (Such as Python). Type Safe Languages are built on the
.NET Common Language Runtime and Dynamic Languages are built on top of the .NET
Dynamic Language Runtime. The .NET Framework is unique in its ability to provide this
flexibility.
Regardless of which .NET language is used, the output of the language compiler is a
representation of the same logic in an intermediate language named Common
Intermediate Language (CIL).
As the program is being executed by the CLR, the CLI code is compiled and cached, just
in time, to the machine code appropriate for the architecture on which the program is
running. This last compilation step is usually performed by the Common Language
Runtime component of the framework “just in time” (JIT) at the moment the program is
first invoked, though it can be manually performed at an earlier stage.
Microsoft Intermediate Language (MSIL)
MSIL or IL(Intermediate Language) is machine independent code generated by .NET
framework after the compilation of program written in any language by user.
MSIL or IL is now known as CIL(Common Intermediate Language).
One of the more interesting aspects of .NET is that when you compile your code, you do
not compile to native code. But the compilation process translates your code into
something called Microsoft intermediate language, which is also called MSIL or just IL.
The compiler also creates the necessary metadata and compiles it into the component.
This IL is CPU independent. After the IL and metadata are in a file, this compiled file is
called the PE, which stands for either portable executable or physical executable.
Because the PE contains your IL and metadata, it is therefore self-describing, eliminating
the need for a type library or interfaces specified with the Interface.
Page 6 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
.NET Assembly
Whatever .NET language you create applications with, compilers generate an assembly,
which is a file containing .NET executable code and is composed essentially by two kinds
of elements: MSIL code and metadata.
The .NET assembly is the standard for components developed with the Microsoft.NET.
Dot NET assemblies may or may not be executable, i.e., they might exist as the
executable (.exe) file or dynamic link library (DLL) file.
All the .NET assemblies contain the definition of types, versioning information for the
type, meta-data, and manifest. The designers of .NET have worked a lot on the
component (assembly) resolution.
The structure of an assembly: Assemblies contain code that is executed by the Common
Language Runtime.
Page 7 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
It forms a reference scope boundary. The assembly's manifest contains assembly
metadata that is used for resolving types and satisfying resource requests.
It forms a version boundary. The assembly is the smallest version able unit in the
common language runtime; all types and resources in the same assembly are versioned as
a unit.
It forms a deployment unit. When an application starts, only the assemblies the
application initially calls must be present. Other assemblies, such as localization
resources or assemblies containing utility classes, can be retrieved on demand. This
allows applications to be kept simple and thin when first downloaded.
It is a unit where side-by-side execution is supported.
There are two kinds of assemblies in .NET
a) Private
b) Shared
a) Private assemblies is the assembly which is used by application only, normally it resides
in your application folder directory.
b) Shared assemblies - It resides in GAC, so that anyone can use this assembly. Public
assemblies are always share the common functionalities with other applications.
An assembly can be a single file or it may consist of the multiple files. In case of multi-
file, there is one master module containing the manifest while other assemblies exist as
non-manifest modules. A module in .NET is a sub part of a multi-file .NET assembly.
Assembly is one of the most interesting and extremely useful areas of .NET architecture
along with reflections and attributes, but unfortunately very few people take interest in
learning such theoretical looking topics.
The .NET Framework Namespaces
. Net framework class library is a collection of namespaces.
Namespace is a logical naming scheme for types that have related functionality.
Namespace means nothing but a logical container or partition.
For example: My computer contains C:, D:, E: and F: Each drive contains 1.txt file. The
file 1.txt is available in all the drive so it is require to specify the drive name to locate the
actual required file.
At the top of the hierarchy is the System namespace.
A namespace is just a grouping of related classes. It's a method of putting classes inside a
container so that they can be clearly distinguished from other classes with the same name.
A namespace is a logical grouping rather than a physical grouping. The physical grouping
is accomplished by an assembly
The .NET CLR consists of multiple namespaces, which are spread across many
assemblies. For example, ADO.NET is the set of classes located in the System.Data
namespace, and ASP.NET is the set of classes located in the System.Web namespace.
In the CLR, the classes and structures contained in each of the namespaces represent a
common theme of development responsibility.
.NET Framework class library is collection of namespaces.
Following table shows Common Namespaces supported by .NET
System Contains fundamental classes and base classes.
System.IO Contains classes for reading and writing data in file.
System.XML Contains classes work with XML.
Page 8 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
System.Windows.Forms Contains classes for windows-based applications.
System.Data Contains classes for the database connection.
Why .NET?
Interoperability between language and execution environment.
Uniformity in schema or formats for Data exchange using XML, XSL (Extensible Style
Sheet Language)
Extend or use existing code that is valid.
Programming complexity of environment is reduced
Multiplatform applications, automatic resource management simplification of application
deployment.
It provides security like – code authenticity check, resources access authorizations,
declarative and imperative security and cryptographic security methods for embedding
into user’s application.
The .Net platform is on integral component a new and simplified model for programming
and deploying application on the windows platform.
Page 9 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
.Net development framework provides a new and simplified model for programming and
deploying applications on the windows platform.
Types of projects:
The following list provides a comparison of Visual Basic 6.0 and Visual Basic .NET project
types.
Visual Basic 6.0 Visual Basic .NET
Standard EXE Windows Application
ActiveX DLL Class Library
ActiveX EXE Class Library
ActiveX Control Windows Control Library
No equivalent. Visual Basic .NET can interoperate with ActiveX
ActiveX Document
Documents.
DHTML Application No equivalent. Use ASP.NET Web Application.
IIS Application (Web
No equivalent. Use ASP.NET Web Application.
Class)
Page 10 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
. ASP.NET Web Application ASP.NET−based application composed of static or
dynamic HTML pages
ASP.NET Web Service For Web services to be used by clients communicating over the
HTTP protocol
Web Control Library Web−based controls for ASP.NET applications
Console Application Your standard Console application
Windows Service Create Windows services
Empty Project Empty Windows application project
Empty Web Project Empty Web server−based application
Page 11 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
File: With this menu you can create a new project, open existing one, save the current
project ,exit form the vb.net etc
Edit: The Edit menu provides access to the items you would expect: Undo, Redo, Cut, Copy,
Paste, and Delete.
View: The View menu provides quick access to the windows that make up the IDE, such as the
Solution Explorer, Properties window, Output window, Toolbox, etc.
Project: The Project menu allows you to add various extra files to your application.
Build: The Build menu becomes important when you have completed your application and want
to be able to run it without the use of the Visual Basic .NET environment.
Debug: The Debug menu allows you to start and stop running your application within the Visual
Basic .NET IDE. It also gives you access to the Visual Studio .NET debugger.
Data: The Data menu helps you use information that comes from a database. It only appears
when you are working with the visual part of your application ,not when you are writing code.
Format: The Format menu also only appears when you are working with the visual part of your
application. Items on the Format menu allow you to manipulate how the windows you create will
appear to the users of your application.
Page 12 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Tools : The Tools menu has commands to configure the Visual Studio .NET IDE, as well as links
to other external tools that may have been installed.
Window: The commands on this menu allow you to change the physical layout of the windows
in the IDE.
Help: The Help menu provides access to the Visual Studio .NET documentation.
Code Designers
You can use the tabs at the top center of the IDE to switch between graphical designer
and code designer
From view menu, you can also switch between by using code (F7) and Designer
(Shift+F7) items.
From solution Explorer, from the left side you can use top two buttons.
At the top of code designer two drop down list boxes are available. The two drop-down
list boxes at the top of the code designer; the one on the left lets you select what object's
code you're working with, and the one on the right lets you select the part of the code that
you want to work on, letting you select between the declarations area, functions, Sub
procedures, and methods.
Page 13 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Figure 8 : Intellisense
The Toolbox
It is available on left side of IDE.
It uses tabs to divide its contents into categories like marked Data, Components,
Windows Forms, and General.
The Data, Components, Windows Forms, and General tabs appear when you're working
with a Windows form in a Windows form designer, but when you switch to a code
designer in the same project, all you'll see are General and Clipboard Ring in the toolbox.
When you're working on a Web form, you'll see Data, Web Forms, Components,
Components, HTML, Clipboard Ring, and General, and so on.
The Data tab displays tools for creating datasets and making data connections.
The Windows Forms tab displays tools for adding controls to Windows forms and so on.
The General tab is empty by default, and is a place to store general components, controls,
and fragments of code in.
Page 14 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Refresh button is also available.
The Class View Window
If you click the Class View tab under the Solution Explorer, you'll see the Class View
window, This view presents solutions and projects in terms of the classes they contain,
and the members of these classes.
Using the Class View window gives you an easy way of jumping to a member of class
that you want to access quickly-just find it in the Class View window, and double-click it
to bring it up in a code designer.
The Properties Window
The Properties window is divided into two columns of text, with the properties on the
left, and their settings on the right.
From drop-down list box at top of properties window, user can select any object which is
available in current form.
When you select a property, Visual Basic will give you an explanation of the property in
the panel at the bottom of the Properties window. And you can display the properties
alphabetically by clicking the second button from the left at the top of the Properties
window, or in categories by clicking the left-most button.
The Dynamic Help Window
The window that shares the Properties window's space, however, is quite new-the
Dynamic Help window. Visual Basic .NET includes the usual Help menu with Contents,
Index, and Search items, of course, but it also now supports dynamic help, which looks
things up for you automatically. You can see the Dynamic Help window by clicking the
Dynamic Help tab under the Properties window.
VB .NET looks up all kinds of help topics on the element you've selected automatically;
for example, I've selected a button on a Windows form, and dynamic help has responded
by displaying all kinds of helpful links to information on buttons.
The Server Explorer
It is used to explore what’s going on in a server
Using this tool you can drag and drop whole items onto windows forms from server
explorer. Ex. Database.
The Output Window
At the bottom of the IDE, two tabs are available one is Output and other is Breakpoints
windows.
From View menu Other Window Select Output Window.
This window displays results of building and running programs.
Using system Diagnostic.Debug.Write method user can send output to output window.
Ex. System.Diagnostics.Debug.Write(“Hello”)
The Task List
It is display from View Show Tasks All
The Task List displays tasks that VB .NET assumes you still have to take care of, and
when you click a task, the corresponding location in a code designer appears.
The Command Window
It is display from View Other Windows Command Window
It opens the Command window
This window is a little like the Immediate window in VB6, because you can enter
commands like File.AddNewProject here and VB .NET will display the Add New
Page 15 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Project dialog box. However, this window is not exactly like the Immediate window,
because you can't enter Visual Basic code and have it executed.
Following table shows storage size in memory for the data type.
Type Storage Size
String 2 bytes
Char 2 bytes
Integer 4 bytes
Long 8 bytes
Boolean 2 bytes
Byte 1 byte
Short 2 bytes
Single 4 bytes
Double 8 bytes
Decimal 16 bytes
Date 8 bytes
Object 4 bytes
Variables:
A variable is something that is used in a program to store data in memory.
A variable has a name and a data type which determine the kind of data the variable can
store.
Variable declaration: Dim statement is used to declare a variable.
Syntax: Dim variablename [ ( [ subscript ] ) ] [ As [ New ] datatype
Variablename : It is required. It specifies the name of variable which user wants to create.
Page 16 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Subscript : It is optional. Subscript is used to specify the size of array when user declares an
array.
New: New keyboard enables creation of new object. If you use new when declaring the object
variable, a new instance of the object is created.
Type : The type specify the data type of the variables.
Ex: Dim a as integer, s1 as string
Operators
Visual Basic comes with many built-in operators that allow us to manipulate data. An
operator performs a function on one or more operands. For example, we add two
variables with the "+" addition operator and store the result in a third variable with the
"=" assignment operator like this: int x + int y = int z. The two variables (x ,y) are called
operands. There are different types of operators in Visual Basic and they are described
below in the order of their precedence.
Operators may me Unary or Binary
Page 17 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Operators also categorized in following categories:
Arithmetic Operators : Arithmetic operators are used to perform arithmetic operations that
involve calculation of numeric values. The table below summarizes them:
Operator Use
^ Exponentiation
- Negation (used to reverse the sign of the given value, exp -intValue)
* Multiplication
/ Division for ex a=11/5 then answer is 5.5
\ Integer Division for ex a=11\5 then answer is 5
Mod Modulus Arithmetic
+ Addition
- Subtraction
Concatenation Operators : Concatenation operators join multiple strings into a single string.
There are two concatenation operators, + and & as summarized below:
Operator Use
+ String Concatenation
& String Concatenation
Comparison Operators : A comparison operator compares operands and returns a logical value
based on whether the comparison is true or not. The table below summarizes them:
Operator Use
= Equality
<> Inequality
< Less than
> Greater than
>= Greater than or equal to
<= Less than or equal to
Logical / Bitwise Operators : The logical operators compare Boolean expressions and return a
Boolean result. In short, logical operators are expressions which return a true or false result over
a conditional expression. The table below summarizes them:
Operator Use
Not Negation
Page 18 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
And Conjunction
AndAlso Conjunction
Or Disjunction
OrElse Disjunction
Xor Disjunction
Type Conversion functions
Type conversion is used for convert one data type to another
There are two type of conversion : Implicit and Explicit.
An Implicit Conversion does not require any special syntax in the source code.
An Explicit Conversion requires function.
For Example : Implicit Conversion
Dim a As Integer
Dim b As Double
a = 4499
b=a
An explicit conversion requires function.
Function Name Convert Into
CBool Boolean
CByte Byte
CChar Char
CDate Date
CDbl or Val Double
CDec Decimal
CInt Integer
CLng Long
CObj Object
CShort Short
CSng Single
CStr String
Following is common syntax for each type conversion function:
Syntax : Function_Name(argument)
For Example: Dim str As String
Dim no As Integer
str = “5”
no = Cint(str)
CTYPE function
It uses to convert one type to another type.
Instead of remember all conversion functions , we can use CTYPE function
Execution is faster .
Syntax : Ctype(expression,Type name)
For Example : Dim no1 As Integer
Dim no2 As Double
no2 = 66.77
no1 = Ctype(no2,Integer)
Page 19 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Boxing and Unboxing:
Boxing and unboxing act like bridges between value type and reference types. When we
convert
value type to a reference type it’s termed as boxing. Unboxing is just vice-versa.
Boxing: The conversion of a value type instance to an object.
Unboxing : The conversion of an object instance to a value type.
Example: Dim no As Integer= 10
Dim obj As Object = no ---- Boxing
Dim ans As Integer = CInt(obj) ---- Unboxing
Boxing conversions.
A boxing conversion permits any value-type to be implicitly converted to the type object or
to any interface-type implemented by the value-type.
Boxing a value of a value-type consists of allocating an object instance and copying the
value-type value into that instance.
For example any value-type G, the boxing class would be declared as follows:
Class vBox
Private value As G
Sub New(ByVal g As G)
value = g
End Sub 'New
End Class
BoxBoxing of a value v of type G now consists of executing the expression new G_Box(v),
and returning the resulting instance as a value of type object.
Thus, the statements
Dim i As Integer = 12
Dim box As Object = i
conceptually correspond to
Dim i As Integer = 12
Dim box = New int_Box(i)
Boxing classes like G_Box and int_Box above don't actually exist and the dynamic type of a
boxed value isn't actually a class type. Instead, a boxed value of type G has the dynamic
type G, and a dynamic type check using these operator can simply reference type G. For
example,
Dim i As Integer = 12
Dim box As Object = i
If TypeOf box Is Integer Then
Console.Write("Box contains an int")
End If
will output the string "Box contains an integer" on the console.
Unboxing conversions.
An unboxing conversion permits an explicit conversion from type object to any
value-type or from any interface-type to any value-type that implements the interface-type.
An unboxing operation consists of first checking that the object instance is a boxed value of
the given value-type, and then copying the value out of the instance.
Unboxing conversion of an object box to a value-type G consists of executing the expression
((G_Box)box).value.
Thus, the statements
Page 20 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
For an unboxing conversion to a given value-type to succeed at run-time, the value of the
source argument must be a reference to an object that was previously created by boxing a
value of that value-type. If the source argument is null or a reference to an incompatible
object, an InvalidCastException is thrown.
Array:
An ordered collection of same type of data having single variable name is known as
array. Each element of the array can be referenced by a numerical subscript.
In VB.Net two types of arrays are:
a) Standard Array
b) Dynamic Array
Declaration Of Standard Array:
Syntax : Dim varname [(subscripts)] [As type ]
WithEvents: This keyword is valid only in class modules. This keyword specifies that varname
is an object variable used to respond to events triggered by an ActiveX object.
VarName : The Varname specify the name of variable which you want to create.
Subscript : Subscript is used when you declare an array.
Type : The type specify the data type of the array variables. User can also include “To” keyword
in array declaration.
Ex : Dim n(5) As Integer.
Dim s(3) As String.
Dim n(1 to 4) As Integer.
Dynamic Array:
In any C or C++ programming language user can not modify the size of the array. Once
we declared the size of array then it becomes fixed.
In VB .NET we can increase the size of array.
In some cases we may not know exactly the size of array at declaration time. We may
need to change the size of the array at runtime. So we can resize the array at any time by
using Redim statement.
But with dynamic array we cannot change the dimension of the array.
Page 21 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
End Sub
Private Sub cmdPrint_Click()
ReDim Preserve a(3) As Integer
'MsgBox LBound(a) & UBound(a)
For i = LBound(a) To UBound(a)
msgbox a(i)
Next
End Sub
String Functions:
1) Len: This function returns an integer containing the number of characters in a given string.
Syntax : Len(string)
String: Any valid string expression. If string contains Null, Null is returned.
Example:
S1=”hello”
Msgbox len(s1)
2) Mid: It returns a Variant (String) containing a specified number of characters from a string.
Syntax: Mid(string, start[, length])
The Mid function syntax has these named arguments:
Part Description
String Required. String expression from which characters are returned. If string contains
Null, Null is returned.
Start Required; Long. Character position in string at which the part to be taken begins. If
start is greater than the number of characters in string, Mid returns a zero-length
string ("").
Length Optional; Variant (Long). Number of characters to return. If omitted or if there are
fewer than length characters in the text (including the character at start), all
characters from the start position to the end of the string are returned.
Examples:
Dim MyString, FirstWord, LastWord
MyString = "Mid Function Demo" ' Create text string.
FirstWord = Mid(MyString, 1, 3) ' Returns "Mid".
LastWord = Mid(MyString, 14, 4) ' Returns "Demo".
3) Trim , Rtrim, Ltrim: It Returns a string that contains a copy of a specified string without
leading spaces (LTrim), without trailing spaces (RTrim), or without leading or trailing
spaces (Trim).
Syntax: Trim / Rtrim / Ltrim (string)
String: It is requires any valid String expression. If string equals Nothing, the function returns
an empty string.
Example:
S1= “ This is test “
Msgbox Trim(s1)
Msgbox Rtrim(s1)
Msgbox Ltrim(s1)
Page 22 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
4) Instr: It returns a Variant (Long) specifying the position of the first occurrence of one string
within another.
Part Description
Start Optional. Numeric expression that sets the starting position for each search. If
omitted, search begins at the first character position. If start contains Null, an
error occurs. The start argument is required if compare is specified.
Compare Optional. Specifies the type of string comparison. If compare is Null, an error
occurs. If compare is omitted, the Option Compare setting determines the type
of comparison.
Return Value
If InStr returns
Examples:
Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP" ' String to search in.
SearchChar = "P" ' Search for "P".
' A textual comparison starting at position 4. Returns 6.
MyPos = Instr(4, SearchString, SearchChar, 1)
' A binary comparison starting at position 1. Returns 9.
Page 23 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
MyPos = Instr(1, SearchString, SearchChar, 0)
' Comparison is binary by default (last argument is omitted).
MyPos = Instr(SearchString, SearchChar) ' Returns 9.
Syntax: LCase(string)
The required string argument is any valid string expression. If string contains Null, Null is
returned. Only uppercase letters are converted to lowercase; all lowercase letters and nonletter
characters remain unchanged.
Example:
Dim UpperCase, LowerCase
Uppercase = "Hello World 1234" ' String to convert.
Msgbox Lcase(UpperCase) ' Returns "hello world 1234"
6) Ucase: It returns a Variant (String) containing the specified string, converted to uppercase.
Syntax: UCase(string)
The required string argument is any valid string expression. If string contains Null, Null is
returned.
Only lowercase letters are converted to uppercase; all uppercase letters and nonletter characters
remain unchanged.
Example:
Dim LowerCase, UpperCase
LowerCase = "Hello World 1234" ' String to convert.
Msgbox UCase(LowerCase) ' Returns "HELLO WORLD 1234".
7) Asc: It returns an Integer representing the character code corresponding to the first letter in a
string.
Syntax: Asc(string)
The required string argument is any valid string expression. If String is a String expression, only
the first character of the string is used for input. If String is Nothing or contains no characters, an
error occurs.
Example: msgbox Asc("A")
8) Chr: It returns a String containing the character associated with the specified character code.
Syntax: Chr(charcode)
An Integer expression representing the code point, or character code, for the character. If
CharCode is outside the valid range, an error occur. The valid range for Chr is 0 through 255.
Examples:
Dim MyChar
MyChar = Chr(65) ' Returns A.
9) Space: It returns a string consisting of the specified number of spaces.
Page 24 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Syntax: Space(number)
Number : It is required Integer expression. The number of spaces you want in the string.
Example: Msgbox “ Hi” & space(5) & “ How r u?”
10) Format: This function returns a string formatted according to instructions contained in a
format String expression.
Syntax: Format (Expression, style)
Expression : it is any valid expression.
Style: it is applied on specified expression
Example:
D1= #02/14/1989#
Msgbox format(d1,”DD-MM-YY”)
If StrComp returns
12) Left: It returns a Variant (String) containing a specified number of characters from the left
side of a string.
Page 25 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Syntax: Left(str, length)
str :it is required String expression from which the rightmost characters are returned.
Length: It is required Numeric expression indicating how many characters to return. If 0, a zero-
length string ("") is returned. If greater than or equal to the number of characters in str, the entire
string is returned.
Examples:
Dim AnyString, MyStr
AnyString = "Hello World" ' Define string.
MyStr = Microsoft.VisualBasic.Left(AnyString, 1)
Msgbox Mystr ' Returns "H".
13) Right: It returns a string containing a specified number of characters from the right side of
a string.
Syntax: Right(str,length)
str :it is required String expression from which the rightmost characters are returned.
Length: It is required Numeric expression indicating how many characters to return. If 0, a zero-
length string ("") is returned. If greater than or equal to the number of characters in str, the entire
string is returned.
Example:
S1=”this is test”
Msgbox Micosoft.VisualBasic.Right(s1,3)
14) Replace: It returns a string in which a specified substring has been replaced with another
substring a specified number of times.
Syntax: Replace (Expression, Find, Replacement)
Expression :Required. String expression containing substring to replace.
Find :Required. Substring being searched for.
Replacement :Required. Replacement substring.
Syntax : System.String.Concat(str1,str2)
Example:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
Page 26 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
ByVal e As System.EventArgs) Handles Button1.Click
Dim str1 As String
Dim str2 As String
Syntac: System.String.Copy(str)
Syntax: System.String.IndexOf(str)
If the parameter String occurred as a substring in the specified String then it returns position of
the first character of the substring. If it does not occur as a substring, -1 is returned.
Example:
Page 27 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Syntax: Substring(startIndex,length)
Example:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
End Sub
End Class
5) String.format: VB.NET String Format method replace the argument Object into a text
equivalent System.Striing.
Examples:
The currency symbol ($) displayed depends on the global locale settings.
The ToUpper method is often used to convert a string to uppercase so that it can be used in a
case-insensitive comparison.
Syntax: string.ToUpper()
Example:
S1= “This is Test”
Msgbox s1.Toupper()
7) String.ToLower: This method does not modify the value of the current instance. Instead, it
returns a new string in which all characters in the current instance are converted to lowercase.
Syntax: string.tolower()
Example:
S1= “This is Test”
Msgbox s1.tolower()
8) String.Remove: Deletes all the characters from this string beginning at a specified position
and continuing through the last position.
Syntax: String.Remove(startIndex)
startIndex : The position to begin deleting characters.
Example:
S1=”abc---def”
Msgbox s1.remove(3)
Page 29 of 29
7/13/2019 Button Control in VB.NET
VB.NET Tutorial
Basic Concepts
VB.NET Controls
www.thecodegallery.com/VBNET/Button.php 1/6
7/13/2019 Button Control in VB.NET
Label (Label.php)
TextBox (TextBox.php)
Button (Button.php)
LinkLabel (LinkLabel.php)
CheckBox (CheckBox.php)
RadioButton (RadioButton.php)
ComboBox (ComboBox.php)
ListBox (ListBox.php)
CheckedListBox (CheckedListBox.php)
DateTimePicker (DateTimePicker.php)
MaskedTextBox (MaskedtextBox.php)
RichTextBox (RichTextBox.php)
NumericUpDown (NumericUpDown.php)
ProgressBar (ProgressBar.php)
ToolTip (ToolTip.php)
GroupBox (GroupBox.php)
PictureBox (PictureBox.php)
ErrorProvider (ErrorProvider.php)
Timer (Timer.php)
OpenFileDialog (OpenFileDialog.php)
SaveFileDialog (SaveFileDialog.php)
ColorDialog (ColorDialog.php)
FontDialog (FontDialog.php)
PrintDialog (PrintDialog.php)
MenuStrip (MenuStrip.php)
ContextMenuStrip (ContextMenuStrip.php)
InputBox (InputBox.php)
MsgBox (MsgBox.php)
Property Purpose
BackColor It is used to get or set background color of the Button.
Font It is used to set Font Face, Font Style, Font Size and Effects of the text
associated with Button Control.
ForeColor It is used to get or set Fore color of the text associated with Button Control.
Enabled It is used to specify weather Button Control is enabled or not at run time. It has
Boolean value. Default value is true.
FlatStyle It is used to get or set appearance of the Button Control when user moves
mouse on it or click on it. It has following 4 options:
System, Popup, Standard, Flat
ImageAlign It is used to get or set alignment of the image that is displayed in the Button
control.
Text It is used to get or set text associated with the Button Control.
TextAlign It is used to get or set alignment of the text associated with the Button control.
www.thecodegallery.com/VBNET/Button.php 3/6
7/13/2019 Button Control in VB.NET
Visible It is used to specify weather Button Control is visible or not at run time. It has
Boolean value. Default value is true.
TextImageRelation It is used to get or set position of text in relation with image. It has following 5
options:
(1) Overlay
(2) ImageAboveText
(3) TextAboveImage
(4) ImageBeforeText
(5) TextBeforeImage
It is used when user wants to display both text and image on Button Control.
TabStop It is used to specify weather user can use TAB key to set focus on Button
Control or not. It has Boolean value. Default value is true.
Method Purpose
Show It is used to show Button control at run time.
Event Purpose
Click It is the default event of Button Control. It fires each time user clicks on Button Control.
Download Projects
www.thecodegallery.com/VBNET/Button.php 4/6
7/13/2019 Button Control in VB.NET
Download VB.NET Projects (Download.php)
Download Programs
www.thecodegallery.com/VBNET/Button.php 5/6
7/13/2019 Button Control in VB.NET
Best Free
Android
Emulator
Tencent Gaming Buddy
DOWNLOAD
www.thecodegallery.com/VBNET/Button.php 6/6
7/13/2019 InputBox Function in VB.NET
VB.NET Tutorial
Basic Concepts
VB.NET Controls
www.thecodegallery.com/VBNET/InputBox.php 1/6
7/13/2019 InputBox Function in VB.NET
Label (Label.php)
TextBox (TextBox.php)
Button (Button.php)
LinkLabel (LinkLabel.php)
CheckBox (CheckBox.php)
RadioButton (RadioButton.php)
ComboBox (ComboBox.php)
ListBox (ListBox.php)
CheckedListBox (CheckedListBox.php)
DateTimePicker (DateTimePicker.php)
MaskedTextBox (MaskedtextBox.php)
RichTextBox (RichTextBox.php)
NumericUpDown (NumericUpDown.php)
ProgressBar (ProgressBar.php)
ToolTip (ToolTip.php)
GroupBox (GroupBox.php)
PictureBox (PictureBox.php)
ErrorProvider (ErrorProvider.php)
Timer (Timer.php)
OpenFileDialog (OpenFileDialog.php)
SaveFileDialog (SaveFileDialog.php)
ColorDialog (ColorDialog.php)
FontDialog (FontDialog.php)
PrintDialog (PrintDialog.php)
MenuStrip (MenuStrip.php)
ContextMenuStrip (ContextMenuStrip.php)
InputBox (InputBox.php)
MsgBox (MsgBox.php)
www.thecodegallery.com/VBNET/InputBox.php 2/6
7/13/2019
InputBox function display a prompt in the formInputBox Function in VB.NET
of dialog box as shown below and waits for the user
to input some value in textbox or click a button.
If user clicks on OK button then it will return content of textbox in the form of string.
If user clicks on Cancel Button then it will return a blank value.
Learn more
www.thecodegallery.com/VBNET/InputBox.php 3/6
7/13/2019
SPONSORED SEARCHES InputBox Function in VB.NET
SPONSORED SEARCHES SPONSORED SEARCHES
Design a simple application that ask user to enter name and display it in label using Input Box
Function.
Step 1: Design a form as shown below:
Text Name
Step 3: Now Double click on Click To Enter Name Button and write following code display Input Box
and enter name.
Download Projects
www.thecodegallery.com/VBNET/InputBox.php 4/6
7/13/2019 InputBox Function in VB.NET
Download PHP & MySQL Project (../PHP/Download.php)
Download Programs
www.thecodegallery.com/VBNET/InputBox.php 5/6
7/13/2019 InputBox Function in VB.NET
www.thecodegallery.com/VBNET/InputBox.php 6/6
7/13/2019 MessageBox Function in VB.NET
VB.NET Tutorial
Basic Concepts
VB.NET Controls
www.thecodegallery.com/VBNET/MsgBox.php 1/5
7/13/2019 MessageBox Function in VB.NET
Label (Label.php)
TextBox (TextBox.php)
Button (Button.php)
LinkLabel (LinkLabel.php)
CheckBox (CheckBox.php)
RadioButton (RadioButton.php)
ComboBox (ComboBox.php)
ListBox (ListBox.php)
CheckedListBox (CheckedListBox.php)
DateTimePicker (DateTimePicker.php)
MaskedTextBox (MaskedtextBox.php)
RichTextBox (RichTextBox.php)
NumericUpDown (NumericUpDown.php)
ProgressBar (ProgressBar.php)
ToolTip (ToolTip.php)
GroupBox (GroupBox.php)
PictureBox (PictureBox.php)
ErrorProvider (ErrorProvider.php)
Timer (Timer.php)
OpenFileDialog (OpenFileDialog.php)
SaveFileDialog (SaveFileDialog.php)
ColorDialog (ColorDialog.php)
FontDialog (FontDialog.php)
PrintDialog (PrintDialog.php)
MenuStrip (MenuStrip.php)
ContextMenuStrip (ContextMenuStrip.php)
InputBox (InputBox.php)
MsgBox (MsgBox.php)
Alert Button for Seniors Array Data Structure Basic PHP Code
Design a simple application that displays a message box when user clicks on Close Form Button. If
user clicks yes then form will be closed otherwise it remains open.
Step 1: Design a form as shown below:
Step 3: Now Double click on Close Form Button and write following code display Message Box.
Download Projects
Download Programs
www.thecodegallery.com/VBNET/MsgBox.php 5/5
8/24/2020 NumericUpDown Control in VB.NET
SPONSORED SEARCHES
visual basic vb net code
AL
Free Live Chat for 3 Agents
AR
AdSupport Customers Wherever AS
Ad
They are with Agents on Site or at… AS
Comm100 AS
CO
Open
CR
Posted in VB.NET | WINDOWS CONTROLS on November 05, 2019 CR
Tags: NumericUpDown, Numeric UpDown control, VB.NET, windows controls
DA
A NumericUpDown control allows users to provide a spin (up/down) interface to move through pre-defined numbers using up and down
DE
arrows. In this tutorial, we will see how to create a NumericUpDown control at design- me as well as at run- me.
DE
20985
DI
EN
FI
A NumericUpDown control allows users to provide a spin (up/down) interface to move through pre-defined numbers using up
and down arrows. In this tutorial, we will see how to create a NumericUpDown control at design- me as well as at run- me. GA
https://www.dotnetheaven.com/article/numericupdown-control-in-vb.net 1/9
8/24/2020 NumericUpDown Control in VB.NET
Crea ng a NumericUpDown GD
GE
Performance monitoring
LI
and - pro ling of CI servers M
AdPerformance monitoring and
Ad M
pro ling of Jenkins, TeamCity,…
NE
yourkit.com
OF
Learn more
PR
We can create a NumericUpDown control using the Forms designer at design- me or using the NumericUpDown class in code at RE
run- me (also known as dynamically).
RE
Design- me
SE
SI
SP
#1 Controls Alternative ST
TA
1600 controls for web, desktop VB
VB
Community license for $1 million or less in revenue. Competitor discounts
available. VB
syncfusion.com VB
VB
VB
OPEN
VB
To create a NumericUpDown control at design- me, you simply drag and drop a NumericUpDown control from Toolbox to a Form VB
in Visual Studio. A er you drag and drop a NumericUpDown on a Form, the NumericUpDown looks like Figure 1. Once a
NumericUpDown is on the Form, you can move it around and resize it using mouse and set its proper es and events. VB
VI
VI
Figure 1 W
Run- me XA
XM
M
https://www.dotnetheaven.com/article/numericupdown-control-in-vb.net 2/9
8/24/2020 NumericUpDown Control in VB.NET
dynamicUpDown.ForeColor = Color.Orange
dynamicUpDown.BackColor = Color.Black
Current Value
The Value property represents the currently selected value in a control. The following code snippet sets and gets the Value proper es at run-
me.
dynamicUpDown.Value = 10
MessageBox.Show(dynamicUpDown.Value.ToString())
https://www.dotnetheaven.com/article/numericupdown-control-in-vb.net 6/9
8/24/2020 NumericUpDown Control in VB.NET
Ra
Ti
#1 Controls Alternative Lis
Da
1600 controls for web, desktop Pr
Lis
Community license for $1 million or less in revenue. Competitor discounts
He
available.
syncfusion.com Ri
Se
No
OPEN
Pi
Crea ng a NumericUpDown control at run- me is merely a work of crea ng an instance of NumericUpDown class, set its Ba
proper es and adds NumericUpDown class to the Form controls.
Ta
First step to create a dynamic NumericUpDown is to create an instance of NumericUpDown class. The following code snippet Sp
creates a NumericUpDown control object.
To
Dim dynamicUpDown As New NumericUpDown()
Pr
Co
Co
Tr
To
Ra
To
Im
Pa
Choose from several fast, reliable web hosting plans to meet your unique Pr
needs. M
Lin
In the next step, you may set proper es of a NumericUpDown control. The following code snippet sets loca on, size and Name proper es of
a NumericUpDown. La
Me.Controls.Add(this.NumericUpDown1) Gr
Se ng NumericUpDown Proper es
Sa
A er you place a NumericUpDown control on a Form, the next step is to set its proper es.
Fo
Fo
Flo
https://www.dotnetheaven.com/article/numericupdown-control-in-vb.net 3/9
8/24/2020 NumericUpDown Control in VB.NET
Minimum and Maximum proper es are used to set the minimum and maximum values of a NumericUpDown control. The following code
snippet sets the minimum and maximum proper es at run- me.
dynamicUpDown.Minimum = -10
dynamicUpDown.Maximum = 10
Accelera ons property can be used to move through a set of values when up and down bu ons are clicked in a NumericUpDown control.
Increment property is used to set the value that is increased or decreased when up and down bu ons are clicked. The following code snippet
sets the Increment and adds accelera ons.
dynamicUpDown.Increment = 5
https://www.dotnetheaven.com/article/numericupdown-control-in-vb.net 7/9
8/24/2020 NumericUpDown Control in VB.NET
Decimal Places
We can format the number of a NumericDropDown control using the DecimalPlaces property. The following code snippet formats the
number that displays 4 decimal values.
dynamicUpDown.DecimalPlaces = 4
HexaDecimal
We can use a NumericDropDown control to display number value in hexadecimal format. The following code snippet formats the number in
hexadecimal.
dynamicUpDown.Hexadecimal = True
https://www.dotnetheaven.com/article/numericupdown-control-in-vb.net 8/9
8/24/2020 NumericUpDown Control in VB.NET
Nu
Do
Performance monitoring and Cu
Ch
pro ling of CI servers M
Co
Performance monitoring and pro ling of Jenkins, TeamCity, Gradle, Maven, Ant and
Lis
JUnit
yourkit.com M
Ad
Ad
OPEN
Pr
The easiest way to set proper es is from the Proper es Window. You can open Proper es window by pressing F4 or right click on a control
and select Proper es menu item. The Proper es window looks like Figure 2.
Figure 2
Name
https://www.dotnetheaven.com/article/numericupdown-control-in-vb.net 4/9
8/24/2020 NumericUpDown Control in VB.NET
Summary
In this ar cle, we discussed discuss how to create a NumericUpDown control in Windows Forms at design- me as well as run-
me. A er that, we saw how to use various proper es and methods.
RELATED ARTICLES
WPF Grid Using VB.NET NumericUpDown and DomainUpDown control in VB.NET
Introduc on of DataGrid Control in VB.NET NumericUpDown Ajax Extender Control in VB.NET
How to Set Focus on a Control in ASP.NET using VB.NET Add items to a ListBox control in Vb.net
CheckedListBox Control in VB.NET ASP.NET 2.0 SqlDataSource Control in VB.NET
TabControl in WPF using VB.NET Dynamic Tab Control using VB.NET
https://www.dotnetheaven.com/article/numericupdown-control-in-vb.net 9/9
8/24/2020 NumericUpDown Control in VB.NET
The Loca on property takes a Point that specifies the star ng posi on of the NumericUpDown on a Form. You may also use Le and Top
proper es to specify the loca on of a control from the le top corner of the Form. The Size property specifies the size of the control. We can
also use Width and Height property instead of Size property. The following code snippet sets Loca on, Width, and Height proper es of a
NumericUpDown control.
Font
Font property represents the font of text of a NumericUpDown control. If you click on the Font property in Proper es window, you will see
Font name, size and other font op ons. The following code snippet sets Font property at run- me.
ForeColor and BackColor proper es represent foreground and background colors of a control. The following code snippet sets the
background and foreground colors of a control.
https://www.dotnetheaven.com/article/numericupdown-control-in-vb.net 5/9
VB.NET - CHECKBOX CONTROL
http://www.tutorialspoint.com/vb.net/vb.net_checkbox.htm Copyright © tutorialspoint.com
The CheckBox control allows the user to set true/false or yes/no type options. The user can select
or deselect it. When a check box is selected it has the value True, and when it is cleared, it holds
the value False.
Let's create two check boxes by dragging CheckBox controls from the Toolbox and dropping on
the form.
The CheckBox control has three states, checked, unchecked and indeterminate. In the
indeterminate state, the check box is grayed out. To enable the indeterminate state, the
ThreeState property of the check box is set to be True.
3 CheckAlign Gets or sets the horizontal and vertical alignment of the check
mark on the check box.
4 Checked Gets or sets a value indicating whether the check box is selected.
7 ThreeState Gets or sets a value indicating whether or not a check box should
allow three check states rather than two.
Methods of the CheckBox Control
The following are some of the commonly used methods of the CheckBox control:
1
OnCheckedChanged
2
OnCheckStateChanged
3
OnClick
1 AppearanceChanged Occurs when the value of the Appearance property of the check
box is changed.
2 CheckedChanged Occurs when the value of the Checked property of the CheckBox
control is changed.
Consult Microsoft documentation for detailed list of properties, methods and events of the
CheckBox control.
Example
In this example, let us add four check boxes in a group box. The check boxes will allow the users to
choose the source from which they came to know about the organization. If the user chooses the
check box with text "others", then the user is asked to specify and a text box is provided to give
input. When the user clicks the Submit button, he/she gets an appropriate message.
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:
Checking all the boxes:
The Label control represents a standard Windows label. It is generally used to display some
informative text on the GUI which is not changed during runtime.
Let's create a label by dragging a Label control from the Toolbox and dropping it on the form.
3 FlatStyle Gets or sets the flat style appearance of the Label control
4 Font Gets or sets the font of the text displayed by the control.
9 TabStop Gets or sets a value indicating whether the user can tab to the
Label. This property is not used by this class.
1
GetPreferredSize
Retrieves the size of a rectangular area into which a control can be fitted.
2
Refresh
Forces the control to invalidate its client area and immediately redraw itself and any child
controls.
3
Select
4
Show
5
ToString
Consult Microsoft documentation for detailed list of properties, methods and events of the Label
control.
Example
Following is an example, which shows how we can create two labels. Let us create the first label
from the designer view tab and set its properties from the properties window. We will use the Click
and the DoubleClick events of the label to move the first label and change its text and create the
second label and add it to the form, respectively.
2. Set the Text property to provide the caption "This is a Label Control".
4. Click the label to add the Click event in the code window and add the following codes.
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 and double clicking the label would produce the following effect:
VB.NET - RADIOBUTTON CONTROL
http://www.tutorialspoint.com/vb.net/vb.net_radio_button.htm Copyright © tutorialspoint.com
The RadioButton control is used to provide a set of mutually exclusive options. The user can select
one radio button in a group. If you need to place more than one group of radio buttons in the same
form, you should place them in different container controls like a GroupBox control.
Let's create three radio buttons by dragging RadioButton controls from the Toolbox and dropping
on the form.
The Checked property of the radio button is used to set the state of a radio button. You can display
text, image or both on radio button control. You can also change the appearance of the radio
button control by using the Appearance property.
2 AutoCheck Gets or sets a value indicating whether the Checked value and
the appearance of the control automatically change when the
control is clicked.
3 CheckAlign Gets or sets the location of the check box portion of the radio
button.
6 TabStop Gets or sets a value indicating whether a user can give focus to
the RadioButton control using the TAB key.
1
PerformClick
Consult Microsoft documentation for detailed list of properties, methods and events of the
RadioButton control.
Example
In the following example, let us create two groups of radio buttons and use their CheckedChanged
events for changing the BackColor and ForeColor property of the form.
Let's double click on the radio buttons and put the follow code in the opened window.
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:
7/2/2019 VB.NET working with Windows Form and Events in Visual Basic .NET
Sea
Basic .NET AL
In this ar cle, I will explain you about working with Windows Form and Events in Visual Basic .NET. AS
AS
2417
CO
CR
Now we can start working with forms. When we open a new form we can see the default proper es of the form by
selec ng View->Proper es Window (F4). The proper es window opens with default proper es set to form by the .NET DA
Framework
DE
Briefly on Proper es
DE
Appearance
DI
When we want to change the appearance of the form then we use Appearance proper es. Appearance proper es can change a
EN
background color, background image, border style, change the cursor, set the font for the text and so on.
FI
Behavior
GA
By se ng Behavior property to True or False we can enable or disable the form notable this property is the enabled property.
GD
Layout
GE
When we want to change the structure of the form then we use layout proper es. With these proper es we can set the loca on,
maximum size, minimum size, exact size of the form with the size property. Layout proper es let use specify the loca on of the LI
form where it should appear when we run the applica on which we can select from a predefined list. M
Window Style M
ControlBox property comes under Window style proper es which by default is True. If we want that minimize, maximize and the NE
cancel bu ons become invisible on the form. Set this property to False.
OF
Form Event
PR
The default event of a form is the load event which looks like this in code: RE
Public Class Form1 RE
SI
End Sub
End Class SP
You can also write code in the load event of the form, I show you how: ST
VB
When you press the OK bu on on the message box the blank form is displayed. It looks like the image below:
VB
img2.gif
VB
VI
Example:
VI
Now, add a TextBox and a Bu on to the form from the toolbox. The toolbox can be selected fromView->ToolBox on the main
menu or by holding Ctrl+Alt+X on the keyboard. Once adding the TextBox and Bu on to the form. We need to write an event for W
the Bu on sta ng something should happen when you click it. To do that get back to design view and double-click on the Bu on.
Doing that opens an event handler for the Bu on where you specify what should happen when you click the bu on. Now that W
code is looks like this:
W
W
Public Class Form1
W
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
W
End Sub
W
Private Sub Bu on1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles Bu on1.Click W
End Sub W
End Class
XA
Now place the code TextBox1.Text = "This is my first Form" in the Click event of the Bu on and run the applica on. When you click XM
the Bu on the output "This is my first Form" is displayed in the TextBox.
M
Example: Te
Cr
Public Class Form1
Fu
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
Ev
End Sub Tr
img3.gif W
Alterna vely, you can also use the MsgBox or MessageBox func ons to display text when you click on the Bu on. To do that place W
this line of code, MsgBox("This is my first Form") orMessageBox.Show("This is my first Form") in the click event of the Bu on and run Us
the applica on.
Te
Summary:
Bu
I hope this ar cle help you to understand about how to working with Windows Form and Events in Visual Basic .NET.
Ch
Au
RELATED ARTICLES
https://www.dotnetheaven.com/article/vb.net-working-with-windows-form-and-events-in-visual-basic 2/4
7/2/2019 VB.NET working with Windows Form and Events in Visual Basic .NET
HS
He
Er
Do
Sa
Pr
Pa
Da
Re
Co
Ke
Co
Fo
De
Ch
Co
Ch
Ad
Da
Co
Fo
Ha
Cr
Lo
Ta
Ha
https://www.dotnetheaven.com/article/vb.net-working-with-windows-form-and-events-in-visual-basic 3/4
7/2/2019 VB.NET working with Windows Form and Events in Visual Basic .NET
https://www.dotnetheaven.com/article/vb.net-working-with-windows-form-and-events-in-visual-basic 4/4
VB.NET - TEXTBOX CONTROL
http://www.tutorialspoint.com/vb.net/vb.net_textbox.htm Copyright © tutorialspoint.com
Text box controls allow entering text on a form at runtime. By default, it takes a single line of text,
however, you can make it accept multiple texts and even add scroll bars to it.
Let's create a text box by dragging a Text Box control from the Toolbox and dropping it on the
form.
6 Font Gets or sets the font of the text displayed by the control.
None
Horizontal
Vertical
Both
14 TabIndex Gets or sets the tab order of the control within its
container.
Left
Right
Center
1
AppendText
2
Clear
3
Copy
4
4
Cut
5
Paste
Replaces the current selection in the text box with the contents of the Clipboard.
6
PasteString
Sets the selected text to the specified text without clearing the undo buffer.
7
ResetText
8
ToString
9
Undo
Example
In this example, we create three text boxes and use the Click event of a button to display the
entered text using a message box. Take the following steps:
Drag and drop three Label controls and three TextBox controls on the form.
Change the texts on the labels to: Name, Organization and Comments, respectively.
Change the names of the text boxes to txtName, txtOrg and txtComment, respectively.
Drag and drop a button control on the form. Set its name to btnMessage and its text property
to 'Send Message'.
Click the button to add the Click event in the code window and add the following code.
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 Send Message button would show the following message box:
Loading [MathJax]/jax/output/HTML-CSS/jax.js
8/24/2020 CheckedListBox Control Overview - Windows Forms | Microsoft Docs
In this article
See also
The Windows Forms CheckedListBox control extends the ListBox control. It does almost
everything that a list box does and also can display a check mark next to items in the list.
Other differences between the two controls are that checked list boxes only support
DrawMode.Normal; and that checked list boxes can only have one item or none selected.
Note that a selected item appears highlighted on the form and is not the same as a
checked item.
Checked list boxes can have items added at design time using the String Collection Editor
or their items can added dynamically from a collection at run time, using the Items
property. For more information, see How to: Add and Remove Items from a Windows
Forms ComboBox, ListBox, or CheckedListBox Control.
See also
CheckedListBox
CheckedListBox.Items
ListControl.DataSource
ListBox Control Overview
Windows Forms Controls Used to List Options
How to: Determine Checked Items in the Windows Forms CheckedListBox Control
Yes No
https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/checkedlistbox-control-overview-windows-forms 1/1
7/2/2019 Creating Context Menu or Popup Menu in VB.NET
VB.NET Tutorial
Basic Concepts
VB.NET Controls
www.thecodegallery.com/VBNET/ContextMenuStrip.php 1/5
7/2/2019 Creating Context Menu or Popup Menu in VB.NET
Label (Label.php)
TextBox (TextBox.php)
Button (Button.php)
LinkLabel (LinkLabel.php)
CheckBox (CheckBox.php)
RadioButton (RadioButton.php)
ComboBox (ComboBox.php)
ListBox (ListBox.php)
CheckedListBox (CheckedListBox.php)
DateTimePicker (DateTimePicker.php)
MaskedTextBox (MaskedtextBox.php)
RichTextBox (RichTextBox.php)
NumericUpDown (NumericUpDown.php)
ProgressBar (ProgressBar.php)
ToolTip (ToolTip.php)
GroupBox (GroupBox.php)
PictureBox (PictureBox.php)
ErrorProvider (ErrorProvider.php)
Timer (Timer.php)
OpenFileDialog (OpenFileDialog.php)
SaveFileDialog (SaveFileDialog.php)
ColorDialog (ColorDialog.php)
FontDialog (FontDialog.php)
PrintDialog (PrintDialog.php)
MenuStrip (MenuStrip.php)
ContextMenuStrip (ContextMenuStrip.php)
InputBox (InputBox.php)
MsgBox (MsgBox.php)
A PopUp menu is a menu that is displayed when user right click either on a form or on a control.
It is also known as Context Menu or Floating Menu.
PopUp menu is useful to represents
www.thecodegallery.com/VBNET/ContextMenuStrip.php list of commonly used commands for form or control. 2/5
7/2/2019 Creating Context Menu or Popup Menu in VB.NET
It is displayed independent of the menu strip. It display at the position where right button of the
mouse is clicked by user.
Different controls and forms having different Pop up menu as per their requirements.
In order to create a PopUp menu double click on the ContextMenuStrip control in the Tool Box as
shown below:
As you double click on ContextMenuStrip control a PopUp menu is added just under the title bar or
menu strip of the form and ContextMenuStrip is added in the component tray under the form as
shown below:
As shown in the figure a PopUp menu is added just under the title bar of the form or Menu Bar but it
does not display at the same position during run time. It display at the position where user click right
button of the mouse.
User can add as many PopUp menus as required and assign them to different controls placed on
the form or to the form itself. In order to assign PopUp menu to particular control user have to set
ContextMenuStrip property of that control.
www.thecodegallery.com/VBNET/ContextMenuStrip.php 3/5
PopUp
7/2/2019 menu is shown in the figure below:
Creating Context Menu or Popup Menu in VB.NET
Download Projects
Download Programs
www.thecodegallery.com/VBNET/ContextMenuStrip.php 4/5
7/2/2019 Creating Context Menu or Popup Menu in VB.NET
Download Data Structure Algorithm (../DSM/Algorithm.php)
www.thecodegallery.com/VBNET/ContextMenuStrip.php 5/5
7/13/2019 Date time picker control in VB.NET
VB.NET Tutorial
Basic Concepts
VB.NET Controls
www.thecodegallery.com/VBNET/DateTimePicker.php 1/8
7/13/2019 Date time picker control in VB.NET
Label (Label.php)
TextBox (TextBox.php)
Button (Button.php)
LinkLabel (LinkLabel.php)
CheckBox (CheckBox.php)
RadioButton (RadioButton.php)
ComboBox (ComboBox.php)
ListBox (ListBox.php)
CheckedListBox (CheckedListBox.php)
DateTimePicker (DateTimePicker.php)
MaskedTextBox (MaskedtextBox.php)
RichTextBox (RichTextBox.php)
NumericUpDown (NumericUpDown.php)
ProgressBar (ProgressBar.php)
ToolTip (ToolTip.php)
GroupBox (GroupBox.php)
PictureBox (PictureBox.php)
ErrorProvider (ErrorProvider.php)
Timer (Timer.php)
OpenFileDialog (OpenFileDialog.php)
SaveFileDialog (SaveFileDialog.php)
ColorDialog (ColorDialog.php)
FontDialog (FontDialog.php)
PrintDialog (PrintDialog.php)
MenuStrip (MenuStrip.php)
ContextMenuStrip (ContextMenuStrip.php)
InputBox (InputBox.php)
MsgBox (MsgBox.php)
By default it displays current date in Long Date format. When user clicks on arrow button it displays
full calendar for the current month as shown below:
Property Purpose
Format It is used to get or set format for displaying date and time in
DateTimePicker Control. It has four options: Long, Short, Time, And
Custom. Default format is long.
www.thecodegallery.com/VBNET/DateTimePicker.php 3/8
7/13/2019 Date time picker control in VB.NET
CustomFormat It is used to get or set custom format for displaying date and time in
DateTimePicker Control.
For Example:
www.thecodegallery.com/VBNET/DateTimePicker.php 4/8
7/13/2019 Date time picker control in VB.NET
ShowUpDown It is used to specify weather UpDown arrow is displayed in the
DateTimePicker instead of DropDown Calendar or Not. It has Boolean
value. Default value is false.
MinDate It is used to get or set Minimum Date that can be selected using
DateTimePicker Control. Default value is 01/01/1753.
MaxDate It is used to get or set Maximum Date that can be selected using
DateTimePicker Control. Default value is 31/12/9998.
CalendarTrailingForeColor It is used to get or set Fore Color of the previous and next month’s date
that is displayed in Current Month’s Calendar.
Method Purpose
Show It is used to show DateTimePicker Control at run time.
www.thecodegallery.com/VBNET/DateTimePicker.php 5/8
7/13/2019 Date time picker control in VB.NET
Focus It is used to set cursor or focus on DateTimePicker Control.
Event Purpose
ValueChanged It is the default event of DateTimePicker Control. This event fires each time a value
in the DateTimePicker Control is changed.
TextChanged This event fires each time a text that is displayed in the DateTimePicker Control is
changed.
CloseUp This event fires each time a Popup Calendar is disappeared after selecting
particular date.
DropDown This event fires each time a Popup Calendar is displayed by clicking on DropDown
arrow.
Download Projects
www.thecodegallery.com/VBNET/DateTimePicker.php 6/8
7/13/2019 Date time picker control in VB.NET
Download Programs
www.thecodegallery.com/VBNET/DateTimePicker.php 7/8
7/13/2019 Date time picker control in VB.NET
Shipping quote
real time
www.thecodegallery.com/VBNET/DateTimePicker.php 8/8
7/13/2019 LinkLabel Control in VB.NET
VB.NET Tutorial
Basic Concepts
VB.NET Controls
www.thecodegallery.com/VBNET/LinkLabel.php 1/5
7/13/2019 LinkLabel Control in VB.NET
Label (Label.php)
TextBox (TextBox.php)
Button (Button.php)
LinkLabel (LinkLabel.php)
CheckBox (CheckBox.php)
RadioButton (RadioButton.php)
ComboBox (ComboBox.php)
ListBox (ListBox.php)
CheckedListBox (CheckedListBox.php)
DateTimePicker (DateTimePicker.php)
MaskedTextBox (MaskedtextBox.php)
RichTextBox (RichTextBox.php)
NumericUpDown (NumericUpDown.php)
ProgressBar (ProgressBar.php)
ToolTip (ToolTip.php)
GroupBox (GroupBox.php)
PictureBox (PictureBox.php)
ErrorProvider (ErrorProvider.php)
Timer (Timer.php)
OpenFileDialog (OpenFileDialog.php)
SaveFileDialog (SaveFileDialog.php)
ColorDialog (ColorDialog.php)
FontDialog (FontDialog.php)
PrintDialog (PrintDialog.php)
MenuStrip (MenuStrip.php)
ContextMenuStrip (ContextMenuStrip.php)
InputBox (InputBox.php)
MsgBox (MsgBox.php)
LinkLabel Control is designed such that it provides the functionality of Hyperlink in window
application.
It is derived from label Control
www.thecodegallery.com/VBNET/LinkLabel.php so it also provides all the functionality of Label control. 2/5
7/13/2019 LinkLabel Control in VB.NET
Properties of Linklabel Control in VB.NET
Property Purpose
LinkColor It is used to get or set Fore color of the Hyperlink in its default state.
ActiveLinkColor It is used to get or set Fore color of the Hyperlink when user clicks it.
DisabledLinkColor It is used to get or set Fore color of the Hyperlink when LinkLabel is disabled.
VisitedLinkColor It is used to get or set Fore color of the Hyperlink when LinkVisited property of
LinkLabel is set to true.
LinkVisited It is used to specify weather Hyperlink is already visited or not. It has Boolean
value. Default value is false.
TextAlign It is used to get or set alignment of the text associated with LinkLabel Control.
ForeColor It is used to get or set Fore Color of the text associated with LinkLabel Control.
Enabled It is used to specify weather LinkLabel control is enabled or not at runtime. It has
Boolean value true or false. Default value is true.
Visible It is used to specify weather LinkLabel control is visible or not at runtime. It has
Boolean value true or false. Default value is true.
www.thecodegallery.com/VBNET/LinkLabel.php 3/5
7/13/2019 LinkLabel Control in VB.NET
Method Purpose
Show It is used to Show LinkLabel Control at runtime.
Event Purpose
Link Clicked It is the default event of LinkLabel Control. It fires each time a user click on a
hyperlink of LinkLabel Control.
Download Projects
Download Programs
www.thecodegallery.com/VBNET/LinkLabel.php 4/5
7/13/2019 LinkLabel Control in VB.NET
Shipping quote
real time
www.thecodegallery.com/VBNET/LinkLabel.php 5/5
7/2/2019 Masked Textbox Control in VB.NET
VB.NET Tutorial
Basic Concepts
VB.NET Controls
www.thecodegallery.com/VBNET/MaskedtextBox.php 1/8
7/2/2019 Masked Textbox Control in VB.NET
Label (Label.php)
TextBox (TextBox.php)
Button (Button.php)
LinkLabel (LinkLabel.php)
CheckBox (CheckBox.php)
RadioButton (RadioButton.php)
ComboBox (ComboBox.php)
ListBox (ListBox.php)
CheckedListBox (CheckedListBox.php)
DateTimePicker (DateTimePicker.php)
MaskedTextBox (MaskedtextBox.php)
RichTextBox (RichTextBox.php)
NumericUpDown (NumericUpDown.php)
ProgressBar (ProgressBar.php)
ToolTip (ToolTip.php)
GroupBox (GroupBox.php)
PictureBox (PictureBox.php)
ErrorProvider (ErrorProvider.php)
Timer (Timer.php)
OpenFileDialog (OpenFileDialog.php)
SaveFileDialog (SaveFileDialog.php)
ColorDialog (ColorDialog.php)
FontDialog (FontDialog.php)
PrintDialog (PrintDialog.php)
MenuStrip (MenuStrip.php)
ContextMenuStrip (ContextMenuStrip.php)
InputBox (InputBox.php)
MsgBox (MsgBox.php)
Property Purpose
AllowPromptAsInput It is used to specify weather Prompt character can be entered as
valid input character in MaskedTextBox or not. It has Boolean
value. Default value is true.
www.thecodegallery.com/VBNET/MaskedtextBox.php 3/8
7/2/2019 Masked Textbox Control in VB.NET
CutCopyMaskFormat While cut or copy MaskedTextBox contents into clipboard this
property is used to specify weather to:
Exclude Prompt And Literal
Include Prompt
Include Literals
Include Prompt And Literal.
Default value is Include Literals.
Font It is used to set Font Face, Font Style, Font Size and Effects of the
text associated with MaskedTextBox Control.
ForeColor It is used to get or set Fore color of the text associated with
MaskedTextBox Control.
PasswordChar It is used to get or set a character that is displayed for each input
characters in MaskedTextBox.
www.thecodegallery.com/VBNET/MaskedtextBox.php 4/8
7/2/2019 Masked Textbox Control in VB.NET
PromptChar It is used to get or set Prompt character for MaskedTextBox
Control. This character is displayed in MaskedTextBox when user
has not entered any character.
ResetOnPrompt It is used to specify weather to reset and skip the current position
when the input character is same as prompt character. It has
Boolean value. Default value is true.
ResetOnSpace It is used to specify weather to reset and skip the current position
when the input is space character. It has Boolean value. Default
value is false.
TabStop It is used to specify weather user can use TAB key to set focus on
MaskedTextBox Control or not. It has Boolean value. Default value
is true.
TextMaskFormat It is used to get or set value which determines the text that is
returned from MaskedTextBox Control can contains literal, prompt ,
both or none. It has following 4 options:
Exclude Prompt And Literal
Include Prompt
Include Literals
Include Prompt And Literal.
Default value is Include Literals.
www.thecodegallery.com/VBNET/MaskedtextBox.php 5/8
7/2/2019 Masked Textbox Control in VB.NET
UseSystemPasswordCharacter It is used to specify weather each input character that is entered in
MaskedTextBox is displayed as System Password character or not.
It has Boolean value. Default value is false.
Method Purpose
Append Text It is used to append text at the end of current text in MaskedTextBox Control.
Event Purpose
MaskInputRejected It is the default event of MaskedTextBox. It fires each time a character entered
in MskedTextBox does not comply with Mask Property. It means if character
entered in MaskedTextBox does not match with the pattern specified in Mask
property then this event fires.
Download Projects
Download Programs
www.thecodegallery.com/VBNET/MaskedtextBox.php 8/8
7/2/2019 RichTextBox Control in VB.NET
VB.NET Tutorial
Basic Concepts
VB.NET Controls
www.thecodegallery.com/VBNET/RichTextBox.php 1/8
7/2/2019 RichTextBox Control in VB.NET
Label (Label.php)
TextBox (TextBox.php)
Button (Button.php)
LinkLabel (LinkLabel.php)
CheckBox (CheckBox.php)
RadioButton (RadioButton.php)
ComboBox (ComboBox.php)
ListBox (ListBox.php)
CheckedListBox (CheckedListBox.php)
DateTimePicker (DateTimePicker.php)
MaskedTextBox (MaskedtextBox.php)
RichTextBox (RichTextBox.php)
NumericUpDown (NumericUpDown.php)
ProgressBar (ProgressBar.php)
ToolTip (ToolTip.php)
GroupBox (GroupBox.php)
PictureBox (PictureBox.php)
ErrorProvider (ErrorProvider.php)
Timer (Timer.php)
OpenFileDialog (OpenFileDialog.php)
SaveFileDialog (SaveFileDialog.php)
ColorDialog (ColorDialog.php)
FontDialog (FontDialog.php)
PrintDialog (PrintDialog.php)
MenuStrip (MenuStrip.php)
ContextMenuStrip (ContextMenuStrip.php)
InputBox (InputBox.php)
MsgBox (MsgBox.php)
Property Purpose
AutoWordSelection It is used to specify weather automatic word selection is ON or OFF. It has
Boolean value. Default value is false.
ContextMenuStrip It is used to specify the name of shortcut menu that is displayed when user
right clicks on the RichTextBox.
Enabled It is used to specify weather RichTextBox Control is enabled or not at run time.
It has Boolean value. Default value is true.
Font It is used to set Font Face, Font Style, Font Size and Effects of the text
associated with RichTextBox Control.
ForeColor It is used to get or set Fore color of the text associated with RichTextBox
Control.
HideSelection It is used to specify weather text selection should be hidden or not when
RichTextBox lose its focus. It has Boolean value. Default value is true.
www.thecodegallery.com/VBNET/RichTextBox.php 3/8
7/2/2019 RichTextBox Control in VB.NET
MaxLength It is used to get or set maximum number of characters that can be entered in
RichTextBox. Default value is 2147483647.
Multiline It is used to specify weather RichTextBox can be expanded to enter more than
one line of text or not. It has Boolean value. Default value is true.
ScrollBars It is used to get or set type of scrollbars to be added with RichTextBox control.
It has following 4 options:
(1) None
(2) Horizontal
(2) Vertical
(3) Both
Default value is Both.
Size It is used to get or set height and width of RichTextBox control in pixel.
TabStop It is used to specify weather user can use TAB key to set focus on RichTextBox
Control or not. It has Boolean value. Default value is true.
Visible It is used to specify weather RichTextBox Control is visible or not at run time. It
has Boolean value. Default value is true.
WordWrap It is used to specify weather line will be automatically word wrapped while
entering multiple line of text in RichTextBox control or not. It has Boolean
value. Default value is true.
SelectedRtf It is used to get or set currently selected RTF formatted text in RichTextBox.
www.thecodegallery.com/VBNET/RichTextBox.php 4/8
7/2/2019 RichTextBox Control in VB.NET
SelectedText It is used to get or set currently selected text in RichTextBox.
SelectionAlignment It is used to get or set horizontal alignment of the text selected in RichTextBox.
SelectionBullet It is used to get or set value which determines weather bullet style should be
applied to selected text or not.
SelectionColor It is used to get or set Fore Color of the text selected in RichTextBox.
SelectionFont It is used to get or set font face, font style, and font size of the text selected in
RichTextBox.
SelectionStart It is used to get or set starting point of the text selected in the RichTextBox.
Method Purpose
Cut It is used to move current selection of RichTextBox into clipboard.
ClearUndo It is used to clear information from the Undo buffer of the RichTextBox.
Find It is used to find starting position of first occurrence of a string in the RichTextBox
control. If a string is not found then it returns -1.
SaveFile It is used to save contents of RichTextBox in to Rich Text Format (RTF) file.
LoadFile It is used to loads a Rich Text Format (RTF) file or standard ASCII text file into
RichTextBox Control.
Redo It is used to redo the last operation that is undo using undo method.
Event Purpose
TextChanged It is the default event of RichTextBox Control. It fires each time a text in the
RichTextBox control changed.
Download Projects
www.thecodegallery.com/VBNET/RichTextBox.php 6/8
7/2/2019 RichTextBox Control in VB.NET
Download Programs
www.thecodegallery.com/VBNET/RichTextBox.php 7/8
7/2/2019 RichTextBox Control in VB.NET
www.thecodegallery.com/VBNET/RichTextBox.php 8/8
Functions 1
Math Functions 2
String Functions 7
Dates and Times Summary 12
DateAndTime Class 13
Math Summary 17
Derived Math Functions 18
Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/32s6akha(d=printer).aspx
The topics in this section contain tables of the Visual Basic run-time member functions.
Note
You can also create functions and call them. For more information, see Function Statement (Visual Basic) and How to:
Create a Procedure that Returns a Value (Visual Basic).
In This Section
Conversion Functions (Visual Basic)
Related Sections
Visual Basic Language Reference
Visual Basic
© 2016 Microsoft
1 of 1 04.09.2016 0:04
Math Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/thc0a116(d=printer).aspx
The methods of the System.Math class provide trigonometric, logarithmic, and other common mathematical functions.
Remarks
The following table lists methods of the System.Math class. You can use these in a Visual Basic program.
.NET Framework
Description
method
Atan2 Returns the angle whose tangent is the quotient of two specified numbers.
Ceiling Returns the smallest integral value that's greater than or equal to the specified Decimal or
Double.
DivRem Returns the quotient of two 32-bit or 64-bit signed integers, and also returns the remainder
in an output parameter.
Exp Returns e (the base of natural logarithms) raised to the specified power.
Floor Returns the largest integer that's less than or equal to the specified Decimal or Double
number.
IEEERemainder Returns the remainder that results from the division of a specified number by another
specified number.
1 of 5 04.09.2016 0:06
Math Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/thc0a116(d=printer).aspx
Log Returns the natural (base e) logarithm of a specified number or the logarithm of a specified
number in a specified base.
Round Returns a Decimal or Double value rounded to the nearest integral value or to a specified
number of fractional digits.
To use these functions without qualification, import the System.Math namespace into your project by adding the
following code to the top of your source file:
Imports System.Math
Example
This example uses the Abs method of the Math class to compute the absolute value of a number.
2 of 5 04.09.2016 0:06
Math Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/thc0a116(d=printer).aspx
Example
This example uses the Atan method of the Math class to calculate the value of pi.
Example
This example uses the Cos method of the Math class to return the cosine of an angle.
Example
This example uses the Exp method of the Math class to return e raised to a power.
Example
This example uses the Log method of the Math class to return the natural logarithm of a number.
Example
This example uses the Round method of the Math class to round a number to the nearest integer.
3 of 5 04.09.2016 0:06
Math Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/thc0a116(d=printer).aspx
' Returns 3.
Dim MyVar2 As Double = Math.Round(2.8)
Example
This example uses the Sign method of the Math class to determine the sign of a number.
' Returns 1.
Dim MySign1 As Integer = Math.Sign(12)
' Returns ‐1.
Dim MySign2 As Integer = Math.Sign(‐2.4)
' Returns 0.
Dim MySign3 As Integer = Math.Sign(0)
Example
This example uses the Sin method of the Math class to return the sine of an angle.
Example
This example uses the Sqrt method of the Math class to calculate the square root of a number.
' Returns 2.
Dim MySqr1 As Double = Math.Sqrt(4)
' Returns 4.79583152331272.
Dim MySqr2 As Double = Math.Sqrt(23)
' Returns 0.
Dim MySqr3 As Double = Math.Sqrt(0)
' Returns NaN (not a number).
Dim MySqr4 As Double = Math.Sqrt(‐4)
Example
This example uses the Tan method of the Math class to return the tangent of an angle.
4 of 5 04.09.2016 0:06
Math Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/thc0a116(d=printer).aspx
Requirements
Class: Math
Namespace: System
See Also
Rnd
Randomize
NaN
Derived Math Functions (Visual Basic)
Arithmetic Operators (Visual Basic)
© 2016 Microsoft
5 of 5 04.09.2016 0:06
String Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/dd789093(d=printer).aspx
The following table lists the functions that Visual Basic provides to search and manipulate strings.
.NET Framework
Description
method
Asc, AscW Returns an Integer value representing the character code corresponding to a character.
Chr, ChrW Returns the character associated with the specified character code.
Filter Returns a zero-based array containing a subset of a String array based on specified filter
criteria.
Format Returns a string formatted according to instructions contained in a format String expression.
FormatCurrency Returns an expression formatted as a currency value using the currency symbol defined in the
system control panel.
FormatPercent Returns an expression formatted as a percentage (that is, multiplied by 100) with a trailing %
character.
InStr Returns an integer specifying the start position of the first occurrence of one string within
another.
InStrRev Returns the position of the first occurrence of one string within another, starting from the
right side of the string.
Left Returns a string containing a specified number of characters from the left side of a string.
LSet Returns a left-aligned string containing the specified string adjusted to the specified length.
1 of 5 04.09.2016 0:06
String Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/dd789093(d=printer).aspx
LTrim Returns a string containing a copy of a specified string with no leading spaces.
Replace Returns a string in which a specified substring has been replaced with another substring a
specified number of times.
Right Returns a string containing a specified number of characters from the right side of a string.
RSet Returns a right-aligned string containing the specified string adjusted to the specified length.
RTrim Returns a string containing a copy of a specified string with no trailing spaces.
StrDup Returns a string or object consisting of the specified character repeated the specified number
of times.
StrReverse Returns a string in which the character order of a specified string is reversed.
Trim Returns a string containing a copy of a specified string with no leading or trailing spaces.
UCase Returns a string or character containing the specified string converted to uppercase.
You can use the Option Compare statement to set whether strings are compared using a case-insensitive text sort order
determined by your system's locale (Text) or by the internal binary representations of the characters (Binary). The default
text comparison method is Binary.
Example
This example uses the UCase function to return an uppercase version of a string.
VB
Example
This example uses the LTrim function to strip leading spaces and the RTrim function to strip trailing spaces from a string
2 of 5 04.09.2016 0:06
String Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/dd789093(d=printer).aspx
VB
Example
This example uses the Mid function to return a specified number of characters from a string.
VB
Example
This example uses Len to return the number of characters in a string.
VB
Example
This example uses the InStr function to return the position of the first occurrence of one string within another.
VB
3 of 5 04.09.2016 0:06
String Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/dd789093(d=printer).aspx
' Returns 0.
TestPos = InStr(1, SearchString, "W")
Example
This example shows various uses of the Format function to format values using both String formats and user-defined
formats. For the date separator (/), time separator (:), and the AM/PM indicators (t and tt), the actual formatted output
displayed by your system depends on the locale settings the code is using. When times and dates are displayed in the
development environment, the short time format and short date format of the code locale are used.
Note
For locales that use a 24-hour clock, the AM/PM indicators (t and tt) display nothing.
VB
4 of 5 04.09.2016 0:06
String Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/dd789093(d=printer).aspx
TestStr = Format(23)
See Also
Keywords (Visual Basic)
Visual Basic Runtime Library Members
String Manipulation Summary (Visual Basic)
© 2016 Microsoft
5 of 5 04.09.2016 0:06
Dates and Times Summary (Visual Basic) https://msdn.microsoft.com/en-us/library/23zhzt65(d=printer).aspx
Visual Basic language keywords and run-time library members are organized by purpose and use.
See Also
Keywords (Visual Basic)
Visual Basic Runtime Library Members
© 2016 Microsoft
1 of 1 04.09.2016 1:11
DateAndTime Class (Microsoft.VisualBasic) https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.dateandti...
DateAndTime Class
.NET Framework (current version)
The DateAndTime module contains the procedures and properties used in date and time operations.
Namespace: Microsoft.VisualBasic
Assembly: Microsoft.VisualBasic (in Microsoft.VisualBasic.dll)
Inheritance Hierarchy
System.Object
Microsoft.VisualBasic.DateAndTime
Syntax
VB
<StandardModuleAttribute>
Public NotInheritable Class DateAndTime
Properties
1 of 4 04.09.2016 1:10
DateAndTime Class (Microsoft.VisualBasic) https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.dateandti...
Name Description
DateString Returns or sets a String value representing the current date according to your
system.
Now Returns a Date value containing the current date and time according to your system.
TimeOfDay Returns or sets a Date value containing the current time of day according to your
system.
Timer Returns a Double value representing the number of seconds elapsed since midnight.
TimeString Returns or sets a String value representing the current time of day according to your
system.
Today Returns or sets a Date value containing the current date according to your system.
Methods
Name Description
DateAdd(DateInterval, Double, DateTime) Returns a Date value containing a date and time value
to which a specified time interval has been added.
DateAdd(String, Double, Object) Returns a Date value containing a date and time value
to which a specified time interval has been added.
DateDiff(String, Object, Object, Returns a Long value specifying the number of time
FirstDayOfWeek, FirstWeekOfYear) intervals between two Date values.
2 of 4 04.09.2016 1:10
DateAndTime Class (Microsoft.VisualBasic) https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.dateandti...
3 of 4 04.09.2016 1:10
DateAndTime Class (Microsoft.VisualBasic) https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.dateandti...
Remarks
This module supports the Visual Basic language keywords and run-time library members that get the current date or time,
perform date calculations, return a date or time, set the date or time, or time the duration of a process.
Examples
This example uses the Today property to return the current system date.
Version Information
.NET Framework
Available since 1.1
Silverlight
Available since 2.0
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed
to be thread safe.
See Also
Microsoft.VisualBasic Namespace
Dates and Times Summary (Visual Basic)
Keywords (Visual Basic)
Visual Basic Runtime Library Members
Return to top
© 2016 Microsoft
4 of 4 04.09.2016 1:10
Math Summary (Visual Basic) https://msdn.microsoft.com/en-us/library/ay1z9h21(d=printer).aspx
Visual Basic language keywords and run-time library members are organized by purpose and use.
See Also
Derived Math Functions (Visual Basic)
Keywords (Visual Basic)
Visual Basic Runtime Library Members
© 2016 Microsoft
1 of 1 04.09.2016 1:14
Derived Math Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/w3t84e33(d=printer).aspx
The following table shows non-intrinsic math functions that can be derived from the intrinsic math functions of the
System.Math object. You can access the intrinsic math functions by adding Imports System.Math to your file or project.
1 of 2 04.09.2016 1:14
Derived Math Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/w3t84e33(d=printer).aspx
See Also
Math Functions (Visual Basic)
© 2016 Microsoft
2 of 2 04.09.2016 1:14
8/24/2020 VB.Net - ContextMenuStrip Control - Tutorialspoint
The ContextMenuStrip control represents a shortcut menu that pops up over controls, usually
when you right click them. They appear in context of some specific controls, so are called context
menus. For example, Cut, Copy or Paste options.
This control associates the context menu with other menu items by setting that menu item's
ContextMenuStrip property to the ContextMenuStrip control you designed.
Context menu items can also be disabled, hidden or deleted. You can also show a context menu
with the help of the Show method of the ContextMenuStrip control.
The following diagram shows adding a ContextMenuStrip control on the form −
1 SourceControl
Gets the last control that displayed the ContextMenuStrip control.
Example
https://www.tutorialspoint.com/vb.net/vb.net_context_menustrip.htm 1/3
8/24/2020 VB.Net - ContextMenuStrip Control - Tutorialspoint
In this example, let us add a content menu with the menu items Cut, Copy and Paste.
Take the following steps −
Drag and drop or double click on a ControlMenuStrip control to add it to the form.
Add the menu items, Cut, Copy and Paste to it.
Add a RichTextBox control on the form.
Set the ContextMenuStrip property of the rich text box to ContextMenuStrip1 using the
properties window.
Double the menu items and add following codes in the Click event of these menus −
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 −
Enter some text in the rich text box, select it and right-click to get the context menu appear −
https://www.tutorialspoint.com/vb.net/vb.net_context_menustrip.htm 2/3
8/24/2020 VB.Net - ContextMenuStrip Control - Tutorialspoint
Now, you can select any menu items and perform cut, copy or paste on the text box.
https://www.tutorialspoint.com/vb.net/vb.net_context_menustrip.htm 3/3
VB.NET - MENUSTRIP CONTROL
http://www.tutorialspoint.com/vb.net/vb.net_menustrip.htm Copyright © tutorialspoint.com
The MenuStrip control represents the container for the menu structure.
The MenuStrip control works as the top-level container for the menu structure. The
ToolStripMenuItem class and the ToolStripDropDownMenu class provide the functionalities to
create menu items, sub menus and drop-down menus.
2 Gets or sets the visibility of the grip used to reposition the control.
GripStyle
1 Occurs when the user accesses the menu with the keyboard or
MenuActivate mouse.
Example
In this example, let us add menu and sub-menu items.
Drag and drop or double click on a MenuStrip control, to add it to the form.
Click the Type Here text to open a text box and enter the names of the menu items or sub-
menu items you want. When you add a sub-menu, another text box with 'Type Here' text
opens below it.
Double-Click the Exit menu created and add the following code to the Click event of
ExitToolStripMenuItem:
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:
Click on the File -> Exit to exit from the application:
Loading [MathJax]/jax/output/HTML-CSS/jax.js
VB.NET - COMBOBOX CONTROL
http://www.tutorialspoint.com/vb.net/vb.net_combobox.htm Copyright © tutorialspoint.com
The ComboBox control is used to display a drop-down list of various items. It is a combination of a
text box in which the user enters an item and a drop-down list from which the user selects an item.
Let's create a combo box by dragging a ComboBox control from the Toolbox and dropping it on
the form.
You can populate the list box items either from the properties window or at runtime. To add items
to a ListBox, select the ListBox control and go to the properties window for the properties of this
control. Click the ellipses . . . button next to the Items property. This opens the String Collection
Editor dialog box, where you can enter the values one at a line.
1
BeginUpdate
Prevents the control from drawing until the EndUpdate method is called, while items are
added to the combo box one at a time.
2
EndUpdate
Resumes drawing of a combo box, after it was turned off by the BeginUpdate method.
3
FindString
Finds the first item in the combo box that starts with the string specified as an argument.
4
FindStringExact
Finds the first item in the combo box that exactly matches the specified string.
5
SelectAll
Selects all the text in the editable area of the combo box.
5 SelectionChangeCommitted Occurs when the selected item has changed and the
change appears in the combo box.
Example
In this example, let us fill a combo box with various items, get the selected items in the combo box
and show them in a list box and sort the items.
Drag and drop a combo box to store the items, a list box to display the selected items, four button
controls to add to the list box with selected items, to fill the combo box, to sort the items and to
clear the combo box list, respectively.
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:
Click on various buttons to check the actions performed by each:
Loading [MathJax]/jax/output/HTML-CSS/jax.js
VB.NET - LISTBOX CONTROL
http://www.tutorialspoint.com/vb.net/vb.net_listbox.htm Copyright © tutorialspoint.com
The ListBox represents a Windows control to display a list of items to a user. A user can select an
item from the list. It allows the programmer to add items at design time by using the properties
window or at the runtime.
Let's create a list box by dragging a ListBox control from the Toolbox and dropping it on the form.
You can populate the list box items either from the properties window or at runtime. To add items
to a ListBox, select the ListBox control and get to the properties window, for the properties of this
control. Click the ellipses . . . button next to the Items property. This opens the String Collection
Editor dialog box, where you can enter the values one at a line.
2 BorderStyle Gets or sets the type of border drawn around the list box.
8 MultiColumn Gets or sets a value indicating whether the list box supports
multiple columns.
9 ScrollAlwaysVisible Gets or sets a value indicating whether the vertical scroll bar is
shown at all times.
10 SelectedIndex Gets or sets the zero-based index of the currently selected item
in a list box.
12 SelectedItem Gets or sets the currently selected item in the list box.
14 SelectedValue Gets or sets the value of the member property specified by the
ValueMember property.
15 SelectionMode Gets or sets the method in which items are selected in the list
box. This property has values:
None
One
MultiSimple
MultiExtended
16 Sorted Gets or sets a value indicating whether the items in the list box
are sorted alphabetically.
17 Text Gets or searches for the text of the currently selected item in the
list box.
18 TopIndex Gets or sets the index of the first visible item of a list box.
1 BeginUpdate
Prevents the control from drawing until the EndUpdate method is called, while items are
added to the ListBox one at a time.
2
ClearSelected
3
EndUpdate
Resumes drawing of a list box after it was turned off by the BeginUpdate method.
4
FindString
Finds the first item in the ListBox that starts with the string specified as an argument.
5
FindStringExact
Finds the first item in the ListBox that exactly matches the specified string.
6
GetSelected
7
SetSelected
8
OnSelectedIndexChanged
8
OnSelectedValueChanged
Consult Microsoft documentation for detailed list of properties, methods and events of the ListBox
control.
Example 1
In the following example, let us add a list box at design time and add items on it at runtime.
Drag and drop two labels, a button and a ListBox control on the form.
Set the Text property of the first label to provide the caption "Choose your favourite
destination for higher studies".
Set the Text property of the second label to provide the caption "Destination". The text on
this label will change at runtime when the user selects an item on the list.
Click the listbox and the button controls to add the following codes in the code editor.
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:
When the user chooses a destination, the text in the second label changes:
Clicking the Select button displays a message box with the user's choice:
Example 2
In this example, we will fill up a list box with items, retrieve the total number of items in the list box,
sort the list box, remove some items and clear the entire list box.
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:
Loading [MathJax]/jax/output/HTML-CSS/jax.js
VB.NET - PICTUREBOX CONTROL
http://www.tutorialspoint.com/vb.net/vb.net_picturebox.htm Copyright © tutorialspoint.com
The PictureBox control is used for displaying images on the form. The Image property of the
control allows you to set an image both at design time or at run time.
Let's create a picture box by dragging a PictureBox control from the Toolbox and dropping it on
the form.
1 AllowDrop Specifies whether the picture box accepts data that a user drags
on it.
4 ImageLocation Gets or sets the path or the URL for the image displayed in the
control.
5 InitialImage Gets or sets the image displayed in the control when the main
image is loaded
8 TabStop Specifies whether the user will be able to focus on the picture box
by using the TAB key.
1
CancelAsync
2
Load
3
LoadAsync
4
ToString
6 KeyDown Occurs when a key is pressed when the control has focus.
7 KeyPress Occurs when a key is pressed when the control has focus.
8 KeyUp Occurs when a key is released when the control has focus.
Example
In this example, let us put a picture box and a button control on the form. We set the image
property of the picture box to logo.png, as we used before. The Click event of the button named
Button1 is coded to stretch the image to a specified size:
Design View:
When the application is executed, it displays:
It represents a Windows progress bar control. It is used to provide visual feedback to your users
about the status of some task. It shows a bar that fills in from left to right as the operation
progresses.
Let's click on a ProgressBar control from the Toolbox and place it on the form.
The main properties of a progress bar are Value, Maximum and Minimum. The Minimum and
Maximum properties are used to set the minimum and maximum values that the progress bar can
display. The Value property specifies the current position of the progress bar.
The ProgressBar control is typically used when an application performs tasks such as copying files
or printing documents. To a user the application might look unresponsive if there is no visual cue.
In such cases, using the ProgressBar allows the programmer to provide a visual status of progress.
6 ImeMode Gets or sets the input method editor IME for the
ProgressBar.
10 Minimum Gets or sets the minimum value of the range of the control.
1
Increment
2
PerformStep
3
ResetText
4
ToString
Example
In this example, let us create a progress bar at runtime. Let's double click on the Form and put the
follow code in the opened window.
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:
Loading [MathJax]/jax/output/HTML-CSS/jax.js
7/18/2019 MDI Form
Home C# VB.NET JAVA Python JavaScript jQuery ASP.NET Interview Questions Net Framework
Net-informations.com
OPEN
OPEN
vb.net-informations.com/gui/vb.net-mdi-form.htm 1/3
7/18/2019 MDI Form
Download
Home Source
C#Code VB.NET JAVA Print Source
Python Code
JavaScript jQuery ASP.NET Interview Questions Net Framework
Public Class Form1
End Class
vb.net-informations.com/gui/vb.net-mdi-form.htm 2/3
7/18/2019 MDI Form
Home C# VB.NET JAVA Python JavaScript jQuery ASP.NET Interview Questions Net Framework
Visual Studio IDE Step by Step help for DateTimePicker Control ProgressBar Control
creating a simple Crystal
Reports in VB.NET
net-informations.com net-informations.com net-informations.com net-informations.com
vb.net-informations.com/gui/vb.net-mdi-form.htm 3/3
11/29/2020 Using Unstructured Exception Handling
Search
web www.yaldex.com
Main Page
I'll take a look at the On Error GoTo statement first in this and the next few topics. Although one gets the impression that Microsoft would far rather you use
Try…Catch…Finally, there are simply some things you can do with On Error GoTo that you can't do with Try…Catch…Finally, such as resume execution
with a Resume statement.
The On Error GoTo statement enables exception handling and specifies the location of the exception-handling code within a procedure. Here's how the On
Error GoTo statement works:
On Error { GoTo [ line | 0 | -1 ] | Resume Next }
GoTo line—Enables the exception-handling code that starts at the line specified in the required line argument. The line argument is any line
label or line number. If an exception occurs, program execution goes to the given location. (Note that the specified line must be in the same
procedure as the On Error statement.)
GoTo 0—Disables enabled exception handler in the current procedure and resets it to Nothing.
Resume Next—Specifies that when an exception occurs, execution skips over the statement that caused the problem and goes to the
statement immediately following. Execution continues from that point.
Note If a trappable exception occurs in a procedure, you can handle that exception in an exception handler. But what if you call another procedure, and
an exception occurs before control returns from that procedure? If the called procedure has an exception handler, the code in that exception
handler will be executed. However, if the called procedure does not have an exception handler, control will return to the exception handler in the
calling procedure. In this way, control moves back up the calling chain to the closest exception handler.
Here's an example showing how to use the On Error GoTo statement that uses a division by zero to create an overflow exception. In this case, I'm directing
execution to the label "Handler", which you create by placing this label on a line of its own, followed by a colon—note that I also place an Exit Sub statement
before the exception handler so the exception-handling code isn't executed inadvertently during normal program execution:
Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
On Error Goto Handler
int3 = int2 / int1
Exit Sub
Handler:
www.yaldex.com/vb-net-tutorial-2/library.books24x7.com/book/id_5526/viewer.asp@bookid=5526&chunkid=0657090764.htm 1/3
11/29/2020 Using Unstructured Exception Handling
⋮
End Sub
End Module
And I can add exception-handling code in the exception handler like this:
Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
On Error Goto Handler
int3 = int2 / int1
Exit Sub
Handler:
System.Console.WriteLine("Overflow error!")
End Sub
End Module
Now when this console application runs, you'll see "Overflow error!". You can also handle specific exceptions in different ways depending which exception
occurred by checking the Err object's Number property, which holds the exception's number. Here, I'm handling only arithmetic overflow exceptions, which
are exception number 6:
Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
On Error Goto Handler
int3 = int2 / int1
Exit Sub
Handler:
If (Err.Number = 6) Then
System.Console.WriteLine("Overflow error!")
End If
End Sub
End Module
The Err object also has a new GetException method that returns an exception object. For more on these objects, see the topic "Using Structured Exception
Handling" in this chapter. Using the TypeOf and Is keywords in an If statement, you can handle exception objects such as OverflowException like this:
Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
On Error Goto Handler
int3 = int2 / int1
Exit Sub
Handler:
If (TypeOf Err.GetException() Is OverflowException) Then
System.Console.WriteLine("Overflow error!")
End If
End Sub
End Module
Now that structured exception handling has been added to Visual Basic, the real attraction of unstructured exception handling is the Resume statement—see
the next topic.
Tip System errors during calls to Windows dynamic-link libraries (DLL) do not throw exceptions which means they can't be trapped with Visual Basic
exception trapping. When calling DLL functions, you should check each return value for success or failure, and in case of failure, check the value in
the Err object's LastDLLError property.
www.yaldex.com/vb-net-tutorial-2/library.books24x7.com/book/id_5526/viewer.asp@bookid=5526&chunkid=0657090764.htm 2/3
11/29/2020 Using Unstructured Exception Handling
↓ https://websitetrafficestimator.wordpress.com/
www.yaldex.com/vb-net-tutorial-2/library.books24x7.com/book/id_5526/viewer.asp@bookid=5526&chunkid=0657090764.htm 3/3
11/29/2020 VB.Net - ColorDialog Control - Tutorialspoint
The ColorDialog control class represents a common dialog box that displays available colors along
with controls that enable the user to define custom colors. It lets the user select a color.
The main property of the ColorDialog control is Color, which returns a Color object.
Following is the Color dialog box −
The following are some of the commonly used properties of the ColorDialog control −
https://www.tutorialspoint.com/vb.net/vb.net_color_dialog.htm 1/4
11/29/2020 VB.Net - ColorDialog Control - Tutorialspoint
1
AllowFullOpen
Gets or sets a value indicating whether the user can use the dialog box to define
custom colors.
2
AnyColor
Gets or sets a value indicating whether the dialog box displays all available colors in the
set of basic colors.
3 CanRaiseEvents
4
Color
Gets or sets the color selected by the user.
5
CustomColors
Gets or sets the set of custom colors shown in the dialog box.
6
FullOpen
Gets or sets a value indicating whether the controls used to create custom colors are
visible when the dialog box is opened.
7 ShowHelp
Gets or sets a value indicating whether a Help button appears in the color dialog box.
8 SolidColorOnly
Gets or sets a value indicating whether the dialog box will restrict users to selecting
solid colors only.
The following are some of the commonly used methods of the ColorDialog control −
https://www.tutorialspoint.com/vb.net/vb.net_color_dialog.htm 2/4
11/29/2020 VB.Net - ColorDialog Control - Tutorialspoint
1 Reset
Resets all options to their default values, the last selected color to black, and the
custom colors to their default values.
2 RunDialog
3
ShowDialog
Runs a common dialog box with a default owner.
The following are some of the commonly used events of the ColorDialog control −
1 HelpRequest
Occurs when the user clicks the Help button on a common dialog box.
Example
In this example, let's change the forecolor of a label control using the color dialog box. Take the
following steps −
Drag and drop a label control, a button control and a ColorDialog control on the form.
Set the Text property of the label and the button control to 'Give me a new Color' and
'Change Color', respectively.
Change the font of the label as per your likings.
Double-click the Change Color button and modify the code of the Click event.
https://www.tutorialspoint.com/vb.net/vb.net_color_dialog.htm 3/4
11/29/2020 VB.Net - ColorDialog Control - Tutorialspoint
When the application is compiled and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −
Clicking on the Change Color button, the color dialog appears, select a color and click the OK
button. The selected color will be applied as the forecolor of the text of the label.
https://www.tutorialspoint.com/vb.net/vb.net_color_dialog.htm 4/4
VB.NET - EXCEPTION HANDLING
http://www.tutorialspoint.com/vb.net/vb.net_exception_handling.htm Copyright © tutorialspoint.com
Exceptions provide a way to transfer control from one part of a program to another. VB.Net
exception handling is built upon four keywords: 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.
Syntax
Assuming a block will raise an exception, a method catches an exception using a combination of
the Try and Catch keywords. A Try/Catch block is placed around the code that might generate an
exception. Code within a Try/Catch block is referred to as protected code, and the syntax for using
Try/Catch looks like the following:
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
You can list down multiple catch statements to catch different type of exceptions in case your try
block raises more than one exception in different situations.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class:
Handling Exceptions
VB.Net provides a structured solution to the exception handling problems in the form of try and
catch blocks. Using these blocks the core program statements are separated from the error-
handling statements.
These error handling blocks are implemented using the Try, Catch and Finally keywords.
Following is an example of throwing an exception when dividing by zero condition occurs:
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException
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
When the above code is compiled and executed, it produces the following result:
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
When the above code is compiled and executed, it produces the following result:
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception class.
You can use a throw statement in the catch block to throw the present object as:
Throw [ expression ]
Module exceptionProg
Sub Main()
Try
Throw New ApplicationException("A custom exception _
is being thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
It prompts the user to choose a font from among those installed on the local computer and lets the
user select the font, font size, and color. It returns the Font and Color objects.
Following is the Font dialog box −
By default, the Color ComboBox is not shown on the Font dialog box. You should set the
ShowColor property of the FontDialog control to be True.
The following are some of the commonly used properties of the FontDialog control −
https://www.tutorialspoint.com/vb.net/vb.net_font_dialog.htm 1/5
11/29/2020 VB.Net - FontDialog Control - Tutorialspoint
1
AllowSimulations
Gets or sets a value indicating whether the dialog box allows graphics device interface
(GDI) font simulations.
2
AllowVectorFonts
Gets or sets a value indicating whether the dialog box allows vector font selections.
3 AllowVerticalFonts
Gets or sets a value indicating whether the dialog box displays both vertical and
horizontal fonts, or only horizontal fonts.
4
Color
Gets or sets the selected font color.
5
FixedPitchOnly
Gets or sets a value indicating whether the dialog box allows only the selection of fixed-
pitch fonts.
6
Font
Gets or sets the selected font.
7 FontMustExist
Gets or sets a value indicating whether the dialog box specifies an error condition if the
user attempts to select a font or style that does not exist.
8 MaxSize
9 MinSize
10
ScriptsOnly
https://www.tutorialspoint.com/vb.net/vb.net_font_dialog.htm 2/5
11/29/2020 VB.Net - FontDialog Control - Tutorialspoint
Gets or sets a value indicating whether the dialog box allows selection of fonts for all
non-OEM and Symbol character sets, as well as the ANSI character set.
11 ShowApply
Gets or sets a value indicating whether the dialog box contains an Apply
button.
12 ShowColor
Gets or sets a value indicating whether the dialog box displays the color choice.
13 ShowEffects
Gets or sets a value indicating whether the dialog box contains controls that allow the
user to specify strikethrough, underline, and text color options.
14 ShowHelp
Gets or sets a value indicating whether the dialog box displays a Help button.
The following are some of the commonly used methods of the FontDialog control −
1 Reset
Resets all options to their default values.
2 RunDialog
When overridden in a derived class, specifies a common dialog box.
3 ShowDialog
Runs a common dialog box with a default owner.
The following are some of the commonly used events of the FontDialog control −
https://www.tutorialspoint.com/vb.net/vb.net_font_dialog.htm 3/5
11/29/2020 VB.Net - FontDialog Control - Tutorialspoint
1 Apply
Occurs when the Apply button on the font dialog box is clicked.
Example
In this example, let's change the font and color of the text from a rich text control using the Font
dialog box. Take the following steps −
Drag and drop a RichTextBox control, a Button control and a FontDialog control on the
form.
Set the Text property of the button control to 'Change Font'.
Set the ShowColor property of the FontDialog control to True.
Double-click the Change Color button and modify the code of the Click event −
When the application is compiled and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −
https://www.tutorialspoint.com/vb.net/vb.net_font_dialog.htm 4/5
11/29/2020 VB.Net - FontDialog Control - Tutorialspoint
The Font dialog appears, select a font and a color and click the OK button. The selected font and
color will be applied as the font and fore color of the text of the rich text box.
https://www.tutorialspoint.com/vb.net/vb.net_font_dialog.htm 5/5
10/2/2020 VB.Net - OpenFileDialog Control - Tutorialspoint
The OpenFileDialog control prompts the user to open a file and allows the user to select a file to
open. The user can check if the file exists and then open it. The OpenFileDialog control class
inherits from the abstract class FileDialog.
If the ShowReadOnly property is set to True, then a read-only check box appears in the dialog box.
You can also set the ReadOnlyChecked property to True, so that the read-only check box appears
checked.
Following is the Open File dialog box −
https://www.tutorialspoint.com/vb.net/vb.net_openfile_dialog.htm 1/5
10/2/2020 VB.Net - OpenFileDialog Control - Tutorialspoint
1
AddExtension
Gets or sets a value indicating whether the dialog box automatically adds an extension
to a file name if the user omits the extension.
2
AutoUpgradeEnabled
Gets or sets a value indicating whether this FileDialog instance should automatically
upgrade appearance and behavior when running on Windows Vista.
3 CheckFileExists
Gets or sets a value indicating whether the dialog box displays a warning if the user
specifies a file name that does not exist.
4 CheckPathExists
Gets or sets a value indicating whether the dialog box displays a warning if the user
specifies a path that does not exist.
5
CustomPlaces
Gets the custom places collection for this FileDialog instance.
6
DefaultExt
Gets or sets the default file name extension.
7 DereferenceLinks
Gets or sets a value indicating whether the dialog box returns the location of the file
referenced by the shortcut or whether it returns the location of the shortcut (.lnk).
8 FileName
Gets or sets a string containing the file name selected in the file dialog box.
9 FileNames
Gets the file names of all selected files in the dialog box.
10
Filter
https://www.tutorialspoint.com/vb.net/vb.net_openfile_dialog.htm 2/5
10/2/2020 VB.Net - OpenFileDialog Control - Tutorialspoint
Gets or sets the current file name filter string, which determines the choices that appear
in the "Save as file type" or "Files of type" box in the dialog box.
11 FilterIndex
Gets or sets the index of the filter currently selected in the file dialog box.
12 InitialDirectory
Gets or sets the initial directory displayed by the file dialog box.
13
Multiselect
Gets or sets a value indicating whether the dialog box allows multiple files to be
selected.
14
ReadOnlyChecked
Gets or sets a value indicating whether the read-only check box is selected.
15 RestoreDirectory
Gets or sets a value indicating whether the dialog box restores the current directory
before closing.
16 SafeFileName
Gets the file name and extension for the file selected in the dialog box. The file name
does not include the path.
17 SafeFileNames
Gets an array of file names and extensions for all the selected files in the dialog box.
The file names do not include the path.
18 ShowHelp
Gets or sets a value indicating whether the Help button is displayed in the file dialog
box.
19 ShowReadOnly
Gets or sets a value indicating whether the dialog box contains a read-only check box.
https://www.tutorialspoint.com/vb.net/vb.net_openfile_dialog.htm 3/5
10/2/2020 VB.Net - OpenFileDialog Control - Tutorialspoint
20 SupportMultiDottedExtensions
Gets or sets whether the dialog box supports displaying and saving files that have
multiple file name extensions.
21
Title
Gets or sets the file dialog box title.
22 ValidateNames
Gets or sets a value indicating whether the dialog box accepts only valid Win32 file
names.
1 OpenFile
Opens the file selected by the user, with read-only permission. The file is specified by
the FileName property.
2 Reset
Resets all options to their default value.
Example
In this example, let's load an image file in a picture box, using the open file dialog box. Take the
following steps −
Drag and drop a PictureBox control, a Button control and a OpenFileDialog control on the
form.
Set the Text property of the button control to 'Load Image File'.
Double-click the Load Image File button and modify the code of the Click event:
https://www.tutorialspoint.com/vb.net/vb.net_openfile_dialog.htm 4/5
10/2/2020 VB.Net - OpenFileDialog Control - Tutorialspoint
When the application is compiled and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −
Click on the Load Image File button to load an image stored in your computer.
https://www.tutorialspoint.com/vb.net/vb.net_openfile_dialog.htm 5/5
VB.NET - PRINTDIALOG CONTROL
http://www.tutorialspoint.com/vb.net/vb.net_print_dialog.htm Copyright © tutorialspoint.com
The PrintDialog control lets the user to print documents by selecting a printer and choosing which
sections of the document to print from a Windows Forms application.
There are various other controls related to printing of documents. Let us have a brief look at these
controls and their purpose. These other controls are:
The PrintDocument control - it provides support for actual events and operations of printing
in Visual Basic and sets the properties for printing.
The PageSetUpDialog control - it allows the user to specify page-related print settings
including page orientation, paper size and margin size.
The PrintPreviewControl control - it represents the raw preview part of print previewing
from a Windows Forms application, without any dialog boxes or buttons.
1 AllowCurrentPage Gets or sets a value indicating whether the Current Page option
button is displayed.
2 AllowPrintToFile Gets or sets a value indicating whether the Print to file check
box is enabled.
4 AllowSomePages Gets or sets a value indicating whether the Pages option button
is enabled.
6 PrinterSettings Gets or sets the printer settings the dialog box modifies.
7 PrintToFile Gets or sets a value indicating whether the Print to file check
box is selected.
1
Reset
2
RunDialog
3
ShowDialog
Example
In this example, let us see how to show a Print dialog box in a form. Take the following steps:
Add a PrintDocument control, a PrintDialog control and a Button control on the form. The
PrintDocument and the PrintDialog controls are found on the Print category of the controls
toolbox.
Double-click the Print button and modify the code of the Click event as shown:
When the application is compiled and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window:
Click the Print button to make the Print dialog box appear.
11/29/2020 VB.Net - Sub Procedures - Tutorialspoint
As we mentioned in the previous chapter, Sub procedures are procedures that do not return any
value. We have been using the Sub procedure Main in all our examples. We have been writing
console applications so far in these tutorials. When these applications start, the control goes to the
Main Sub procedure, and it in turn, runs any other statements constituting the body of the program.
The Sub statement is used to declare the name, parameter and the body of a sub procedure. The
syntax for the Sub statement is −
Where,
Modifiers − specify the access level of the procedure; possible values are - Public,
Private, Protected, Friend, Protected Friend and information regarding overloading,
overriding, sharing, and shadowing.
SubName − indicates the name of the Sub
ParameterList − specifies the list of the parameters
Example
The following example demonstrates a Sub procedure CalculatePay that takes two parameters
hours and wages and displays the total pay of an employee −
Live Demo
Module mysub
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
CalculatePay(25, 10)
CalculatePay(40, 20)
https://www.tutorialspoint.com/vb.net/vb.net_subs.htm 1/3
11/29/2020 VB.Net - Sub Procedures - Tutorialspoint
CalculatePay(30, 27.5)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
In VB.Net, you declare the reference parameters using the ByVal keyword. The following example
demonstrates the concept −
Live Demo
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
https://www.tutorialspoint.com/vb.net/vb.net_subs.htm 2/3
11/29/2020 VB.Net - Sub Procedures - Tutorialspoint
It shows that there is no change in the values though they had been changed inside the function.
In VB.Net, you declare the reference parameters using the ByRef keyword. The following example
demonstrates this −
Live Demo
Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
https://www.tutorialspoint.com/vb.net/vb.net_subs.htm 3/3
VB.NET - SAVEFILEDIALOG CONTROL
http://www.tutorialspoint.com/vb.net/vb.net_savefile_dialog.htm Copyright © tutorialspoint.com
The SaveFileDialog control prompts the user to select a location for saving a file and allows the
user to specify the name of the file to save data. The SaveFileDialog control class inherits from the
abstract class FileDialog.
8 FileNames Gets the file names of all selected files in the dialog
box.
9 Filter Gets or sets the current file name filter string, which
determines the choices that appear in the "Save as
file type" or "Files of type" box in the dialog box.
1
OpenFile
2
Reset
Example
In this example, let's save the text entered into a rich text box by the user using the save file dialog
box. Take the following steps:
Drag and drop a Label control, a RichTextBox control, a Button control and a SaveFileDialog
control on the form.
Set the Text property of the label and the button control to 'We appreciate your comments'
and 'Save Comments', respectively.
Double-click the Save Comments button and modify the code of the Click event as shown:
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
When the application is compiled and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window:
We have set the Filter property of the SaveFileDialog control to display text file types with .txt
extensions only.
Write some text in the text box and click on the Save Comment button to save the text as a text file
in your computer.
Loading [MathJax]/jax/output/HTML-CSS/jax.js
VB.NET - STRINGS
http://www.tutorialspoint.com/vb.net/vb.net_strings.htm Copyright © tutorialspoint.com
In VB.Net, you can use strings as array of characters, however, more common practice is to use
the String keyword to declare a string variable. The string keyword is an alias for the
System.String class.
Module strings
Sub Main()
Dim fname, lname, fullname, greetings As String
fname = "Rowan"
lname = "Atkinson"
fullname = fname + " " + lname
Console.WriteLine("Full Name: {0}", fullname)
When the above code is compiled and executed, it produces the following result:
1
1
Chars
Gets the Char object at a specified position in the current String object.
2
Length
1
Public Shared Function Compare strAAsString, strBAsString As Integer
Compares two specified string objects and returns an integer that indicates their relative
position in the sort order.
2
Public Shared Function Compare strAAsString, strBAsString, ignoreCaseAsBoolean As Integer
Compares two specified string objects and returns an integer that indicates their relative
position in the sort order. However, it ignores case if the Boolean parameter is true.
3
Public Shared Function Concat str0AsString, str1AsString As String
4
Public Shared Function Concat str0AsString, str1AsString, str2AsString As String
5
Public Shared Function Concat str0AsString, str1AsString, str2AsString, str3AsString As String
6
Public Function Contains valueAsString As Boolean
Returns a value indicating whether the specified string object occurs within this string.
7
Public Shared Function Copy strAsString As String
Creates a new String object with the same value as the specified string.
8
pPublic Sub CopyTo sourceIndexAsInteger, destinationAsChar(, destinationIndex As Integer,
count As Integer )
Copies a specified number of characters from a specified position of the string object to a
specified position in an array of Unicode characters.
9
Public Function EndsWith valueAsString As Boolean
Determines whether the end of the string object matches the specified string.
10
Public Function Equals valueAsString As Boolean
Determines whether the current string object and the specified string object have the
same value.
11
Public Shared Function Equals aAsString, bAsString As Boolean
Determines whether two specified string objects have the same value.
12
Public Shared Function Format formatAsString, arg0AsObject As String
Replaces one or more format items in a specified string with the string representation of a
specified object.
13
Public Function IndexOf valueAsChar As Integer
Returns the zero-based index of the first occurrence of the specified Unicode character in
the current string.
14
Public Function IndexOf valueAsString As Integer
Returns the zero-based index of the first occurrence of the specified string in this instance.
15
Public Function IndexOf valueAsChar, startIndexAsInteger As Integer
Returns the zero-based index of the first occurrence of the specified Unicode character in
this string, starting search at the specified character position.
16
Public Function IndexOf valueAsString, startIndexAsInteger As Integer
Returns the zero-based index of the first occurrence of the specified string in this instance,
starting search at the specified character position.
17
Public Function IndexOfAny anyOfAsChar( ) As Integer
Returns the zero-based index of the first occurrence in this instance of any character in a
specified array of Unicode characters.
18
Public Function IndexOfAny anyOfAsChar(, startIndex As Integer ) As Integer
Returns the zero-based index of the first occurrence in this instance of any character in a
specified array of Unicode characters, starting search at the specified character position.
19
Public Function Insert startIndexAsInteger, valueAsString As String
Returns a new string in which a specified string is inserted at a specified index position in
the current string object.
20
Public Shared Function IsNullOrEmpty valueAsString As Boolean
21
Public Shared Function Join separatorAsString, ParamArrayvalueAsString( ) As String
Concatenates all the elements of a string array, using the specified separator between
each element.
22
Public Shared Function Join separatorAsString, valueAsString(, startIndex As Integer,
count As Integer ) As String
Concatenates the specified elements of a string array, using the specified separator
between each element.
23
Public Function LastIndexOf valueAsChar As Integer
Returns the zero-based index position of the last occurrence of the specified Unicode
character within the current string object.
24
Public Function LastIndexOf valueAsString As Integer
Returns the zero-based index position of the last occurrence of a specified string within
the current string object.
25
Public Function Remove startIndexAsInteger As String
Removes all the characters in the current instance, beginning at a specified position and
continuing through the last position, and returns the string.
26
Public Function Remove startIndexAsInteger, countAsInteger As String
Removes the specified number of characters in the current string beginning at a specified
position and returns the string.
27
Public Function Replace oldCharAsChar, newCharAsChar As String
Replaces all occurrences of a specified Unicode character in the current string object with
the specified Unicode character and returns the new string.
28
Public Function Replace oldValueAsString, newValueAsString As String
Replaces all occurrences of a specified string in the current string object with the
specified string and returns the new string.
29
Public Function Split ParamArrayseparatorAsChar( ) As String
Returns a string array that contains the substrings in the current string object, delimited
by elements of a specified Unicode character array.
30
Public Function Split separatorAsChar(, count As Integer ) As String
Returns a string array that contains the substrings in the current string object, delimited
by elements of a specified Unicode character array. The int parameter specifies the
maximum number of substrings to return.
31
Public Function StartsWith valueAsString As Boolean
Determines whether the beginning of this string instance matches the specified string.
32
Public Function ToCharArray As Char
Returns a Unicode character array with all the characters in the current string object.
33
Public Function ToCharArray startIndexAsInteger, lengthAsInteger As Char
Returns a Unicode character array with all the characters in the current string object,
starting from the specified index and up to the specified length.
34
Public Function ToLower As String
35
Public Function ToUpper As String
36
Public Function Trim As String
Removes all leading and trailing white-space characters from the current String object.
The above list of methods is not exhaustive, please visit MSDN library for the complete list of
methods and String class constructors.
Examples:
The following example demonstrates some of the methods mentioned above:
Comparing Strings:
#include <include.h>
Module strings
Sub Main()
Dim str1, str2 As String
str1 = "This is test"
str2 = "This is text"
If (String.Compare(str1, str2) = 0) Then
Console.WriteLine(str1 + " and " + str2 +
" are equal.")
Else
Console.WriteLine(str1 + " and " + str2 +
" are not equal.")
End If
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Module strings
Sub Main()
Dim str1 As String
str1 = "This is test"
If (str1.Contains("test")) Then
Console.WriteLine("The sequence 'test' was found.")
End If
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Getting a Substring:
Module strings
Sub Main()
Dim str As String
str = "Last night I dreamt of San Pedro"
Console.WriteLine(str)
Dim substr As String = str.Substring(23)
Console.WriteLine(substr)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Joining Strings:
Module strings
Sub Main()
Dim strarray As String() = {"Down the way where the nights are gay",
"And the sun shines daily on the mountain top",
"I took a trip on a sailing ship",
"And when I reached Jamaica",
"I made a stop"}
Dim str As String = String.Join(vbCrLf, strarray)
Console.WriteLine(str)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Down the way where the nights are gay
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop
Processing math: 100%
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
ADO.NET provides consistent access to data sources such as SQL Server and XML, and to data
sources exposed through OLE DB and ODBC. Data-sharing consumer applications can use
ADO.NET to connect to these data sources and retrieve, handle, and update the data that they
contain.
ADO.NET separates data access from data manipulation into discrete components that can be
used separately. ADO.NET includes .NET Framework data providers for connecting to a
database, executing commands, and retrieving results. Those results are either processed directly,
placed in an ADO.NET DataSet object in order to be exposed to the user in an ad hoc manner,
combined with data from multiple sources, or passed between tiers. The DataSet object can also
be used independently of a .NET Framework data provider to manage data local to the
application or sourced from XML.
The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes
found in System.Xml.dll. For sample code that connects to a database, retrieves data from it, and
then displays that data in a console window.
ADO.NET provides functionality to developers who write managed code similar to the
functionality provided to native component object model (COM) developers by ActiveX Data
Objects (ADO). We recommend that you use ADO.NET, not ADO, for accessing data in your
.NET applications
Page 1 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
ADO ADO.NET
Data access ADO used connected data ADO.NET used
usage. (Connection- disconnected data
Oriented Models) environment. (Disconnected
Models)
XML Support In ADO XML Support is In ADO.NET XML robust
limited. Support.
Format of data transferring ADO used technology to ADO.NET uses xml for
access data and is COM – transmitting data to and
Based. from your database and web
application.
Data provider In ADO disconnected data In ADO.NET disconnected
provide by Record Set. data provide by DataSet and
DataAdpter.
Tables In ADO, Record Set, is like In ADO.NET DataSet, can
a single table or query contain multiple tables.
result.
Client connection In ADO client connection In ADO.NET client
model is very poor. Client disconnected as soon as the
application needs to be data is fetched or processed.
connected to data-sever DataSet is always
while working on the data. disconnected.
Advantages of ADO.NET
Interoperability
ADO.NET applications can take advantage of the flexibility and broad acceptance of XML.
Because XML is the format for transmitting datasets across the network, any component that can
read the XML format can process data. In fact, the receiving component need not be an
ADO.NET component at all: The transmitting component can simply transmit the dataset to its
destination without regard to how the receiving component is implemented. The destination
component might be a Visual Studio application or any other application implemented with any
tool whatsoever. The only requirement is that the receiving component be able to read XML. As
an industry standard, XML was designed with exactly this kind of interoperability in mind.
Maintainability
In the life of a deployed system, modest changes are possible, but substantial, architectural
changes are rarely attempted because they are so difficult. That is unfortunate, because in a
natural course of events, such substantial changes can become necessary. For example, as a
deployed application becomes popular with users, the increased performance load might require
Page 2 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
architectural changes. As the performance load on a deployed application server grows, system
resources can become scarce and response time or throughput can suffer. Faced with this
problem, software architects can choose to divide the server's business-logic processing and user-
interface processing onto separate tiers on separate machines. In effect, the application server tier
is replaced with two tiers, alleviating the shortage of system resources.
The problem is not designing a three-tiered application. Rather, it is increasing the number of
tiers after an application is deployed. If the original application is implemented in ADO.NET
using datasets, this transformation is made easier. Remember, when you replace a single tier with
two tiers, you arrange for those two tiers to trade information. Because the tiers can transmit data
through XML-formatted datasets, the communication is relatively easy.
Programmability
ADO.NET data components in Visual Studio encapsulate data access functionality in various
ways that help you program more quickly and with fewer mistakes. For example, data commands
abstract the task of building and executing SQL statements or stored procedures.
Similarly, ADO.NET data classes generated by the designer tools result in typed datasets. This in
turn allows you to access data through typed programming. The code for the typed dataset is
easier to read. It is also easier to write, because statement completion is provided.
Performance
For disconnected applications, ADO.NET datasets offer performance advantages over ADO
disconnected recordsets. When using COM marshalling to transmit a disconnected recordset
among tiers, a significant processing cost can result from converting the values in the recordset
to data types recognized by COM. In ADO.NET, such data-type conversion is not necessary.
Scalability
Because the Web can vastly increase the demands on your data, scalability has become critical.
Internet applications have a limitless supply of potential users. Although an application might
serve a dozen users well, it might not serve hundreds —or hundreds of thousands — equally
well. An application that consumes resources such as database locks and database connections
will not serve high numbers of users well, because the user demand for those limited resources
will eventually exceed their supply.
ADO.NET accommodates scalability by encouraging programmers to conserve limited
resources. Because any ADO.NET application employs disconnected access to data, it does not
retain database locks or active database connections for long durations.
Page 3 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
ADO.NET Architecture
Data processing has traditionally relied primarily on a connection-based, two-tier model. As data
processing increasingly uses multi-tier architectures, programmers are switching to a
disconnected approach to provide better scalability for their applications.
The two main components of ADO.NET 3.0 for accessing and manipulating data are the .NET
Framework data providers and the DataSet.
The DataSet
The ADO.NET DataSet is explicitly designed for data access independent of any data source. As
a result, it can be used with multiple and differing data sources, used with XML data, or used to
manage data local to the application. The DataSet contains a collection of one or more
DataTable objects consisting of rows and columns of data, and also primary key, foreign key,
Page 4 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
constraint, and relation information about the data in the DataTable objects. The following
diagram illustrates the relationship between a .NET Framework data provider and a DataSet.
The architecture of ADO.net, in which connection must be opened to access the data retrieved
from database is called as connected architecture. Connected architecture was built on the
classes connection, command, datareader and transaction.
DataReader : DataReader is used to store the data retrieved by command object and make
it available for .net application. Data in DataReader is read only and within the DataReader you
can navigate only in forward direction and it also only one record at a time.
To access one by one record from the DataReader, call Read() method of the DataReader whose
return type is bool. When the next record was successfully read, the Read() method will return
true and otherwise returns false.
Page 5 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
The architecture of ADO.net in which data retrieved from database can be accessed even when
connection to database was closed is called as disconnected architecture. Disconnected
architecture of ADO.net was built on classes connection, dataadapter, commandbuilder and
dataset and dataview.
Page 6 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
DataAdapter : DataAdapter is used to transfer the data between database and dataset. It
has commands like select, insert, update and delete. Select command is used to retrieve data from
database and insert, update and delete commands are used to send changes to the data in dataset
to database. It needs a connection to transfer the data.
DataSet : Dataset is used to store the data retrieved from database by dataadapter and make
it available for .net application.
To fill data in to dataset fill() method of dataadapter is used and has the following syntax.
Da.Fill(Ds,”TableName”);
When fill method was called, dataadapter will open a connection to database, executes select
command, stores the data retrieved by select command in to dataset and immediately closes the
connection.
As connection to database was closed, any changes to the data in dataset will not be directly sent
to the database and will be made only in the dataset. To send changes made to data in dataset to
the database, Update() method of the dataadapter is used that has the following syntax.
Da.Update(Ds,”Tablename”);
When Update method was called, dataadapter will again open the connection to database,
executes insert, update and delete commands to send changes in dataset to database and
immediately closes the connection. As connection is opened only when it is required and will be
automatically closed when it was not required, this architecture is called disconnected
architecture.
DataView : DataView is a view of table available in DataSet. It is used to find a record, sort
the records and filter the records. By using dataview, you can also perform insert, update and
delete as in case of a DataSet.
DataReader is Connected Architecture since it keeps the connection open until all rows are
fetched one by one
DataSet is DisConnected Architecture since all the records are brought at once and there is no
need to keep the connection alive
Page 7 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
connected can hold the data of single table disconnected can hold multiple tables of data
connected you need to use a read only
forward only data reader disconnected you cannot
Data Reader can't persist the data Data Set can persist the data
It is Read only, we can't update the data. We can update data
ADO.NET Components
There are two major components of ADO.NET:
1. DataSet
2. DataProvider
DataSet : represents either an entire database or a subset of database. It can contain tables and
relationships between those tables.
Data Provider is a collection of components like Connection, Command, DataReader,
DataAdapter objects and handles communication with a physical data store and the dataset.
Data Provider
The data provider is responsible for providing and maintaining the connection to the
database.
It is a set of classes that can be used for communicating with database, and
holding/manipulating data
The DataProvider connects to the data source on behalf of ADO.NET.
The data source can be Microsoft SQL Server or Oracle database and OLEDB data
provider.
The data provider components are specific to data source.
The following lists the .NET Framework data providers that are included in the .NET
Framework.
Page 8 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Page 9 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Namespaces
System.Data The System.Data namespace provides access to classes that represent the
ADO.NET architecture. ADO.NET lets you build components that
efficiently manage data from multiple data sources.
Classes that make up the .NET Framework Data Provider for OLE DB-
compatible data sources. These classes allow you to connect to an OLE
DB data source, execute commands against the source, and read the
results.
Classes that make up the .NET Framework Data Provider for SQL Server,
which allows you to connect to SQL Server 7.0, execute commands, and
Page 10 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Connection Object
A primary function of any database application is connecting to a data source and retrieving the
data that it contains. The .NET Framework data providers of ADO.NET serve as a bridge
between an application and a data source, allowing you to execute commands as well as to
retrieve data by using a DataReader or a DataAdapter. A key function of any database
application is the ability to update the data that is stored in the database
In ADO.NET you use a Connection object to connect to a specific data source by supplying
necessary information in a connection string. The Connection object you use depends on the
type of data source.
Each .NET Framework data provider included with the .NET Framework has a Connection
object: the .NET Framework Data Provider for OLE DB includes an OleDbConnection object,
the .NET Framework Data Provider for SQL Server includes a SqlConnection object, the .NET
Framework Data Provider for ODBC includes an OdbcConnection object, and the .NET
Framework Data Provider for Oracle includes an OracleConnection object.
Steps to connect database:
1. Create Database.
2. Start writing connection string in VB.Net.
3. Set the provider.
4. Specify the data source.
Connection object have ConnectionString property. Depends on the parameter specified in the
Connection String, ADO.Net Connection Object connect to the specified Database.
Properties :
Page 11 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Methods :
Close : Closes the connection to the data provider.
Open : Opens a database connection.
Command Object :
For Example
Str1 = "Insert into stud values(‘”+ TextBox1.Text +”’, ‘”+ TextBox1.Text +”’)
con.Open()
cmd = New SqlCommand(str1, con)
cmd.ExecuteNonQuery()
con.close()
OR
con.Open()
cmd.Connection = con
cmd.CommandText = “Insert into stud values(‘”+ TextBox1.Text +”’, ‘”+ TextBox1.Text +”’)”
cmd.ExecuteNonQuery()
con.close()
Properties
Property Meaning
CommandText Gets/sets the SQL statement (or stored procedure) for this
command to execute.
CommandType Gets/sets the type of the CommandText property (typically set
to text for SQL).
Connection Gets/sets the SqlConnection to use.
Page 12 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Page 13 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Methods
Methods Meaning
ExecuteNonQuery Executes a non-row returning SQL statement, returning the
number of affected rows.
ExecuteReader Creates a data reader using the command
ExecuteScalar Executes the command and returns the value in the first
column in the first row of the result.
DataAdapter Object :
The SqlDataAdapter, serves as a bridge between a DataSet and SQL Server for retrieving and
saving data. The SqlDataAdapter provides this bridge by mapping Fill, which changes the data
in the DataSet to match the data in the data source, and Update, which changes the data in the
data source to match the data in the DataSet, using the appropriate Transact-SQL statements
against the data source. The update is performed on a by-row basis. For every inserted, modified,
and deleted row, the Update method determines the type of change that has been performed on it
(Insert, Update, or Delete). Depending on the type of change, the Insert, Update, or Delete
command template executes to propagate the modified row to the data source.
When the SqlDataAdapter fills a DataSet, it creates the necessary tables and columns for the
returned data if they do not already exist. SqlDataAdapter is used in conjunction with
SqlConnection and SqlCommand to increase performance when connecting to a SQL Server
database.
The SqlDataAdapter also includes the SelectCommand, InsertCommand, DeleteCommand,
UpdateCommand properties to facilitate the loading and updating of data.
When an instance of SqlDataAdapter is created, the read/write properties are set to initial
values. For a list of these values, see the SqlDataAdapter constructor.
The InsertCommand, DeleteCommand, and UpdateCommand are generic templates that are
automatically filled with individual values from every modified row through the parameters
mechanism.
For every column that you propagate to the data source on Update, a parameter should be added
to the InsertCommand, UpdateCommand, or DeleteCommand. The SourceColumn property
of the DbParameter object should be set to the name of the column. This setting indicates that the
value of the parameter is not set manually, but is taken from the particular column in the
currently processed row.
Properties
Name Meaning
DeleteCommand Gets or sets a Transact-SQL statement or stored procedure to
delete records from the data set.
InsertCommand Gets or sets a Transact-SQL statement or stored procedure to
insert new records into the data source.
Page 14 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Methods Meaning
Fill Adds or updates rows in a data set to match those in the data source.
Creates a table named "Table" by default
Update Updates the data store by calling the INSERT, UPDATE, or DELETE
statements for each inserted, updated, or deleted row in the given dataset.
For Example :
Dim da As SqlDataAdapter
Dim ds As New DataSet
str1 = "select * from stud"
da = New SqlDataAdapter(str1, con)
da.Fill(ds)
DataSet Object
ADO.NET caches data locally on the client and store that data into DataSet.
The dataset is a disconnected, I-memory representation of data.
It’s not exact copy the database.
It can be considered as a local copy of the some portions of the database.
The DataSet contains a collection of one or more DataTable objects made up of rows and
columns of data.
Tables can be identified in DataSet using DataSet’s Tables property.
It also contains primary key, foreign key, constraint and relation information about the
data in the DataTable objects.
DataSet are also fully XML-featured.
Whaterer operations are made by the user it is stored temporary in the DataSet, when the
use of this DataSet is finished, changes can be made back to the central database for
updating.
DataSet doesn’t “know” where the data it contains came from and if fact it can contain
data from multiple sources.
The DataSet is populated DataAdapter’s Fill method.
The DataSet is a major component of the ADO.NET architecture. The DataSet consists of a
collection of DataTable objects that you can relate to each other with Data Relation objects. You
can also enforce data integrity in the DataSet by using the UniqueConstraint and
ForeignKeyConstraint objects. For further details about working with DataSet objects.
Page 15 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Whereas DataTable objects contain the data, the DataRelationCollection allows you to navigate
though the table hierarchy. The tables are contained in a DataTableCollection accessed through
the Tables property. When accessing DataTable objects, note that they are conditionally case
sensitive.
For example, if one DataTable is named "mydatatable" and another is named "Mydatatable", a
string used to search for one of the tables is regarded as case sensitive. However, if
"mydatatable" exists and "Mydatatable" does not, the search string is regarded as case
insensitive. For more information about working with DataTable objects.
A DataSet can read and write data and schema as XML documents. The data and schema can
then be transported across HTTP and used by any application, on any platform that is XML-
enabled. You can save the schema as an XML schema with the WriteXmlSchema method, and
both schema and data can be saved using the WriteXml method. To read an XML document that
includes both schema and data, use the ReadXml method.
In a typical multiple-tier implementation, the steps for creating and refreshing a DataSet, and in
turn, updating the original data are to:
1. Build and fill each DataTable in a DataSet with data from a data source using a
DataAdapter.
2. Change the data in individual DataTable objects by adding, updating, or deleting
DataRow objects.
3. Invoke the GetChanges method to create a second DataSet that features only the changes
to the data.
4. Call the Update method of the DataAdapter, passing the second DataSet as an argument.
5. Invoke the Merge method to merge the changes from the second DataSet into the first.
6. Invoke the AcceptChanges on the DataSet. Alternatively, invoke RejectChanges to
cancel the changes.
Properties
Name Description
Relations Get the collection of relations that link tables and allow navigation from parent
tables to child tables.
Tables Gets the collection of tables contained in the DataSet.
For Example :
Dim da As SqlDataAdapter
Dim ds As New DataSet
str1 = "select * from stud"
da = New SqlDataAdapter(str1, con)
da.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
Page 16 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
DataReader Object
Provides a way of reading a forward-only stream of rows from a SQL Server database
To create a SqlDataReader, you must call the ExecuteReader method of the SqlCommand
object, instead of directly using a constructor.
While the SqlDataReader is being used, the associated SqlConnection is busy serving the
SqlDataReader, and no other operations can be performed on the SqlConnection other than
closing it. This is the case until the Close method of the SqlDataReader is called. For example,
you cannot retrieve output parameters until after you call Close.
Changes made to a result set by another process or thread while data is being read may be visible
to the user of the SqlDataReader. However, the precise behavior is timing dependent.
IsClosed and RecordsAffected are the only properties that you can call after the SqlDataReader
is closed. Although the RecordsAffected property may be accessed while the SqlDataReader
exists, always call Close before returning the value of RecordsAffected to guarantee an accurate
return value.
Properties
Name Description
Connection Gets the SqlConnection associated with the SqlDataReader.
IsClosed Retrieves a Boolean value that indicates whether the specified SqlDataReader
instance has been closed. (Overrides DbDataReader.IsClosed.)
Item Overloaded. Gets the value of a column in its native format.
Methods
Name Description
Close Closes the SqlDataReader object. (Overrides DbDataReader.Close().)
Read Advances the SqlDataReader to the next record. (Overrides DbDataReader.Read().)
Page 17 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
cmd.Dispose()
con.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
DataGridView Control
The DataGridView control provides a powerful and flexible way to display data in a tabular
format. You can use the DataGridView control to show read-only views of a small amount of
data, or you can scale it to show editable views of very large sets of data.
You can extend the DataGridView control in a number of ways to build custom behaviors into
your applications. For example, you can programmatically specify your own sorting algorithms,
and you can create your own types of cells. You can easily customize the appearance of the
DataGridView control by choosing among several properties. Many types of data stores can be
used as a data source, or the DataGridView control can operate with no data source bound to it.
The DataGridView control provides a customizable table for displaying data. The
DataGridView class allows customization of cells, rows, columns, and borders through the use
of properties such as DefaultCellStyle, ColumnHeadersDefaultCellStyle, CellBorderStyle, and
GridColor.
You can use a DataGridView control to display data with or without an underlying data source.
Without specifying a data source, you can create columns and rows that contain data and add
them directly to the DataGridView using the Rows and Columns properties. You can also use
the Rows collection to access DataGridViewRow objects and the DataGridViewRow.Cells
property to read or write cell values directly. The Item indexer also provides direct access to
cells.
As an alternative to populating the control manually, you can set the DataSource and
DataMember properties to bind the DataGridView to a data source and automatically populate it
with data. For more information, see Displaying Data in the Windows Forms DataGridView
Control.
When working with very large amounts of data, you can set the VirtualMode property to true to
display a subset of the available data. Virtual mode requires the implementation of a data cache
from which the DataGridView control is populated. For more information, see Data Display
Modes in the Windows Forms DataGridView Control.
For additional information about the features available in the DataGridView control, see
DataGridView Control (Windows Forms). The following table provides direct links to common
tasks.
Page 18 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
DataGrid1.SetDataBinding(dsDataSet, "authors")
You can use these data sources with the data grid's DataSource property:
DataTable objects
DataView objects
DataSet objects
DataViewManager objects
single dimension arrays
To determine which cell was selected by the user, use the CurrentCell property. You can change
the value of any cell using the Item property, which can take either the row or column indexes of
the cell. And you can use the CurrentCell Changed event to determine when the user selects
another cell.
Example
First, you should add a DataGridView collection to your Windows Forms application by double-
clicking on the control name in the Visual Studio designer panel. After you add the control, you
can add the Load event on the form, which you can create from the Form's event pane.
Page 19 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
This event handler is executed when the program starts up and when the DataGridView control
is displayed. The Form1_Load autogenerated subroutine calls into the GetDataTable function,
which would return a DataTable from your database in SQL Server.
Assigning the DataSource property on DataGridView does not copy any data, but instead
allows the DataGridView to read in the DataTable and display all its contents on the screen in
grid form. This is often the most efficient way to populate DataGridView.
Explain the steps to bind the application with the Database in ADO .net using Binding
Navigator control
Step : 1 Take New VB.NET Project
Step : 2 Add two labels and two textbox on the form1
Step : 3 Add database in your project (Named : dbemp.mdf)
Add New Table in database file (Named : emp ) from the Server Explorer Window
Add some records in that table
Step : 4 Now add emp table to the DBEmpDataSet.xsd file
Step : 5 After creating table
Add BindingNavigator1 and BindingSource1 Control to the form
Step : 6 Now set the property of BindingSource1 control
DataSource = DBEmpDataSet
DateMember = emp
Step : 7 Now Set the property of BindingNavigator1 control
Right click on BindingNavigator1 control and select Edit Items…
Set BindingSource = BindingSource1
Then ok
Step : 8 Now Set the property of each textbox control
Select TextBox1 and set the DataBinding property
Click on Advanced property. The Formatting and Advanced Binding
Window is appeared. In this window set Binding = BindingSource1 – empno
Similarly, set all the textbox control
Step : 9 At the end, Run the project
Properties of BindingSource Control:
1) Datasource: Gets or sets the data source that the connector binds to.
Syntax: instance.DataSource = value
2) Datamember: Gets or sets the specific list in the data source to which the connector currently
binds to.
Page 20 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
ExecuteNonQuery
ExecuteNonQuery() is one of the most frequently used method in SqlCommand Object and is
used for executing statements that do not return result set. ExecuteNonQuery() performs Data
Definition tasks as well as Data Manipulation tasks also. The Data Definition tasks like creating
Stored Procedures and Views perform by ExecuteNonQuery() . Also Data Manipulation tasks
like Insert , Update and Delete perform by ExecuteNonQuery().
The following example shows how to use the method ExecuteNonQuery() through SqlCommand
Object.
sql = "Insert into stud values(‘”+ TextBox1.Text +”’, ‘”+ TextBox1.Text +”’)
Try
con.Open()
cmd = New SqlCommand(Sql, con)
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
MsgBox(" ExecuteNonQuery in SqlCommand executed !!")
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
ExecuteReader
ExecuteReader() in SqlCommand Object send the SQL statements to Connection Object and
populate a SqlDataReader Object based on the SQL statement. When the ExecuteReader method
in SqlCommand Object execute, it instantiate a SqlClient.SqlDataReader Object.
Page 21 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Try
con.Open()
cmd = New SqlCommand(sql, con)
reader = cmd.ExecuteReader()
While reader.Read()
MsgBox(reader.Item(0) & " - " & reader.Item(1))
End While
reader.Close()
cmd.Dispose()
con.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
ExecuteScaler
ExecuteScalar() in SqlCommand Object is used for get a single value from Database after its
execution. It executes SQL statements or Stored Procedure and returned a scalar value on first
column of first row in the Result Set. If the Result Set contains more than one columns or rows ,
it takes only the first column of first row, all other values will ignore. If the Result Set is empty it
will return a Null reference.
It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to
ExecuteReader() , ExecuteScalar() uses fewer System resources.
What are the four common SQL commands used to retrieve and modify data in a SQL
Database? Also explain each of them.
Page 22 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Select
Insert
Syntax:
Insert into TableName values(Value1,Value2,…)
Example :
Changes the values of individual columns in one or more existing rows in a table.
Syntax :
Update TableName set Columnname = value, ….
Update TableName set Columnname = value where <condition>
Example :
Update stud set sname = ‘xyz’ where sno = 1
Delete
Syntax :
Delete from TableName
Delete from TableName where <condition>
Example :
Page 23 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Unit-4
MCQ
1 ___________ is disconnected, in-memory representation of data.
a. DataReader b. DataSet
c. DataAdapter d. DataCommand
2 What is the major component of connected data architecture?
a. DataReader b. DataSet
c. DataAdapter d. DataCommand
3 ______________ method is used to populate DataSet.
a. Populate b. Fill
c.Open d. Store
4 ______________ method returns result set by way of DataReader object.
a. ExecuteDataReader b) ExecuteScalar
c. ExecuteNonQuery d) ExecuteReader
5 For insert, update, and delete SQL commands, ______________ method is used.
a. ExecuteDataReader b) ExecuteScalar
c. ExecuteNonQuery d) ExecuteReader
6 To check whether connection is open or not, ___________ property is used.
a. ConnectionStatus b) State
c. ConnectionState d) Status
7 To use DataSet __________________ namespace needs to be included.
a. System.Data.SqlClient b) System.Sql
c. System.Oledb d) System.Data
8 __________________ object provide connection to the database.
a. Command b) Connection
c. DataReader d) DataAdapter
9 In a connection string, _________________ represents name of the database.
a. DataSource b) Initial Database
c. Initial Catalog d) Catalog Database
10 If we are not returning any records from the database which method is used
a. ExecuteReader () b). ExecuteScalar ()
c. ExecuteXmlReader() d). ExecuteNonQuery()
11 Which namespace defines the interfaces implemented by a .NET Data Provider?
a. System.Data. b. System.Data.OleDb and
System.Data.SqlClient.
c. System.Data.SqlTypes. d. System.Data.Provider.
12 What are the two Data Providers provided with the .NET Framework?
a. OLEDB Data Provider and XML Data b. SQL Server Data Provider and XML Data
Provider. Provider.
c. OLEDB Data Provider and SQL Server d. SQL Server Data Provider and Oracle
Data Provider. Data Provider.
13 DataSet changes are saved to the database using the:
a. Save method. b. Update method.
c. Fill method. d. None of the above.
Page 24 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Page 25 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET
Short Questions
1 What are the features of ADO.Net?
2 What are the applications of ADO .net?
3 Explain the use of server explorer in data access in .net.
4 Mention the namespace that is used to include .NET Data Provider for SQL server in
.NET code.
5 Mention different types of data providers available in ADO .NET Framework.
6 Which namespaces are required to enable the use of databases in ADO .net?
7 What is the use of the Connection object?
8 What are the usages of the Command object in ADO.NET?
9 What is difference between DataSet and DataReader?
10 What is Dataset object?
11 What is connection string? Explain in brief.
12 Which properties are used to bind a DataGridView control?
13 Mention different types of data providers available in ADO .NET Framework.
14 Explain DataGrid control.
15 Explain any one of following namespaces
System.Data
System.Data.SqlClient
System.Data.OleDB
System.Data.SqlTypes
16 Explain any one of following .NET Data Provider Main Classes
Connection
Command
DataReader
DataAdapter
Long Questions:--
1 Explain the connected architecture of ADO.NET in brief.
2 Describe the disconnected architecture of ADO.NET's data access model.
3 Explain major ADO .net objects.
4 Explain the steps to bind the application with the Database in ADO .net.
5 Explain the step, how can we retrieve data in DataSet?
6 Explain public methods of SqlCommand objects
7 What are the four common SQL commands used to retrieve and modify data in a SQL
Database? Also explain each of them
8 Explain use of “ExecuteScalar” , “ExecuteNonQuery” and “ExecuteReader” method in
detail
Page 26 of 26