[go: up one dir, main page]

0% found this document useful (0 votes)
8 views219 pages

DOT NET

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 219

US05CCSC03 Unit-1: Visual Programming through VB .

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

Figure 1 An overview of the .NET architecture.

Here we examine the following key components of the .NET Framework:


1) Common Language Infrastructure (CLI): The purpose of the Common Language
Infrastructure (CLI) is to provide a language-neutral platform for application development
and execution, including functions for Exception handling, Garbage Collection, security, and
interoperability.
2) Common Language Runtime ( CLR ): The .NET Framework provides a runtime
environment called the Common Language Runtime or CLR (similar to the Java Virtual
Machine or JVM in Java), which handles the execution of code and provides useful services
for the implementation of the program.
The CLR is the execution engine for .NET applications and serves as the interface between .NET
applications and the operating system. The CLR provides many services such as:
 Loads and executes code
 Converts intermediate language to native machine code
 Manages memory and objects
 Enforces code and access security
 Handles exceptions
 Interfaces between managed code, COM objects, and DLLs
 Provides type-checking
 Provides code meta data (Reflection)
 Provides profiling, debugging, etc.
 Separates processes and memory

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)

7) Common Language Specification ( CLS )

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.

8) Microsoft Intermediate Language:


 When you compile your Visual Basic .NET source code, it is changed to an intermediate
language (IL) that the CLR and all other .NET development environments understand.
 All .NET languages compile code to this IL, which is known as Microsoft Intermediate
Language, MSIL, or IL.
 MSIL is a common language in the sense that the same programming tasks written with
different .NET languages produce the same IL code.
 At the IL level, all .NET code is the same regardless of whether it came from C++ or
Visual Basic.
 When a compiler produces Microsoft Intermediate Language (MSIL), it also produces
Metadata.
 The Microsoft Intermediate Language (MSIL) and Metadata are contained in a portable
executable (PE) file.
 Microsoft Intermediate Language (MSIL) includes instructions for loading, storing,
initializing, and calling methods on objects, as well as instructions for arithmetic and
logical operations, control flow, direct memory access, exception handling, and other
operations
Advantages :
 It offers cross− language integration, including cross− language inheritance, which
allows you to create a new class by deriving it from a base class written in another
language.
 It facilitates automatic memory management, known as garbage collection.
 compilation is much quicker
 It allows you to compile code once and then run it on any CPU and operating system
that supports the runtime.
Disadvantages:
 IL is not compiled to machine, so it can more easily be reverse engineered. Defense
mechanisms for handling this are likely to follow shortly after the .NET Framework is
officially released.
 While IL is further compiled to machine code, a tiny percentage of algorithms will
require a direct unwrapped access to system resources and hardware.

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.

Figure 2 : Following the IL

The Just-In-Time Compiler


 Your code does not stay IL for long, however. It is the PE file, containing the IL that can
be distributed and placed with the CLR running on the .NET Framework on any
operating system for which the .NET Framework exists, because the IL is platform
independent. When you run the IL, however, it is compiled to native code for that
platform. Therefore, you are still running native code. The compilation to native code
occurs via another tool of the .NET Framework: the Just-In-Time (JIT) compiler.
 With the code compiled, it can run within the Framework and take advantage of low level
features such as memory management and security. The compiled code is native code for
the CPU on which the .NET Framework is running. A JIT compiler will be available for
each platform on which the .NET Framework runs, so you should always be getting
native code on any platform running the .NET Framework.
 Just-in-time compilation (JIT), also known as dynamic translation, is a method to
improve the runtime performance of computer programs. Historically, computer
programs had two modes of runtime operation, either interpreted or static (ahead-of-time)
compilation. Interpreted code is translated from a high-level language to a machine code
continuously during every execution, whereas statically compiled code is translated into
machine code before execution, and only requires this translation once.
 JIT compilers represent a hybrid approach, with translation occurring continuously, as
with interpreters, but with caching of translated code to minimize performance
degradation. It also offers other advantages over statically compiled code at development
time, such as handling of late-bound data types and the ability to enforce security
guarantees.
 The Common Language Runtime (CLR) provides various Just In Time compilers (JIT)
and each works on a different architecture depending on Operating System. That is why
the same Microsoft Intermediate Language (MSIL) can be executed on different
Operating Systems without rewrite the source code.

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.

Figure 3 : A diagram of assembly


 Assemblies are made up of the following parts:
a) The assembly manifest
b) Type metadata
c) Microsoft Intermediate Language (MSIL) code
 The assembly manifest is where the details of the assembly are stored. The assembly is
stored within the DLL or EXE itself. Assemblies can either be single or multiple file
assemblies and, therefore, assembly manifests can either be stored in the assembly or as a
separate file. The assembly manifest also stores the version number of the assembly to
ensure that the application always uses the correct version.
 The metadata contains information on the types that are exposed by the assembly such as
security permission information, class and interface information, and other assembly
information.
Contents of an Assembly:
a) Assembly Manifest
b) Assembly Name
c) Version Information
d) Types
e) Cryptographic Hash
f) Security Permissions
An assembly does the following functions:
 It contains the code that the runtime executes.
 It forms a security boundary. An assembly is the unit at which permissions are requested
and granted.
 It forms a type boundary. Every type’s identity includes the name of the assembly at
which it resides.

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.

Figure 4: .Net namespaces


VB.NET - Introduction
 Microsoft .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.
 This is how Microsoft describes it: “.NET is the Microsoft Web services strategy to
connect information, people, systems, and devices through software. Integrated across the
Microsoft platform, .NET technology provides the ability to quickly build, deploy,
manage, and use connected, security-enhanced solutions with Web services.
 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.
 Visual Basic 2008 version 9.0 was released together with the Microsoft .NET Framework
3.5

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.

Compilation and Execution

Figure 5: Compilation and Execution Process


Solutions and Projects
 In VB.Net project groups are known as solutions.
 By default, when you create a new project in VB.Net, then visual basic creates a new
solution first and then adds a project to that solution.
File Extensions used in VB.Net
 When you save a solution, the file extension is “.sln” and all projects in the solution are
saved with extension “.vbproj”.
 Most popular file extension is “.vb”

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)

The Visual Basic projects you can create are as follows:


 Windows Application Windows standard thick client applications based on forms (EXE)
 Class Library For individual classes or collections of classes (DLL)
 Windows Control Library Controls and components for Windows Forms (classic)

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

Visual Basic Integrated Development Environment:


Start Page
 User can use the start page to select from recent projects
 By default ‘Get Started’ item is selected in the start page.
 User can create new project or open existing project from recent project item.
Toolbars
 This feature is another handy aspect of the IDE.
 These appear near the top of the IDE.
 IDE displays tool tips, it becomes easy to know which button performs which operation.
 Toolbars provides a quick way to select menu item.
Graphical Designer
 VB.Net can display those elements which will look like at run time.
 Different types of graphical designers including.
a) windows form designers
b) web form designers
c) compact designers
d) XML designers
 From tools menu  select options  options dialog box will open from that select
“Window Form Designer” folder display possible options.

The Object Explorer


 This tool lets you look at all the members of an object at once
 The Object Explorer helps open up any mysterious objects that Visual Basic has added to
your code so you can see what's going on inside.
 To open the Object Explorer, select View Other Windows Object Explorer
 The Object Explorer shows all the objects in your program and gives you access to what's
going on in all of them.

Page 11 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET

Figure 6: VB .NET IDE


The Menu
 Visual Studio .NET's menu is dynamic, meaning that items will be added or removed
depending on what you are trying to do. The menu bar consist of the following options:

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.

Figure 7: Code Designer Window


IntelliSense
 One useful feature of VB .NET code designers is Microsoft's IntelliSense. IntelliSense are
those boxes that open as you write your code, listing all the possible options and even
completing your typing for user.
 IntelliSense is made up of a number of options, including:
 List Members-Lists the members of an object.
 Parameter Info-Lists the arguments of procedure calls.
 Quick Info-Displays information in tool tips as the mouse rests on elements in your code.
 Complete Word-Completes typed words.
 Automatic Brace Matching-Adds parentheses or braces as needed.
 you can turn various parts of IntelliSense off if you want; just select the Tools  Options
menu item, then select the Text Editor folder, then the Basic subfolder, and finally the
General item in the Basic subfolder.

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.

The Solution Explorer


 It is available on right top corner of IDE
 This tool displays a hierarchy-with the solution at the top of the hierarchy, the projects
one step down in the hierarchy, and the items in each project as the next step down.
 You can set the properties of various items in a project by selecting them in the Solution
Explorer and then setting their properties in the properties window. And you can set
properties of solutions and projects by right-clicking them and selecting the Properties
item in the menu that appears, or you can select an item and click the properties button,
which is the right-most button at the top of the Solutions Explorer.
 User can switch between graphical and code designers by using the buttons that appear at
top left in the Solution Explorer
 You can right-click a solution and add a new project to it by selecting the AddNew
Project menu item in the popup menu that appears. And you can specify which of
multiple projects runs first-that is, is the startup project or projects-by right-clicking the
project and selecting the Set As Startup Object item, or by right-clicking the solution and
selecting the Set Startup Projects item.
 With this tool user can also add new item
 By clicking on see all button, solution explorer will shows all files available with current
project.

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.

Object Explorer Window


 The object explorer window allows us to view all the members of an object at once. It
lists all the objects in our code and gives us access to them. The image below displays an
object explorer window. You can view the object explorer window by selecting View-
>Other Windows-> Object Browser from the main menu.
Data Types:
 The following are the data type supported by VB.Net .
 Numeric Data Type(Short, Integer, Long, Single, Double, Decimal)
 Character Data Type (Char, String)
 Miscellaneous Data Type( Boolean , Byte, Date, Object)

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

Variable name should follow the following rules:


 Begin with a letter or _.
 Must contain atleast one numeric digit or alphabetic character.
 Maximun 1023 characters are allowed.
 It must be unique in its scope.
 In VB.NET each variable contains default value depends on its data type.
 Default value for Numeric and Byte data type is 0(zero).
 Default value for Char data type is Binary 0(zero).
 Default value for all reference types like object, string, and arrays is Nothing.
 Default value for Boolean data type is False.
 Default value for Date data type is 12:00 AM of 1,1,0001.
Constant Declaration:
Declares and defines one or more constants.
Syntax: Const constantlist
Each constant has the following syntax and parts:
constantname[ As datatype ] = initializer
constantlist : Required. List of constants being declared in this statement. Constant
[ , constant ... ]
Constantname: It is required. It specifies the name of the constant.
Datatype: It specifies the type of constant.
Initialize: it is required. The value which is assigned to the constant. Once you initialize the
constant variable with a value it can never change.
Ex: Const pi as double = 3.24

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

 Unary used with a single operand for example Ans= -10

 Binary used with two operands for example Ans= 10 / 5

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

Dim box As Object = 12


Dim i As Integer = CInt(box)
conceptually correspond to
Dim box = New int_Box(12)
Dim i As Integer = CType(box, int_Box).value.

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.

Redim Statement: It reallocates storage space for array variables.


Syntax: ReDim [Preserve] name(boundlist) [, name(boundlist) …]
Preserve: It is optional. It is used to preserve the data in an existing array when user changes the
size of the last dimension.

Name: The name of the array variable.


Boundlist: It is required. It is dimensions of an array variable.
Example:

Dim a() As Integer


Private Sub cmdInput_Click()
ReDim a(5) As Integer
For i = LBound(a) To UBound(a)
a(i) = InputBox("Enter elements:")
Next

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.

Syntax: InStr([start, ]string1, string2[, compare])

The InStr function syntax has these arguments:

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.

string1 Required. String expression being searched.

string2 Required. String expression sought.

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.

Settings: The Compare argument settings are:

Constant Value Description

Binary 0 Performs a binary comparison

Text 1 Performs a text comparison

Return Value

If InStr returns

String1 is zero length or Nothing 0

String2 is zero length or Nothing start

String2 is not found 0

String2 is found within String1 Position where match begins

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.

5) Lcase: It returns a String that has been converted to lowercase.

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”)

11) Strcomp: It returns -1, 0, or 1, based on the result of a string comparison.


Syntax: Strcomp(string1,string2[,compare])
String1 :Required. Any valid String expression.
String2 :Required. Any valid String expression.
Compare :Optional. Specifies the type of string comparison. If Compare is omitted, the Option
Compare setting determines the type of comparison.
The Compare argument settings are:

Return Value:The StrComp function has the following return values.

If StrComp returns

String1 sorts ahead of String2 -1

String1 is equal to String2 0

String1 sorts after String2 1


Example:
Dim TestStr1 As String = "ABCD"
Dim TestStr2 As String = "abcd"
Dim TestComp As Integer
' The two strings sort equally. Returns 0.
TestComp = StrComp(TestStr1, TestStr2, CompareMethod.Text)
' TestStr1 sorts after TestStr2. Returns -1.
TestComp = StrComp(TestStr1, TestStr2, CompareMethod.Binary)
' TestStr2 sorts before TestStr1. Returns 1.
TestComp = StrComp(TestStr2, TestStr1)

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.

Example: S1= “Shopping List”


Msgbox Replace( s1, “o”,”I”)

Tostring with its Methods:


1) ToString.Concat: This method is used Concatenates three specified instances of String.

Syntax : System.String.Concat(str1,str2)

str1 : Parameter String

str2 : Parameter String

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

str1 = "Concat() "


str2 = "Test"
MsgBox(String.Concat(str1, str2))
End Sub
End Class
2) String.copy : This method creates a new instance of String with the same value as a
specified String.

Syntac: System.String.Copy(str)

str : The argument String for Copy method


Example:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str1 As String
Dim str2 As String

str1 = "VB.NET Copy() test"


str2 = String.Copy(str1)
MsgBox(str2)
End Sub
End Class
3) String.Indexof: It returns the index of the first occurrence of the specified substring.

Syntax: System.String.IndexOf(str)

str - The parameter string to check its occurrences

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:

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
str = "VB.NET TOP 10 BOOKS"
MsgBox(str.IndexOf("BOOKS"))
End Sub
End Class
4) String.substring: It returns a new string that is a substring of this string. The substring
begins at the specified given index and extended up to the given length.

Page 27 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
Syntax: Substring(startIndex,length)

startIndex: The index of the start of the substring.

length: The number of characters in the substring.

Example:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

Dim str As String


Dim retString As String
str = "This is substring test"
retString = str.Substring(8, 9)
MsgBox(retString)

End Sub
End Class

5) String.format: VB.NET String Format method replace the argument Object into a text
equivalent System.Striing.

Syntax: System.Format(format, arg0)

String format : The format String

The format String Syntax is like {indexNumber:formatCharacter}

Object arg0 : The object to be formatted.

Examples:

Currency : String.Format("{0:c}", 10) will return $10.00

The currency symbol ($) displayed depends on the global locale settings.

Date : String.Format("Today's date is {0:D}", DateTime.Now)

You will get Today's date like : 01 January 2005

Time : String.Format("The current time is {0:T}", DateTime.Now)

You will get Current Time Like : 10:10:12

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim dNum As Double
Page 28 of 29
US05CCSC03 Unit-1: Visual Programming through VB .NET
dNum = 32.123456789
MsgBox("Formated String " & String.Format("{0:n4}", dNum))
End Sub
End Class
6) String.ToUpper: This method uses the casing rules of the current culture to convert each
character in the current instance to its uppercase equivalent. If a character does not have an
uppercase equivalent, it is included unchanged in the returned string.

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

The Code Gallery


MENU

Remove makeup in just 1 swipe.


Get rid of all makeup with minimal effort. No harsh chemicals, colour and added LEARN MORE
perfume Simple

VB.NET Tutorial

Basic Concepts

VB.NET Variable (index.php)


VB.NET Constant (Constant.php)
VB.NET Operators (Operator.php)
VB.NET DataTypes (DataType.php)
VB.NET Control Structure (ControlStructure.php)
VB.NET Looping Structure (LoopingStructure.php)
VB.NET Array (Array.php)
VB.NET Procedure (Procedure.php)
Event Procedure (Event.php)
Function Procedure (Function.php)
General Procedure (General.php)
Pass by Value/Ref (PassValue.php)

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)

VB.NET Built in Functions

InputBox (InputBox.php)
MsgBox (MsgBox.php)

Button Control in VB.NET


Example of Button Control in VB.NET
(TextBoxExample.php)
www.thecodegallery.com/VBNET/Button.php 2/6
7/13/2019 Button Control in VB.NET
Button is a widely used control in window application.
It is used to perform an action.
Whenever user clicks on a Button the click event associated with the Button is fired and the action
associated with the event is executed.

Properties of Button Control

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.

SPONSORED SEARCHES SPONSORED SEARCHES SPONSORED SEARCHES

CSS Templates Alignment Check Basic CSS Code

Display Pop Up And VB Net Basic Style

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

Image It is used to specify an image that is displayed in Button Control.

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.

Methods of Button Control in VB.NET

Method Purpose
Show It is used to show Button control at run time.

Hide It is used to hide Button control at run time.

Focus It is used to set input focus on Button Control at run time.

Event of Button Control in VB.NET

Event Purpose
Click It is the default event of Button Control. It fires each time user clicks on Button Control.

Download Projects

Download PHP & MySQL Project (../PHP/Download.php)

www.thecodegallery.com/VBNET/Button.php 4/6
7/13/2019 Button Control in VB.NET
Download VB.NET Projects (Download.php)

Download Android Projects (../Android/Download.php)

Download Programs

Download C Programs (../C/Download.php)

Download C++ Programs (../CPP/Download.php)

Download Data Structure Program (../DSM/Program.php)

Download Data Structure Algorithm (../DSM/Algorithm.php)

www.thecodegallery.com/VBNET/Button.php 5/6
7/13/2019 Button Control in VB.NET

Best Free
Android
Emulator
Tencent Gaming Buddy

O cial Free Fire emulator for PC

DOWNLOAD

Site built with Simple Responsive Template (http://www.prowebdesign.ro/simple-responsive-template/)

www.thecodegallery.com/VBNET/Button.php 6/6
7/13/2019 InputBox Function in VB.NET

The Code Gallery


MENU

VB.NET Tutorial

Basic Concepts

VB.NET Variable (index.php)


VB.NET Constant (Constant.php)
VB.NET Operators (Operator.php)
VB.NET DataTypes (DataType.php)
VB.NET Control Structure (ControlStructure.php)
VB.NET Looping Structure (LoopingStructure.php)
VB.NET Array (Array.php)
VB.NET Procedure (Procedure.php)
Event Procedure (Event.php)
Function Procedure (Function.php)
General Procedure (General.php)
Pass by Value/Ref (PassValue.php)

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)

VB.NET Built in Functions

InputBox (InputBox.php)
MsgBox (MsgBox.php)

InputBox Function in VB.NET

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.

InputBox (Prompt As String,[Title As String=""], [DefaultResponse As


String=""], [XPos As Integer = -1], [YPos As integer = -1] ) As String
Here,
(1) Prompt is a compulsory argument. The String that you specify as a Prompt will
display as a message in the InputBox Dialog.
(2) Title is an optional Argument. The String that you specify as a Title will display in
the title bar of the InputBox. If you skip this argument then name of the application
will display in the title bar.
Shipping quote real time
Ad Get container shipment quotes the
fast, easy and convenient way. 24/7 –…
Hapag-Lloyd

Learn more

(3) DefaultResponse is an Optional Argument. The String that you specify as a


DefaultResponse will display as a default value in the textbox of the InputBox. If you
skip this argument then Textbox of the InputBox is displayed empty.
(4) XPos is an Optional Argument. It Specify the distance (in pixel) of the left edge
of the Input box from the left edge of the screen.
(5) YPos is an Optional Argument. It Specify the distance (in pixel) of the upper
edge of the Input box from the top edge of the screen.
Note: If you skip XPos and YPos then InputBox will display in the centre of the
screen.

www.thecodegallery.com/VBNET/InputBox.php 3/6
7/13/2019
SPONSORED SEARCHES InputBox Function in VB.NET
SPONSORED SEARCHES SPONSORED SEARCHES

Display Pop Up Array Data Structure Basic Programming

App Programing Software Basic Coding Basic Variables

Example of InputBox Function in VB.NET

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:

Step 2: Now set properties of various controls as given below:

Control Name Property Name Value


Form1 Text Input Box Function Demo

Button1 Name cmdName

Text Click To Enter Name

Label1 Text Your Name Is:

Label2 Name lblName

Text Name

Step 3: Now Double click on Click To Enter Name Button and write following code display Input Box
and enter name.

lblName.Text = InputBox ("Enter Your Name", "Name", "", 100, 100)

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 VB.NET Projects (Download.php)

Download Android Projects (../Android/Download.php)

Download Programs

Download C Programs (../C/Download.php)

Download C++ Programs (../CPP/Download.php)

Download Data Structure Program (../DSM/Program.php)

Download Data Structure Algorithm (../DSM/Algorithm.php)

www.thecodegallery.com/VBNET/InputBox.php 5/6
7/13/2019 InputBox Function in VB.NET

Site built with Simple Responsive Template (http://www.prowebdesign.ro/simple-responsive-template/)

www.thecodegallery.com/VBNET/InputBox.php 6/6
7/13/2019 MessageBox Function in VB.NET

The Code Gallery


MENU

VB.NET Tutorial

Basic Concepts

VB.NET Variable (index.php)


VB.NET Constant (Constant.php)
VB.NET Operators (Operator.php)
VB.NET DataTypes (DataType.php)
VB.NET Control Structure (ControlStructure.php)
VB.NET Looping Structure (LoopingStructure.php)
VB.NET Array (Array.php)
VB.NET Procedure (Procedure.php)
Event Procedure (Event.php)
Function Procedure (Function.php)
General Procedure (General.php)
Pass by Value/Ref (PassValue.php)

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)

VB.NET Built in Functions

InputBox (InputBox.php)
MsgBox (MsgBox.php)

Message Box Function in VB.NET


The show method of MessageBox is used to display User Specific message in a Dialog Box and
waits for the user to click a button.
It returns an integer value indicating which button is click by user.
www.thecodegallery.com/VBNET/MsgBox.php 2/5
7/13/2019 MessageBox Function in VB.NET
MessageBox is shown in the figure below:

MessageBox.Show (Text As String, Caption As String, Buttons As


System.Windows.Forms.MeesageBoxButtons, Icon As
System.Windows.Forms.MessageBoxIcon) As
System.Windows.Forms.DialogResult
Here,
(1) Text is a compulsory argument. The String that you specify as a Text will display
as a message in the Dialog Box.
(2) Caption is a compulsory argument. The String that you specified as a caption
will be display in the title bar of the Dialog Box.
(3) Buttons is used to specify type of buttons to display in the message box.
(4) Icon is used to specify type of icon to display in the message box.

SPONSORED SEARCHES SPONSORED SEARCHES SPONSORED SEARCHES

Display Pop Up And VB Net Basic Java for Beginners

Alert Button for Seniors Array Data Structure Basic PHP Code

Possible values for Button argument are

MessageBoxButtons.OKOnly Display OK Button.

MessageBoxButtons.OKCancel Display OK and Cancel Button.

MessageBoxButtons.AbortRetryIgnore Display Abort, Retry and Ignore Button.

MessageBoxButtons.YesNoCancel Display Yes, No and Cancel Button.

MessageBoxButtons.YesNo Display Yes and No Button.

MessageBoxButtons.CancelRetry Display Cancel and Retry Button.

Possible values for Icon argument are:

MessageBoxIcon.Critical Display Critical icon.


www.thecodegallery.com/VBNET/MsgBox.php 3/5
7/13/2019 MessageBox Function in VB.NET
MessageBoxIcon.Question Display Question icon.

MessageBoxIcon.Exclamation Display Exclamation icon.

MessageBoxIcon.Information Display Information icon.

Example of MessageBox Function in VB.NET

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 2: Now set properties of various controls as given below:

Control Name Property Name Value


Form1 Text MsgBox Function Demo

Button1 Name cmdClose

Text Close Form

Step 3: Now Double click on Close Form Button and write following code display Message Box.

If MessageBox.Show("Close Form?", "Confirmation", MessageBoxButtons.YesNo,


MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
Me.Close()
End If

Download Projects

Download PHP & MySQL Project (../PHP/Download.php)

Download VB.NET Projects (Download.php)


www.thecodegallery.com/VBNET/MsgBox.php 4/5
7/13/2019 MessageBox Function in VB.NET
Download Android Projects (../Android/Download.php)

Download Programs

Download C Programs (../C/Download.php)

Download C++ Programs (../CPP/Download.php)

Download Data Structure Program (../DSM/Program.php)

Download Data Structure Algorithm (../DSM/Algorithm.php)

Site built with Simple Responsive Template (http://www.prowebdesign.ro/simple-responsive-template/)

www.thecodegallery.com/VBNET/MsgBox.php 5/5
8/24/2020 NumericUpDown Control in VB.NET

HOME EXPLORE TAGS CONTRIBUTE

Give your website a


good home.
Your website's hosting plan ma
Trust yours with the best.
GoDaddy.com

SPONSORED SEARCHES
visual basic vb net code

basic coding resize photo

Home » VB.NET » WINDOWS CONTROLS CA


NumericUpDown Control In VB.NET AC

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())

Minimum and Maximum Range

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

Give your website a good home. M

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

this.numericUpDown1.Loca on = New System.Drawing.Point(26, 12) Ve


this.numericUpDown1.Name = "numericUpDown1"
this.numericUpDown1.Size = New System.Drawing.Size(228, 20) Ho
this.numericUpDown1.TabIndex = 0
Co
Once the NumericUpDown control is ready with its proper es, the next step is to add the NumericUpDown to a Form. To do so, we use Co
Form.Controls.Add method that adds NumericUpDown control to the Form controls and displays on the Form based on the loca on and size
of the control. The following code snippet adds a NumericUpDown control to the current Form. Co

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 on and Increment

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

dynamicUpDown.Accelera ons.Add(New NumericUpDownAccelera on(2, -5))

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

TERMS & CONDITIONS | CONTACT US | REPORT ABUSE

https://www.dotnetheaven.com/article/numericupdown-control-in-vb.net 9/9
8/24/2020 NumericUpDown Control in VB.NET

Give your website a good home.


Choose from several fast, reliable web hosting plans to meet your unique
needs.
Name property represents a unique name of a NumericUpDown control. It is used to access the control in the code. The following code
snippet sets and gets the name and text of a NumericUpDown control.

dynamicUpDown.Name = "DynamicUpDownBu on"

Loca on, Height, Width and Size

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.

dynamicUpDown.Loca on = New System.Drawing.Point(12, 50)


dynamicUpDown.Width = 200
dynamicUpDown.Height = 25

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.

dynamicUpDown.Font = New Font("Georgia", 12)

Foreground and Background

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.

Properties of the CheckBox Control


The following are some of the commonly used properties of the CheckBox control:

S.N Property Description

1 Appearance Gets or sets a value determining the appearance of the check


box.

2 AutoCheck Gets or sets a value indicating whether the Checked or


CheckedState value and the appearance of the control
automatically change when the check box is selected.

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.

5 CheckState Gets or sets the state of a check box.

6 Text Gets or sets the caption of a check box.

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:

S.N Method Name & Description

1
OnCheckedChanged

Raises the CheckedChanged event.

2
OnCheckStateChanged

Raises the CheckStateChanged event.

3
OnClick

Raises the OnClick event.

Events of the CheckBox Control


The following are some of the commonly used events of the CheckBox control:

S.N Event Description

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.

3 CheckStateChanged Occurs when the value of the CheckState 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.

The form in design view:


Let's put the following code in the code editor window:

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
Label1.Visible = False
TextBox1.Visible = False
TextBox1.Multiline = True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
Dim str As String
str = " "
If CheckBox1.Checked = True Then
str &= CheckBox1.Text
str &= " "
End If
If CheckBox2.Checked = True Then
str &= CheckBox2.Text
str &= " "
End If
If CheckBox3.Checked = True Then
str &= CheckBox3.Text
str &= " "
End If
If CheckBox4.Checked = True Then
str &= TextBox1.Text
str &= " "
End If
If str <> Nothing Then
MsgBox(str + vbLf + "Thank you")
End If
End Sub
Private Sub CheckBox4_CheckedChanged(sender As Object, _
e As EventArgs) Handles CheckBox4.CheckedChanged
Label1.Visible = True
TextBox1.Visible = True
End Sub
End Class

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

Clicking the Submit button:


VB.NET - LABEL CONTROL
http://www.tutorialspoint.com/vb.net/vb.net_label.htm Copyright © tutorialspoint.com

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.

Properties of the Label Control


The following are some of the commonly used properties of the Label control:

S.N Property Description

1 Autosize Gets or sets a value specifying if the control should be


automatically resized to display all its contents.

2 BorderStyle Gets or sets the border style for the control.

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.

5 FontHeight Gets or sets the height of the font of the control.

6 ForeColor Gets or sets the foreground color of the control.

7 PreferredHeight Gets the preferred height of the control.

8 PreferredWidth Gets the preferred width of 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.

10 Text Gets or sets the text associated with this control.

11 TextAlign Gets or sets the alignment of text in the label.

Methods of the Label Control


The following are some of the commonly used methods of the Label control:
S.N Method Name & Description

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

Activates the control.

4
Show

Displays the control to the user.

5
ToString

Returns a String that contains the name of the control.

Events of the Label Control


The following are some of the commonly used events of the Label control:

S.N Event Description

1 AutoSizeChanged Occurs when the value of the AutoSize property changes.

2 Click Occurs when the control is clicked.

3 DoubleClick Occurs when the control is double-clicked.

4 GotFocus Occurs when the control receives focus.

5 Leave Occurs when the input focus leaves the control.

6 LostFocus Occurs when the control loses focus.

7 TabIndexChanged Occurs when the TabIndex property value changes.

8 TabStopChanged Occurs when the TabStop property changes.

9 TextChanged Occurs when the Text property value changes.

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.

Take the following steps:

1. Drag and drop a Label control on the form.

2. Set the Text property to provide the caption "This is a Label Control".

3. Set the Font property from the properties window.

4. Click the label to add the Click event in the code window and add the following codes.

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) _


Handles MyBase.Load
' Create two buttons to use as the accept and cancel buttons.
' Set window width and height
Me.Height = 300
Me.Width = 560

' Set the caption bar text of the form.


Me.Text = "tutorialspont.com"
' Display a help button on the form.
Me.HelpButton = True
End Sub

Private Sub Label1_Click(sender As Object, e As EventArgs) _


Handles Label1.Click
Label1.Location = New Point(50, 50)
Label1.Text = "You have just moved the label"
End Sub
Private Sub Label1_DoubleClick(sender As Object, e As EventArgs)
Handles Label1.DoubleClick
Dim Label2 As New Label
Label2.Text = "New Label"
Label2.Location = New Point(Label1.Left, Label1.Height + _
Label1.Top + 25)
Me.Controls.Add(Label2)
End Sub
End Class

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

Clicking 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.

Properties of the RadioButton Control


The following are some of the commonly used properties of the RadioButton control:

S.N Property Description

1 Appearance Gets or sets a value determining the appearance of the radio


button.

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.

4 Checked Gets or sets a value indicating whether the control is checked.

5 Text Gets or sets the caption for a radio button.

6 TabStop Gets or sets a value indicating whether a user can give focus to
the RadioButton control using the TAB key.

Methods of the RadioButton Control


The following are some of the commonly used methods of the RadioButton control:

S.N Method Name & Description

1
PerformClick

Generates a Click event for the control, simulating a click by a user.

Events of the RadioButton Control


The following are some of the commonly used events of the RadioButton control:

S.N Event Description

1 AppearanceChanged Occurs when the value of the Appearance property of the


RadioButton control is changed.

2 CheckedChanged Occurs when the value of the Checked property of the


RadioButton control is changed.

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.

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub

Private Sub RadioButton1_CheckedChanged(sender As Object, _


e As EventArgs) Handles RadioButton1.CheckedChanged
Me.BackColor = Color.Red
End Sub
Private Sub RadioButton2_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton2.CheckedChanged
Me.BackColor = Color.Green
End Sub
Private Sub RadioButton3_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton3.CheckedChanged
Me.BackColor = Color.Blue
End Sub

Private Sub RadioButton4_CheckedChanged(sender As Object, _


e As EventArgs) Handles RadioButton4.CheckedChanged
Me.ForeColor = Color.Black
End Sub
Private Sub RadioButton5_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton5.CheckedChanged
Me.ForeColor = Color.White
End Sub
Private Sub RadioButton6_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton6.CheckedChanged
Me.ForeColor = Color.Red
End Sub
End Class

When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window:
7/2/2019 VB.NET working with Windows Form and Events in Visual Basic .NET

HOME EXPLORE TAGS CONTRIBUTE

Sea

Home » VB.NET » WINDOWS FORMS IN VB.NET CA


VB.NET Working With Windows Form And Events In Visual AC

Basic .NET AL

Posted in VB.NET | WINDOWS FORMS IN VB.NET on November 09, 2012 AR


Tags: Appearance proper es, click event, Events in vb.net, layout proper es AS

In this ar cle, I will explain you about working with Windows Form and Events in Visual Basic .NET. AS

AS
2417
CO

Working with Forms CR

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

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load SE

SI
End Sub
End Class SP
You can also write code in the load event of the form, I show you how: ST

Public Class Form1 TA

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load VB


MessageBox.Show("Press this bu on to load the form")
https://www.dotnetheaven.com/article/vb.net-working-with-windows-form-and-events-in-visual-basic 1/4
7/2/2019 VB.NET working with Windows Form and Events in Visual Basic .NET
End Sub VB
End Class
VB
When you write this code in the load event and by selec ng Debug->Start from the main menu(F5) to run the applica on, the
message box is displayed on your screen with a text you wri en in the Show() method and bu on named OK. It looks like the VB
image below:
VB
img1.gif VB

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

Private Sub Bu on1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles Bu on1.Click Ca


TextBox1.Text = "This is my first Form"
St
End Sub
End Class Ta
Image of the Output is given below: Dy

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

Introduc on of DataGrid Control in VB.NET Use of shadows keyword in VB.NET Cr


Forms Task Changes in VB.NET TextBox in VB.NET Ad
MustInherit in VB.NET Tab Control in VB.NET
St
Bu on in VB.NET DateTimePicker Control in VB.NET
As
Date and Time in Window Applica on in VB.NET Mouse Event Handler in VB.NET
Ge

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

PRIVACY POLICY | TERMS & CONDITIONS | CONTACT US | REPORT ABUSE

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.

The Properties of the TextBox Control


The following are some of the commonly used properties of the TextBox control:

S.N Property Description

1 AcceptsReturn Gets or sets a value indicating whether pressing ENTER


in a multiline TextBox control creates a new line of text
in the control or activates the default button for the
form.

2 AutoCompleteCustomSource Gets or sets a custom


System.Collections.Specialized.StringCollection to use
when the AutoCompleteSourceproperty is set to
CustomSource.

3 AutoCompleteMode Gets or sets an option that controls how automatic


completion works for the TextBox.

4 AutoCompleteSource Gets or sets a value specifying the source of complete


strings used for automatic completion.

5 CharacterCasing Gets or sets whether the TextBox control modifies the


case of characters as they are typed.

6 Font Gets or sets the font of the text displayed by the control.

7 FontHeight Gets or sets the height of the font of the control.

8 ForeColor Gets or sets the foreground color of the control.

9 Lines Gets or sets the lines of text in a text box control.


10 Multiline Gets or sets a value indicating whether this is a
multiline TextBox control.

11 PasswordChar Gets or sets the character used to mask characters of a


password in a single-line TextBox control.

12 ReadOnly Gets or sets a value indicating whether text in the text


box is read-only.

13 ScrollBars Gets or sets which scroll bars should appear in a


multiline TextBox control. This property has values:

None
Horizontal
Vertical
Both

14 TabIndex Gets or sets the tab order of the control within its
container.

15 Text Gets or sets the current text in the TextBox.

16 TextAlign Gets or sets how text is aligned in a TextBox control.


This property has values:

Left
Right
Center

17 TextLength Gets the length of text in the control.

18 WordWrap Indicates whether a multiline text box control


automatically wraps words to the beginning of the next
line when necessary.

The Methods of the TextBox Control


The following are some of the commonly used methods of the TextBox control:

S.N Method Name & Description

1
AppendText

Appends text to the current text of a text box.

2
Clear

Clears all text from the text box control.

3
Copy

Copies the current selection in the text box to the Clipboard.

4
4
Cut

Moves the current selection in the text box to the Clipboard.

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

Resets the Text property to its default value.

8
ToString

Returns a string that represents the TextBoxBase control.

9
Undo

Undoes the last edit operation in the text box.

Events of the TextBox Control


The following are some of the commonly used events of the Text control:

S.N Event Description

1 Click Occurs when the control is clicked.

2 DoubleClick Occurs when the control is double-clicked.

3 TextAlignChanged Occurs when the TextAlign property value changes.

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.

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub

Private Sub btnMessage_Click(sender As Object, e As EventArgs) _


Handles btnMessage.Click
MessageBox.Show("Thank you " + txtName.Text + " from " + txtOrg.Text)
End Sub
End Class

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

Clicking the 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

CheckedListBox Control Overview (Windows


Forms)
03/30/2017 • 2 minutes to read • +6

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

Is this page helpful?

 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

The Code Gallery


MENU

Download and Play for Free DOWNLOAD


Convenient and fast, a stable game experience Tencent Gaming Buddy

VB.NET Tutorial

Basic Concepts

VB.NET Variable (index.php)


VB.NET Constant (Constant.php)
VB.NET Operators (Operator.php)
VB.NET DataTypes (DataType.php)
VB.NET Control Structure (ControlStructure.php)
VB.NET Looping Structure (LoopingStructure.php)
VB.NET Array (Array.php)
VB.NET Procedure (Procedure.php)
Event Procedure (Event.php)
Function Procedure (Function.php)
General Procedure (General.php)
Pass by Value/Ref (PassValue.php)

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)

VB.NET Built in Functions

InputBox (InputBox.php)
MsgBox (MsgBox.php)

Working with Popup Menu (Context Menu) in VB.NET

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:

SPONSORED SEARCHES SPONSORED SEARCHES SPONSORED SEARCHES

Display Pop Up Android Mobiles Apps Android БОКС

& VB Net Android Programming BA R

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 PHP & MySQL Project (../PHP/Download.php)

Download VB.NET Projects (Download.php)

Download Android Projects (../Android/Download.php)

Play PUBGM On PC For Free


Flexible control with mouse & keyboard
Tencent Game Buddy

Download Programs

Download C Programs (../C/Download.php)

Download C++ Programs (../CPP/Download.php)

Download Data Structure Program (../DSM/Program.php)

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)

Site built with Simple Responsive Template (http://www.prowebdesign.ro/simple-responsive-template/)

www.thecodegallery.com/VBNET/ContextMenuStrip.php 5/5
7/13/2019 Date time picker control in VB.NET

The Code Gallery


MENU

Download and Play for Free DOWNLOAD


Flexible control with mouse and keyboard Tencent Gaming Buddy

VB.NET Tutorial

Basic Concepts

VB.NET Variable (index.php)


VB.NET Constant (Constant.php)
VB.NET Operators (Operator.php)
VB.NET DataTypes (DataType.php)
VB.NET Control Structure (ControlStructure.php)
VB.NET Looping Structure (LoopingStructure.php)
VB.NET Array (Array.php)
VB.NET Procedure (Procedure.php)
Event Procedure (Event.php)
Function Procedure (Function.php)
General Procedure (General.php)
Pass by Value/Ref (PassValue.php)

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)

VB.NET Built in Functions

InputBox (InputBox.php)
MsgBox (MsgBox.php)

Datetimepicker Control in VB.NET


Example of Datetimepicker Control in VB.NET
(DatetimeExample.php)
www.thecodegallery.com/VBNET/DateTimePicker.php 2/8
7/13/2019 Date time picker control in VB.NET
DateTimePicker Control allows user to select a date and a time. It is also used to display selected
date and time in specific format.

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:

Properties of Datetimepicker Control in VB.NET

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:

dd/MM/yyyy will display 01/01/2014

d/M/yyyy will display 1/1/2014

d/M/yy will display 1/1/14

ddd, MMM, yyyy will display Wed, Jan, 2013

dddd, MMMM, yyyy will display

Wednesday, January, 2014

hh:mm:ss will display 02:25:02

HH:mm:ss will display 14:25:02

hh:mm:ss tt will display 02:25:02 PM

Value It is used to get date and time selected in DateTimePicker Control.

ShowCheckBox It is used to specify weather CheckBox is displayed in DateTimePicker


or not. It has Boolean value. Default value is false.

Checked It is used to specify weather CheckBox in DateTimePicker is checked


or not. It has Boolean value. Default value is true. It works only when
ShowCheckBox property is set to true.

SPONSORED SEARCHES SPONSORED SEARCHES SPONSORED SEARCHES

12 Month Custom Calendar Basic PHP Code Buy Pop Up Display

ActiveX Control Basic Programming C# Date Format

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.

Enabled It is used to specify weather DateTimePicker Control is enabled or not


at runtime. It has Boolean value. Default value is true.

Visible It is used to specify weather DateTimePicker Control is visible or not at


runtime. It has Boolean value. Default value is true.

CalendarFont It is used to get or set Font of the Calendar.

CalendarForeColor It is used to get or set ForeColor of the calendar font.

CalendarMonthBackground It is used to get or set Background Color of the Calendar.

CalendarTitleBackColor It is used to get or set Background Color of Calendar’s Title.

CalendarTitleForeColor It is used to get or set ForeColor of the font that is displayed in


Calendar’s Title.

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.

Methods of Datetimepicker Control in VB.NET

Method Purpose
Show It is used to show DateTimePicker Control at run time.

Hide It is used to Hide 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.

Events of Datetimepicker Control in VB.NET

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

Download PHP & MySQL Project (../PHP/Download.php)

Download VB.NET Projects (Download.php)

Download Android Projects (../Android/Download.php)

www.thecodegallery.com/VBNET/DateTimePicker.php 6/8
7/13/2019 Date time picker control in VB.NET

Play PUBGM On PC For Free


Flexible control with mouse & keyboard
Tencent Game Buddy

Download Programs

Download C Programs (../C/Download.php)

Download C++ Programs (../CPP/Download.php)

Download Data Structure Program (../DSM/Program.php)

Download Data Structure Algorithm (../DSM/Algorithm.php)

www.thecodegallery.com/VBNET/DateTimePicker.php 7/8
7/13/2019 Date time picker control in VB.NET

Shipping quote
real time

Quick Quotes generates


instant online quotes –
anytime, anywhere.
Speed up your business!

Site built with Simple Responsive Template (http://www.prowebdesign.ro/simple-responsive-template/)

www.thecodegallery.com/VBNET/DateTimePicker.php 8/8
7/13/2019 LinkLabel Control in VB.NET

The Code Gallery


MENU

VB.NET Tutorial

Basic Concepts

VB.NET Variable (index.php)


VB.NET Constant (Constant.php)
VB.NET Operators (Operator.php)
VB.NET DataTypes (DataType.php)
VB.NET Control Structure (ControlStructure.php)
VB.NET Looping Structure (LoopingStructure.php)
VB.NET Array (Array.php)
VB.NET Procedure (Procedure.php)
Event Procedure (Event.php)
Function Procedure (Function.php)
General Procedure (General.php)
Pass by Value/Ref (PassValue.php)

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)

VB.NET Built in Functions

InputBox (InputBox.php)
MsgBox (MsgBox.php)

Linklabel Control in VB.NET

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.

SPONSORED SEARCHES SPONSORED SEARCHES SPONSORED SEARCHES

Aluminium Joinery Array Data Structure Basic PHP Code

And VB Net Array Visual Basic Basic Programming

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.

Text It is used to get or set text associated with LinkLabel Control.

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.

BackColor It is used to get or set Background color of the 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.

Methods of Linklabel Control in VB.NET

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.

Hide It is used to Hide LinkLabel Control at runtime.

Focus It is used to set input focus on LinkLabel Control.

Events of Linklabel Control in VB.NET

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 PHP & MySQL Project (../PHP/Download.php)

Download VB.NET Projects (Download.php)

Download Android Projects (../Android/Download.php)

Download Programs
www.thecodegallery.com/VBNET/LinkLabel.php 4/5
7/13/2019 LinkLabel Control in VB.NET

Download C Programs (../C/Download.php)

Download C++ Programs (../CPP/Download.php)

Download Data Structure Program (../DSM/Program.php)

Download Data Structure Algorithm (../DSM/Algorithm.php)

Shipping quote
real time

Get container shipment


quotes the fast, easy and
convenient way. 24/7 –
worldwide.

Site built with Simple Responsive Template (http://www.prowebdesign.ro/simple-responsive-template/)

www.thecodegallery.com/VBNET/LinkLabel.php 5/5
7/2/2019 Masked Textbox Control in VB.NET

The Code Gallery


MENU

VB.NET Tutorial

Basic Concepts

VB.NET Variable (index.php)


VB.NET Constant (Constant.php)
VB.NET Operators (Operator.php)
VB.NET DataTypes (DataType.php)
VB.NET Control Structure (ControlStructure.php)
VB.NET Looping Structure (LoopingStructure.php)
VB.NET Array (Array.php)
VB.NET Procedure (Procedure.php)
Event Procedure (Event.php)
Function Procedure (Function.php)
General Procedure (General.php)
Pass by Value/Ref (PassValue.php)

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)

VB.NET Built in Functions

InputBox (InputBox.php)
MsgBox (MsgBox.php)

Masked Textbox Control in VB.NET


Example of Masked Textbox Control in VB.NET
(MaskedTextBoxExample.php)
www.thecodegallery.com/VBNET/MaskedtextBox.php 2/8
7/2/2019 Masked Textbox Control in VB.NET
MaskedTextBox provides all the facility of simple TextBox Control.
It allows user to validate input by specifying mask property. Mask property is used to specify pattern
that must be followed while entering text into MaskedTextBox. It does not allow user to enter text
that does not comply with the pattern specified in the Mask property.
Thus MaskedTextBox control is used to restrict invalid input from user.

Properties of Masked Textbox Control in VB.NET

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.

AsciiOnly It is used to specify weather only ASCII characters can be entered


as valid input character in MaskedTextBox or not. It has Boolean
value. Default value is false.

BackColor It is used to get or set BackColor of the MaskedTextBox.

BeepOnError It is used to specify weather control will generate system beep


sound on each invalid character input or not. 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 MaskedTextBox.

SPONSORED SEARCHES SPONSORED SEARCHES SPONSORED SEARCHES

Face Mask Array Sound System ASCII Replace

PHP MySQL ASCII Char ASP MVC

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.

Enabled It is used to specify weather MaskedTextBox 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 MaskedTextBox Control.

ForeColor It is used to get or set Fore color of the text associated with
MaskedTextBox Control.

HidePromptOnLeave It is used to specify weather Prompt character is displayed or hide


when focus is lost from MaskedTextBox. It has Boolean value.
Default value is false.

HideSelection It is used to specify weather text selection should be hidden or not


when MaskedTextBox lose its focus. It has Boolean value. Default
value is true.

InsertKeyMode It is used to get or set method used for input characters in


MaskedTextBox. It has following 3 options:
(1) Default
(2) Insert
(3) Overwrite

Mask It is used to get or set format string which determines weather


characters entered in MaskedTextBox are valid or not.

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.

ReadOnly It is used to specify weather text associated with MaskedTextBox is


ReadOnly or not. It has Boolean value. Default value is false.

RejectInputOnFirstFailure It is used to specify weather input is rejected or not when entered


characters are not complying with the pattern specified in mask
property. It has Boolean value. Default value is false.

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.

Text It is used to get or set text associated with MaskedTextBox Control.

TextAlign It is used to get or alignment of the text associated with


MaskedTextBox Control.

TabIndex It is used to get or set Tab order of the MaskedTextBox.

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.

Visible It is used to specify weather MaskedTextBox Control is visible or


not at run time. It has Boolean value. Default value is true.

Methods of Masked Textbox Control in VB.NET

Method Purpose
Append Text It is used to append text at the end of current text in MaskedTextBox Control.

Clear It is used to clear all text from MaskedTextBox Control.

Cut It is used to move current selection of MaskedTextBox into clipboard.

Copy It is used to copies selected text of MaskedTextBox in clipboard.

Paste It is used to replace current selection of MaskedTextBox by contents of


clipboard. It is also used to move contents of Clipboard to MaskedTextBox
control where cursor is currently located.

Select It is used to select specific text from MaskedTextBox.

SelectAll It is used to select all text of MaskedTextBox.

DeselectAll It is used to deselect all text selected in MaskedTextBox.

Show It is used to show MaskedTextBox at run time.

Hide It is used to hide MaskedTextBox at run time.

Focus It is used to set input focus on MaskedTextBox at run time.

Events of Masked Textbox Control in VB.NET


www.thecodegallery.com/VBNET/MaskedtextBox.php 6/8
7/2/2019 Masked Textbox Control in VB.NET

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.

MaskChanged It fires each time a mask property is changed.

TextChanged It fires each time a text in the MaskedTextBox control changed.

Download Projects

Download PHP & MySQL Project (../PHP/Download.php)

Download VB.NET Projects (Download.php)

Download Android Projects (../Android/Download.php)

Download Programs

Download C Programs (../C/Download.php)

Download C++ Programs (../CPP/Download.php)


www.thecodegallery.com/VBNET/MaskedtextBox.php 7/8
7/2/2019 Masked Textbox Control in VB.NET
Download Data Structure Program (../DSM/Program.php)

Download Data Structure Algorithm (../DSM/Algorithm.php)

Site built with Simple Responsive Template (http://www.prowebdesign.ro/simple-responsive-template/)

www.thecodegallery.com/VBNET/MaskedtextBox.php 8/8
7/2/2019 RichTextBox Control in VB.NET

The Code Gallery


MENU

VB.NET Tutorial

Basic Concepts

VB.NET Variable (index.php)


VB.NET Constant (Constant.php)
VB.NET Operators (Operator.php)
VB.NET DataTypes (DataType.php)
VB.NET Control Structure (ControlStructure.php)
VB.NET Looping Structure (LoopingStructure.php)
VB.NET Array (Array.php)
VB.NET Procedure (Procedure.php)
Event Procedure (Event.php)
Function Procedure (Function.php)
General Procedure (General.php)
Pass by Value/Ref (PassValue.php)

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)

VB.NET Built in Functions

InputBox (InputBox.php)
MsgBox (MsgBox.php)

RichTextBox Control in VB.NET


Example of RichTextBox Control in VB.NET
(RichTextBoxExample.php)
www.thecodegallery.com/VBNET/RichTextBox.php 2/8
7/2/2019 RichTextBox Control in VB.NET
RichTextBox Control allows user to display, input, edit and format text information.
RichTextBox Control supports advance formatting features as compared to TextBox. Using
RichTextBox user can format only selected portion of the text. User can also format paragraph using
RichTextBox Control.
RichTextBox Control also allows user to save as well as load file of RTF format and Standard ASCII
format.

Properties of RichTextBox Control in VB.NET

Property Purpose
AutoWordSelection It is used to specify weather automatic word selection is ON or OFF. It has
Boolean value. Default value is false.

BackColor It is used to get or set background color of the RichTextBox.

ContextMenuStrip It is used to specify the name of shortcut menu that is displayed when user
right clicks on the RichTextBox.

DetectUrls It is used to specify weather URL that is entered in RichTextBox is


automatically displayed as hyperlink or not. It has Boolean value. Default value
is true.

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.

SPONSORED SEARCHES SPONSORED SEARCHES SPONSORED SEARCHES

All on 4 And Control Method Auto Key Coding

Property Lines ASCII Characters Automatic 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.

ReadOnly It is used to specify weather text associated with RichTextBox is ReadOnly or


not. It has Boolean value. Default value is false.

RightMargin It is used to get or set right margin of the text in RichTextBox.

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.

Text It is used to get or set text associated with RichTextBox Control.

TabIndex It is used to get or set Tab order of the RichTextBox.

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.

ZoomFactor It is used to get or set current zoom level of RichTextBox.

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.

SelectionBackColor It is used to get or set BackColor 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.

SelectionLength It is used to get or set number of characters selected in the RichTextBox.

SelectionStart It is used to get or set starting point of the text selected in the RichTextBox.

Methods of RichTextBox Control in VB.NET

Method Purpose
Cut It is used to move current selection of RichTextBox into clipboard.

Copy It is used to copies selected text of RichTextBox in clipboard.

Paste It is used to replace current selection of TextBox by contents of clipboard. It is also


used to move contents of Clipboard to RichTextBox control where cursor is currently
located.

Select It is used to select specific text from RichTextBox.

SelectAll It is used to select all text of RichTextBox.

DeselectAll It is used to deselect all text selected in RichTextBox.

Clear It is used to clear all text from RichTextBox Control.


www.thecodegallery.com/VBNET/RichTextBox.php 5/8
7/2/2019 RichTextBox Control in VB.NET
AppendText It is used to append text at the end of current text in RichTextBox Control.

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.

Undo It is used to undo last edit operation of RichTextBox.

Redo It is used to redo the last operation that is undo using undo method.

Events of RichTextBox Control in VB.NET

Event Purpose
TextChanged It is the default event of RichTextBox Control. It fires each time a text in the
RichTextBox control changed.

Download Projects

Download PHP & MySQL Project (../PHP/Download.php)

Download VB.NET Projects (Download.php)

Download Android Projects (../Android/Download.php)

www.thecodegallery.com/VBNET/RichTextBox.php 6/8
7/2/2019 RichTextBox Control in VB.NET

Download Programs

Download C Programs (../C/Download.php)

Download C++ Programs (../CPP/Download.php)

Download Data Structure Program (../DSM/Program.php)

Download Data Structure Algorithm (../DSM/Algorithm.php)

www.thecodegallery.com/VBNET/RichTextBox.php 7/8
7/2/2019 RichTextBox Control in VB.NET

Site built with Simple Responsive Template (http://www.prowebdesign.ro/simple-responsive-template/)

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

Functions (Visual Basic)


Visual Studio 2015

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)

Math Functions (Visual Basic)

String Functions (Visual Basic)

Type Conversion Functions (Visual Basic)

CType Function (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

Math Functions (Visual Basic)


Visual Studio 2015

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

Abs Returns the absolute value of a number.

Acos Returns the angle whose cosine is the specified number.

Asin Returns the angle whose sine is the specified number.

Atan Returns the angle whose tangent is the specified number.

Atan2 Returns the angle whose tangent is the quotient of two specified numbers.

BigMul Returns the full product of two 32-bit numbers.

Ceiling Returns the smallest integral value that's greater than or equal to the specified Decimal or
Double.

Cos Returns the cosine of the specified angle.

Cosh Returns the hyperbolic cosine of the specified angle.

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.

Log10 Returns the base 10 logarithm of a specified number.

Max Returns the larger of two numbers.

Min Returns the smaller of two numbers.

Pow Returns a specified number raised to the specified power.

Round Returns a Decimal or Double value rounded to the nearest integral value or to a specified
number of fractional digits.

Sign Returns an Integer value indicating the sign of a number.

Sin Returns the sine of the specified angle.

Sinh Returns the hyperbolic sine of the specified angle.

Sqrt Returns the square root of a specified number.

Tan Returns the tangent of the specified angle.

Tanh Returns the hyperbolic tangent of the specified angle.

Truncate Calculates the integral part of a specified Decimal or Double number.

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.

' Returns 50.3.


Dim MyNumber1 As Double = Math.Abs(50.3)
' Returns 50.3.
Dim MyNumber2 As Double = Math.Abs(‐50.3)

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.

Public Function GetPi() As Double


' Calculate the value of pi.
Return 4.0 * Math.Atan(1.0)
End Function

Example
This example uses the Cos method of the Math class to return the cosine of an angle.

Public Function Sec(ByVal angle As Double) As Double


' Calculate the secant of angle, in radians.
Return 1.0 / Math.Cos(angle)
End Function

Example
This example uses the Exp method of the Math class to return e raised to a power.

Public Function Sinh(ByVal angle As Double) As Double


' Calculate hyperbolic sine of an angle, in radians.
Return (Math.Exp(angle) ‐ Math.Exp(‐angle)) / 2.0
End Function

Example
This example uses the Log method of the Math class to return the natural logarithm of a number.

Public Function Asinh(ByVal value As Double) As Double


' Calculate inverse hyperbolic sine, in radians.
Return Math.Log(value + Math.Sqrt(value * value + 1.0))
End Function

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.

Public Function Csc(ByVal angle As Double) As Double


' Calculate cosecant of an angle, in radians.
Return 1.0 / Math.Sin(angle)
End Function

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.

Public Function Ctan(ByVal angle As Double) As Double

4 of 5 04.09.2016 0:06
Math Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/thc0a116(d=printer).aspx

' Calculate cotangent of an angle, in radians.


Return 1.0 / Math.Tan(angle)
End Function

Requirements
Class: Math

Namespace: System

Assembly: mscorlib (in mscorlib.dll)

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

String Functions (Visual Basic)


Visual Studio 2015

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.

FormatDateTime Returns a string expression representing a date/time value.

FormatNumber Returns an expression formatted as a number.

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.

Join Returns a string created by joining a number of substrings contained in an array.

LCase Returns a string or character converted to lowercase.

Left Returns a string containing a specified number of characters from the left side of a string.

Len Returns an integer that contains the number of characters in 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.

Mid Returns a string containing a specified number of characters from a string.

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.

Space Returns a string consisting of the specified number of spaces.

Split Returns a zero-based, one-dimensional array containing a specified number of substrings.

StrComp Returns -1, 0, or 1, based on the result of a string comparison.

StrConv Returns a string converted as specified.

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

' String to convert.


Dim LowerCase As String = "Hello World 1234"
' Returns "HELLO WORLD 1234".
Dim UpperCase As String = UCase(LowerCase)

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

variable. It uses the Trim function to strip both types of spaces.

VB

' Initializes string.


Dim TestString As String = " <‐Trim‐> "
Dim TrimString As String
' Returns "<‐Trim‐> ".
TrimString = LTrim(TestString)
' Returns " <‐Trim‐>".
TrimString = RTrim(TestString)
' Returns "<‐Trim‐>".
TrimString = LTrim(RTrim(TestString))
' Using the Trim function alone achieves the same result.
' Returns "<‐Trim‐>".
TrimString = Trim(TestString)

Example
This example uses the Mid function to return a specified number of characters from a string.

VB

' Creates text string.


Dim TestString As String = "Mid Function Demo"
' Returns "Mid".
Dim FirstWord As String = Mid(TestString, 1, 3)
' Returns "Demo".
Dim LastWord As String = Mid(TestString, 14, 4)
' Returns "Function Demo".
Dim MidWords As String = Mid(TestString, 5)

Example
This example uses Len to return the number of characters in a string.

VB

' Initializes variable.


Dim TestString As String = "Hello World"
' Returns 11.
Dim TestLen As Integer = Len(TestString)

Example
This example uses the InStr function to return the position of the first occurrence of one string within another.

VB

' String to search in.


Dim SearchString As String = "XXpXXpXXPXXP"

3 of 5 04.09.2016 0:06
String Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/dd789093(d=printer).aspx

' Search for "P".


Dim SearchChar As String = "P"

Dim TestPos As Integer


' A textual comparison starting at position 4. Returns 6.
TestPos = InStr(4, SearchString, SearchChar, CompareMethod.Text)

' A binary comparison starting at position 1. Returns 9.


TestPos = InStr(1, SearchString, SearchChar, CompareMethod.Binary)

' If Option Compare is not set, or set to Binary, return 9.


' If Option Compare is set to Text, returns 3.
TestPos = InStr(SearchString, SearchChar)

' 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

Dim TestDateTime As Date = #1/27/2001 5:04:23 PM#


Dim TestStr As String
' Returns current system time in the system‐defined long time format.
TestStr = Format(Now(), "Long Time")
' Returns current system date in the system‐defined long date format.
TestStr = Format(Now(), "Long Date")
' Also returns current system date in the system‐defined long date
' format, using the single letter code for the format.
TestStr = Format(Now(), "D")

' Returns the value of TestDateTime in user‐defined date/time formats.


' Returns "5:4:23".
TestStr = Format(TestDateTime, "h:m:s")
' Returns "05:04:23 PM".
TestStr = Format(TestDateTime, "hh:mm:ss tt")
' Returns "Saturday, Jan 27 2001".
TestStr = Format(TestDateTime, "dddd, MMM d yyyy")
' Returns "17:04:23".
TestStr = Format(TestDateTime, "HH:mm:ss")
' Returns "23".

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)

' User‐defined numeric formats.


' Returns "5,459.40".
TestStr = Format(5459.4, "##,##0.00")
' Returns "334.90".
TestStr = Format(334.9, "###0.00")
' Returns "500.00%".
TestStr = Format(5, "0.00%")

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

Dates and Times Summary (Visual Basic)


Visual Studio 2015

Visual Basic language keywords and run-time library members are organized by purpose and use.

Action Language element

Get the current date or time. Now, Today, TimeOfDay

Perform date calculations. DateAdd, DateDiff, DatePart

Return a date. DateSerial, DateValue, MonthName, WeekdayName

Return a time. TimeSerial, TimeValue

Set the date or time. DateString, TimeOfDay, TimeString, Today

Time a process. Timer

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(DateInterval, DateTime, Returns a Long value specifying the number of time


DateTime, FirstDayOfWeek, intervals between two Date values.
FirstWeekOfYear)

DateDiff(String, Object, Object, Returns a Long value specifying the number of time
FirstDayOfWeek, FirstWeekOfYear) intervals between two Date values.

DatePart(DateInterval, DateTime, Returns an Integer value containing the specified


FirstDayOfWeek, FirstWeekOfYear) component of a given Date value.

DatePart(String, Object, Returns an Integer value containing the specified


FirstDayOfWeek, FirstWeekOfYear) component of a given Date value.

DateSerial(Int32, Int32, Int32) Returns a Date value representing a specified year,


month, and day, with the time information set to
midnight (00:00:00).

2 of 4 04.09.2016 1:10
DateAndTime Class (Microsoft.VisualBasic) https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.dateandti...

DateValue(String) Returns a Date value containing the date information


represented by a string, with the time information set
to midnight (00:00:00).

Day(DateTime) Returns an Integer value from 1 through 31


representing the day of the month.

Equals(Object) Determines whether the specified object is equal to the


current object.(Inherited from Object.)

GetHashCode() Serves as the default hash function. (Inherited from


Object.)

GetType() Gets the Type of the current instance.(Inherited from


Object.)

Hour(DateTime) Returns an Integer value from 0 through 23


representing the hour of the day.

Minute(DateTime) Returns an Integer value from 0 through 59


representing the minute of the hour.

Month(DateTime) Returns an Integer value from 1 through 12


representing the month of the year.

MonthName(Int32, Boolean) Returns a String value containing the name of the


specified month.

Second(DateTime) Returns an Integer value from 0 through 59


representing the second of the minute.

TimeSerial(Int32, Int32, Int32) Returns a Date value representing a specified hour,


minute, and second, with the date information set
relative to January 1 of the year 1.

TimeValue(String) Returns a Date value containing the time information


represented by a string, with the date information set
to January 1 of the year 1.

ToString() Returns a string that represents the current object.


(Inherited from Object.)

Weekday(DateTime, FirstDayOfWeek) Returns an Integer value containing a number


representing the day of the week.

WeekdayName(Int32, Boolean, Returns a String value containing the name of the


FirstDayOfWeek) specified weekday.

3 of 4 04.09.2016 1:10
DateAndTime Class (Microsoft.VisualBasic) https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.dateandti...

Year(DateTime) Returns an Integer value from 1 through 9999


representing the year.

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.

Dim thisDate As Date


thisDate = Today

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

Math Summary (Visual Basic)


Visual Studio 2015

Visual Basic language keywords and run-time library members are organized by purpose and use.

Action Language element

Derive trigonometric functions. Atan, Cos, Sin, Tan

General calculations. Exp, Log, Sqrt

Generate random numbers. Randomize, Rnd

Get absolute value. Abs

Get the sign of an expression. Sign

Perform numeric conversions. Fix, Int

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

Derived Math Functions (Visual Basic)


Visual Studio 2015

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.

Function Derived equivalents

Secant (Sec(x)) 1 / Cos(x)

Cosecant (Csc(x)) 1 / Sin(x)

Cotangent (Ctan(x)) 1 / Tan(x)

Inverse sine (Asin(x)) Atan(x / Sqrt(-x * x + 1))

Inverse cosine (Acos(x)) Atan(-x / Sqrt(-x * x + 1)) + 2 * Atan(1)

Inverse secant (Asec(x)) 2 * Atan(1) – Atan(Sign(x) / Sqrt(x * x – 1))

Inverse cosecant (Acsc(x)) Atan(Sign(x) / Sqrt(x * x – 1))

Inverse cotangent (Acot(x)) 2 * Atan(1) - Atan(x)

Hyperbolic sine (Sinh(x)) (Exp(x) – Exp(-x)) / 2

Hyperbolic cosine (Cosh(x)) (Exp(x) + Exp(-x)) / 2

Hyperbolic tangent (Tanh(x)) (Exp(x) – Exp(-x)) / (Exp(x) + Exp(-x))

Hyperbolic secant (Sech(x)) 2 / (Exp(x) + Exp(-x))

Hyperbolic cosecant (Csch(x)) 2 / (Exp(x) – Exp(-x))

Hyperbolic cotangent (Coth(x)) (Exp(x) + Exp(-x)) / (Exp(x) – Exp(-x))

Inverse hyperbolic sine (Asinh(x)) Log(x + Sqrt(x * x + 1))

Inverse hyperbolic cosine (Acosh(x)) Log(x + Sqrt(x * x – 1))

Inverse hyperbolic tangent (Atanh(x)) Log((1 + x) / (1 – x)) / 2

Inverse hyperbolic secant (AsecH(x)) Log((Sqrt(-x * x + 1) + 1) / x)

1 of 2 04.09.2016 1:14
Derived Math Functions (Visual Basic) https://msdn.microsoft.com/en-us/library/w3t84e33(d=printer).aspx

Inverse hyperbolic cosecant (Acsch(x)) Log((Sign(x) * Sqrt(x * x + 1) + 1) / x)

Inverse hyperbolic cotangent (Acoth(x)) Log((x + 1) / (x – 1)) / 2

See Also
Math Functions (Visual Basic)

© 2016 Microsoft

2 of 2 04.09.2016 1:14
8/24/2020 VB.Net - ContextMenuStrip Control - Tutorialspoint

VB.Net - ContextMenuStrip Control

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 −

Properties of the ContextMenuStrip Control


The following are some of the commonly used properties of the ContextMenuStrip control −

Sr.No. Property & Description

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 −

Private Sub CutToolStripMenuItem_Click(sender As Object, e As EventArgs) _


Handles CutToolStripMenuItem.Click
RichTextBox1.Cut()
End Sub

Private Sub CopyToolStripMenuItem_Click(sender As Object, e As EventArgs) _


Handles CopyToolStripMenuItem.Click
RichTextBox1.Copy()
End Sub

Private Sub PasteToolStripMenuItem_Click(sender As Object, e As EventArgs) _


Handles PasteToolStripMenuItem.Click
RichTextBox1.Paste()
End Sub

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.

The following diagram shows adding a MenuStrip control on the form:

Properties of the MenuStrip Control


The following are some of the commonly used properties of the MenuStrip control:

S.N Property Description

1 Gets or sets a value indicating whether the MenuStrip supports


CanOverflow overflow functionality.

2 Gets or sets the visibility of the grip used to reposition the control.
GripStyle

3 Gets or sets the ToolStripMenuItem that is used to display a list of


MdiWindowListItem Multiple-document interface MDI child forms.

4 Gets or sets a value indicating whether ToolTips are shown for


ShowItemToolTips the MenuStrip.

5 Gets or sets a value indicating whether the MenuStrip stretches


Stretch from end to end in its container.
Events of the MenuStrip Control
The following are some of the commonly used events of the MenuStrip control:

S.N Event Description

1 Occurs when the user accesses the menu with the keyboard or
MenuActivate mouse.

2 Occurs when the MenuStrip is deactivated.


MenuDeactivate

Example
In this example, let us add menu and sub-menu items.

Take the following steps:

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.

Complete the menu structure shown in the diagram above.

Add a sub menu Exit under the File menu.

Double-Click the Exit menu created and add the following code to the Click event of
ExitToolStripMenuItem:

Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) _


Handles ExitToolStripMenuItem.Click
End
End Sub

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.

Properties of the ComboBox Control


The following are some of the commonly used properties of the ComboBox control:

S.N Property Description

1 AllowSelection Gets a value indicating whether the list enables


selection of list items.

2 AutoCompleteCustomSource Gets or sets a custom


System.Collections.Specialized.StringCollection to use
when the AutoCompleteSourceproperty is set to
CustomSource.

3 AutoCompleteMode Gets or sets an option that controls how automatic


completion works for the ComboBox.

4 AutoCompleteSource Gets or sets a value specifying the source of complete


strings used for automatic completion.

5 DataBindings Gets the data bindings for the control.

6 DataManager Gets the CurrencyManager associated with this control.


7 DataSource Gets or sets the data source for this ComboBox.

8 DropDownHeight Gets or sets the height in pixels of the drop-down


portion of the ComboBox.

9 DropDownStyle Gets or sets a value specifying the style of the combo


box.

10 DropDownWidth Gets or sets the width of the of the drop-down portion of


a combo box.

11 DroppedDown Gets or sets a value indicating whether the combo box


is displaying its drop-down portion.

12 FlatStyle Gets or sets the appearance of the ComboBox.

13 ItemHeight Gets or sets the height of an item in the combo box.

14 Items Gets an object representing the collection of the items


contained in this ComboBox.

15 MaxDropDownItems Gets or sets the maximum number of items to be


displayed in the drop-down part of the combo box.

16 MaxLength Gets or sets the maximum number of characters a user


can enter in the editable area of the combo box.

17 SelectedIndex Gets or sets the index specifying the currently selected


item.

18 SelectedItem Gets or sets currently selected item in the ComboBox.

19 SelectedText Gets or sets the text that is selected in the editable


portion of a ComboBox.

20 SelectedValue Gets or sets the value of the member property specified


by the ValueMember property.

21 SelectionLength Gets or sets the number of characters selected in the


editable portion of the combo box.

22 SelectionStart Gets or sets the starting index of text selected in the


combo box.

23 Sorted Gets or sets a value indicating whether the items in the


combo box are sorted.

24 Text Gets or sets the text associated with this control.

Methods of the ComboBox Control


The following are some of the commonly used methods of the ComboBox control:

S.N Method Name & Description

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.

Events of the ComboBox Control


The following are some of the commonly used events of the ComboBox control:

S.N Event Description

1 DropDown Occurs when the drop-down portion of a combo box is


displayed.

2 DropDownClosed Occurs when the drop-down portion of a combo box is no


longer visible.

3 DropDownStyleChanged Occurs when the DropDownStyle property of the


ComboBox has changed.

4 SelectedIndexChanged Occurs when the SelectedIndex property of a ComboBox


control has changed.

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.

Add a label control that would display the selected item.


Add the following code in the code editor window:

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
'sends the selected items to the list box
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex > -1 Then
Dim sindex As Integer
sindex = ComboBox1.SelectedIndex
Dim sitem As Object
sitem = ComboBox1.SelectedItem
ListBox1.Items.Add(sitem)
End If
End Sub
'populates the list
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
ComboBox1.Items.Clear()
ComboBox1.Items.Add("Safety")
ComboBox1.Items.Add("Security")
ComboBox1.Items.Add("Governance")
ComboBox1.Items.Add("Good Music")
ComboBox1.Items.Add("Good Movies")
ComboBox1.Items.Add("Good Books")
ComboBox1.Items.Add("Education")
ComboBox1.Items.Add("Roads")
ComboBox1.Items.Add("Health")
ComboBox1.Items.Add("Food for all")
ComboBox1.Items.Add("Shelter for all")
ComboBox1.Items.Add("Industrialisation")
ComboBox1.Items.Add("Peace")
ComboBox1.Items.Add("Liberty")
ComboBox1.Items.Add("Freedom of Speech")
ComboBox1.Text = "Select from..."
End Sub
'sorting the list
Private Sub Button3_Click(sender As Object, e As EventArgs)
ComboBox1.Sorted = True
End Sub
'clears the list
Private Sub Button4_Click(sender As Object, e As EventArgs)
ComboBox1.Items.Clear()
End Sub
'displaying the selected item on the label
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _
Handles ListBox1.SelectedIndexChanged
Label1.Text = ComboBox1.SelectedItem.ToString()
End Sub
End Class

When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window:
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.

Properties of the ListBox Control


The following are some of the commonly used properties of the ListBox control:

S.N Property Description

1 AllowSelection Gets a value indicating whether the ListBox currently enables


selection of list items.

2 BorderStyle Gets or sets the type of border drawn around the list box.

3 ColumnWidth Gets of sets the width of columns in a multicolumn list box.

4 HorizontalExtent Gets or sets the horizontal scrolling area of a list box.

5 HorizontalScrollBar Gets or sets the value indicating whether a horizontal scrollbar is


displayed in the list box.

6 ItemHeight Gets or sets the height of an item in the list box.

7 Items Gets the items of 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.

11 SelectedIndices Gets a collection that contains the zero-based indexes of all


currently selected items in the list box.

12 SelectedItem Gets or sets the currently selected item in the list box.

13 SelectedItems Gets a collection containing the currently selected items 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.

Methods of the ListBox Control


The following are some of the commonly used methods of the ListBox control:

S.N Method Name & Description

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

Unselects all items in the ListBox.

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

Returns a value indicating whether the specified item is selected.

7
SetSelected

Selects or clears the selection for the specified item in a ListBox.

8
OnSelectedIndexChanged

Raises the SelectedIndexChanged event.

8
OnSelectedValueChanged

Raises the SelectedValueChanged event.

Events of the ListBox Control


The following are some of the commonly used events of the ListBox control:

S.N Event Description

1 Click Occurs when a list box is selected.

2 SelectedIndexChanged Occurs when the SelectedIndex property of a list box is


changed.

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.

Take the following steps:

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.

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
ListBox1.Items.Add("Canada")
ListBox1.Items.Add("USA")
ListBox1.Items.Add("UK")
ListBox1.Items.Add("Japan")
ListBox1.Items.Add("Russia")
ListBox1.Items.Add("China")
ListBox1.Items.Add("India")
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


MsgBox("You have selected " + ListBox1.SelectedItem.ToString())
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
Handles ListBox1.SelectedIndexChanged
Label2.Text = ListBox1.SelectedItem.ToString()
End Sub
End Class

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

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.

Design the Form:

Add the following code in the code editor window:

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
' creating multi-column and multiselect list box
ListBox1.MultiColumn = True
ListBox1.SelectionMode = SelectionMode.MultiExtended
End Sub
'populates the list
Private Sub Button1_Click_1(sender As Object, e As EventArgs) _
Handles Button1.Click
ListBox1.Items.Add("Safety")
ListBox1.Items.Add("Security")
ListBox1.Items.Add("Governance")
ListBox1.Items.Add("Good Music")
ListBox1.Items.Add("Good Movies")
ListBox1.Items.Add("Good Books")
ListBox1.Items.Add("Education")
ListBox1.Items.Add("Roads")
ListBox1.Items.Add("Health")
ListBox1.Items.Add("Food for all")
ListBox1.Items.Add("Shelter for all")
ListBox1.Items.Add("Industrialisation")
ListBox1.Items.Add("Peace")
ListBox1.Items.Add("Liberty")
ListBox1.Items.Add("Freedom of Speech")
End Sub
'sorting the list
Private Sub Button2_Click(sender As Object, e As EventArgs) _
Handles Button2.Click
ListBox1.Sorted = True
End Sub
'clears the list
Private Sub Button3_Click(sender As Object, e As EventArgs) _
Handles Button3.Click
ListBox1.Items.Clear()
End Sub
'removing the selected item
Private Sub Button4_Click(sender As Object, e As EventArgs) _
Handles Button4.Click
ListBox1.Items.Remove(ListBox1.SelectedItem.ToString)
End Sub
'counting the numer of items
Private Sub Button5_Click(sender As Object, e As EventArgs) _
Handles Button5.Click
Label1.Text = ListBox1.Items.Count
End Sub
'displaying the selected item on the third label
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _
Handles ListBox1.SelectedIndexChanged
Label3.Text = ListBox1.SelectedItem.ToString()
End Sub
End Class

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

Fill the list and check workings of other buttons:

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.

Properties of the PictureBox Control


The following are some of the commonly used properties of the PictureBox control:

S.N Property Description

1 AllowDrop Specifies whether the picture box accepts data that a user drags
on it.

2 ErrorImage Gets or specifies an image to be displayed when an error occurs


during the image-loading process or if the image load is
cancelled.

3 Image Gets or sets the image that is displayed in the control.

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

6 SizeMode Determines the size of the image to be displayed in the control.


This property takes its value from the PictureBoxSizeMode
enumeration, which has values:

Normal - the upper left corner of the image is placed at


upper left part of the picture box
StrechImage - allows stretching of the image
AutoSize - allows resizing the picture box to the size of the
image
CenterImage - allows centering the image in the picture
box
Zoom - allows increasing or decreasing the image size to
maintain the size ratio.

7 TabIndex Gets or sets the tab index value.

8 TabStop Specifies whether the user will be able to focus on the picture box
by using the TAB key.

9 Text Gets or sets the text for the picture box.

10 WaitOnLoad Specifies whether or not an image is loaded synchronously.

Methods of the PictureBox Control


The following are some of the commonly used methods of the PictureBox control:

S.N Method Name & Description

1
CancelAsync

Cancels an asynchronous image load.

2
Load

Displays an image in the picture box

3
LoadAsync

Loads image asynchronously.

4
ToString

Returns the string that represents the current picture box.

Events of the PictureBox Control


The following are some of the commonly used events of the PictureBox control:

S.N Event Description

1 CausesValidationChanged Overrides the Control.CausesValidationChanged property.

2 Click Occurs when the control is clicked.

3 Enter Overrides the Control.Enter property.

4 FontChanged Occurs when the value of the Font property changes.

5 ForeColorChanged Occurs when the value of the ForeColor property changes.

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.

9 Leave Occurs when input focus leaves the PictureBox.

10 LoadCompleted Occurs when the asynchronous image-load operation is


completed, been canceled, or raised an exception.

11 LoadProgressChanged Occurs when the progress of an asynchronous image-


loading operation has changed.

12 Resize Occurs when the control is resized.

13 RightToLeftChanged Occurs when the value of the RightToLeft property


changes.

14 SizeChanged Occurs when the Size property value changes.

15 SizeModeChanged Occurs when SizeMode changes.

16 TabIndexChanged Occurs when the value of the TabIndex property changes.

17 TabStopChanged Occurs when the value of the TabStop property changes.

18 TextChanged Occurs when the value of the Text property changes.

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:

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


PictureBox1.ClientSize = New Size(300, 300)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Sub
End Class

Design View:
When the application is executed, it displays:

Clicking on the button results in:


VB.NET - PROGRESSBAR CONTROL
http://www.tutorialspoint.com/vb.net/vb.net_progress_bar.htm Copyright © tutorialspoint.com

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.

Properties of the ProgressBar Control


The following are some of the commonly used properties of the ProgressBar control:

S.N Property Description

1 AllowDrop Overrides Control.AllowDrop.

2 BackgroundImage Gets or sets the background image for the ProgressBar


control.

3 BackgroundImageLayout Gets or sets the layout of the background image of the


progress bar.

4 CausesValidation Gets or sets a value indicating whether the control, when it


receives focus, causes validation to be performed on any
controls that require validation.

5 Font Gets or sets the font of text in the ProgressBar.

6 ImeMode Gets or sets the input method editor IME for the
ProgressBar.

7 ImeModeBase Gets or sets the IME mode of a control.

8 MarqueeAnimationSpeed Gets or sets the time period, in milliseconds, that it takes


the progress block to scroll across the progress bar.
9 Maximum Gets or sets the maximum value of the range of the control.

10 Minimum Gets or sets the minimum value of the range of the control.

11 Padding Gets or sets the space between the edges of a ProgressBar


control and its contents.

12 RightToLeftLayout Gets or sets a value indicating whether the ProgressBar and


any text it contains is displayed from right to left.

13 Step Gets or sets the amount by which a call to the PerformStep


method increases the current position of the progress bar.

14 Style Gets or sets the manner in which progress should be


indicated on the progress bar.

15 Value Gets or sets the current position of the progress bar.

Methods of the ProgressBar Control


The following are some of the commonly used methods of the ProgressBar control:

S.N Method Name & Description

1
Increment

Increments the current position of the ProgressBar control by specified amount.

2
PerformStep

Increments the value by the specified step.

3
ResetText

Resets the Text property to its default value.

4
ToString

Returns a string that represents the progress bar control.

Events of the ProgressBar Control


The following are some of the commonly used events of the ProgressBar control:

S.N Event Description

1 BackgroundImageChanged Occurs when the value of the BackgroundImage


property changes.

2 BackgroundImageLayoutChanged Occurs when the value of the


BackgroundImageLayout property changes.

3 CausesValidationChanged Occurs when the value of the CausesValidation


property changes.
4 Click Occurs when the control is clicked.

5 DoubleClick Occurs when the user double-clicks the control.

6 Enter Occurs when focus enters the control.

7 FontChanged Occurs when the value of the Font property


changes.

8 ImeModeChanged Occurs when the value of the ImeMode property


changes.

9 KeyDown Occurs when the user presses a key while the


control has focus.

10 KeyPress Occurs when the user presses a key while the


control has focus.

11 KeyUp Occurs when the user releases a key while the


control has focus.

12 Leave Occurs when focus leaves the ProgressBar control.

13 MouseClick Occurs when the control is clicked by the mouse.

14 MouseDoubleClick Occurs when the user double-clicks the control.

15 PaddingChanged Occurs when the value of the Padding property


changes.

16 Paint Occurs when the ProgressBar is drawn.

17 RightToLeftLayoutChanged Occurs when the RightToLeftLayout property


changes.

18 TabStopChanged Occurs when the TabStop property changes.

18 TextChanged Occurs when the Text property changes.

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.

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
'create two progress bars
Dim ProgressBar1 As ProgressBar
Dim ProgressBar2 As ProgressBar
ProgressBar1 = New ProgressBar()
ProgressBar2 = New ProgressBar()
'set position
ProgressBar1.Location = New Point(10, 10)
ProgressBar2.Location = New Point(10, 50)
'set values
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 200
ProgressBar1.Value = 130
ProgressBar2.Minimum = 0
ProgressBar2.Maximum = 100
ProgressBar2.Value = 40
'add the progress bar to the form
Me.Controls.Add(ProgressBar1)
Me.Controls.Add(ProgressBar2)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
End Class

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

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

MDI Form What Lurks in Your


Cloud?
A Multiple Document Interface (MDI) programs can display multiple child windows
Palo Alto Networks
inside them.
Cloud Security & Compliance Starts With
Visibility. Learn What Lurks in Your Cloud

OPEN

What Lurks in Your


Cloud?
Palo Alto Networks
Cloud Security & Compliance Starts With
Visibility. Learn What Lurks in Your Cloud

OPEN

Microsoft .Net Framework Tutorials


VB.NET Language Basics Tutorials
This is in contrast to single document interface (SDI) applications, which can
VB.NET Program Flow Control Tutorials
manipulate only one document at a time. Visual Studio Environment is an example of
Multiple Document Interface (MDI) and notepad is an example of an SDI VB.Net Graphical User Interface
application, opening a document closes any previously opened document. Any VB.NET Collections Tutorials
windows can become an MDI parent, if you set the IsMdiContainer property to True. VB.NET String Tutorials
VB.NET Files Tutorials
IsMdiContainer = True VB.Net Excel Automation
VB.NET Crystal Reports Tutorials
VB.NET Communications Tutorial
The following vb.net program shows a MDI form with two child forms. Create a new
VB.NET ADO.NET Tutorial
VB.Net project, then you will get a default form Form1 . Then add two mnore forms
in the project (Form2 , Form 3) . Create a Menu on your form and call these two ADO.NET Data Providers Tutorial
forms on menu click event. Click the following link to see how to create a Menu on VB.NET ADO.NET Dataset Tutorial
your form How to Menu Control VB.Net. ADO.NET DataAdapter and Dataset
VB.NET ADO.NET DataView Tutorial
NOTE: If you want the MDI parent to auto-size the child form you can code like this.
VB.NET Remoting Tutorial
VB.NET XML Tutorial
form.MdiParent = Me
form.Dock = DockStyle.Fill VB.NET DataGridView Tutorial
form.Show()

Next : Color Dialog Box

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

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Han


IsMdiContainer = True
End Sub

Private Sub MenuItem1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


Dim frm2 As New Form2
frm2.Show()
frm2.MdiParent = Me
End Sub

Private Sub MenuItem2ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


Dim frm3 As New Form3
frm3.Show()
frm3.MdiParent = Me
End Sub

End Class

Visual Studio IDE


How to Create a vb.net Windows Forms Application
Label Control
Button Control
TextBox Control
ComboBox Control
ListBox Control
Checked ListBox Control
RadioButton Control
CheckBox Control
PictureBox Control
ProgressBar Control
ScrollBars Control
DateTimePicker Control
Treeview Control
ListView Control
Menu Control
Color Dialog Box
Font Dialog Box
OpenFile Dialog Box
Print Dialog Box
KeyPress event in VB.NET
How to create Dynamic Controls in VB.NET ?
How do i keep a form on top of others
Timer Control - VB.Net

Download and Play for Free DOWNLOAD


Flexible control with mouse and keyboard Tencent Gaming Buddy

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

More Source Code : Custom Search Search Mail to : feedback@net-informations.com

Award-winning IT DataGridView Autocomplete Treeview Control Button Control


monitoring TextBox in VB.Net

Ad PRTG Network Monitor net-informations.com net-informations.com net-informations.com

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

net-informations.com (C) 2019 Founded by raps mk


All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap | Terms | About

vb.net-informations.com/gui/vb.net-mdi-form.htm 3/3
11/29/2020 Using Unstructured Exception Handling

Search

web www.yaldex.com

JavaScript Editor JavaScript Debugger

Main Page

Using Unstructured Exception Handling


As discussed in the In Depth section of this chapter, there are now two ways of handling runtime errors in Visual Basic—you can use structured or
unstructured exception handling (exceptions are runtime errors). Unstructured exception handling revolves around the On Error GoTo statement, and
structured exception handling uses the Try…Catch…Finally statement. Without an On Error GoTo or Try…Catch…Finally statement, any exception that
occurs is fatal and your program will stop.

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 }

Here are the parts of this statement:

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.

GoTo -1—Same as GoTo 0.

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

Free JavaScript Editor JavaScript Editor

↓ 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

VB.Net - ColorDialog Control

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 −

Properties of the ColorDialog Control

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

Sr.No. Property & Description

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

Gets a value indicating whether the component can raise an event.

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.

Methods of the ColorDialog Control

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

Sr.No. Method Name & Description

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

When overridden in a derived class, specifies a common dialog box.

3
ShowDialog
Runs a common dialog box with a default owner.

Events of the ColorDialog Control

The following are some of the commonly used events of the ColorDialog control −

Sr.No. Event & Description

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.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


If ColorDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
Label1.ForeColor = ColorDialog1.Color
End If
End Sub

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

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


response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. VB.Net
exception handling is built upon four keywords: 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.

Exception Classes in .Net Framework


In the .Net Framework, exceptions are represented by classes. The exception classes in .Net
Framework are mainly directly or indirectly derived from the System.Exception class. Some of
the exception classes derived from the System.Exception class are the
System.ApplicationException and System.SystemException classes.

The System.ApplicationException class supports exceptions generated by application


programs. So the exceptions defined by the programmers should derive from this class.

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:

Exception Class Description

System.IO.IOException Handles I/O errors.


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

System.ArrayTypeMismatchException Handles errors generated when type is mismatched


with the array type.

System.NullReferenceException Handles errors generated from deferencing a null


object.

System.DivideByZeroException Handles errors generated from dividing a dividend with


zero.

System.InvalidCastException Handles errors generated during typecasting.

System.OutOfMemoryException Handles errors generated from insufficient free


memory.

System.StackOverflowException Handles errors generated from stack overflow.

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:

Exception caught: System.DivideByZeroException: Attempted to divide by zero.


at ...
Result: 0

Creating User-Defined Exceptions


You can also define your own exception. User-defined exception classes are derived from the
ApplicationException class. The following example demonstrates this:

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:

TempIsZeroException: Zero Temperature found

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 ]

The following program demonstrates this:

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:

A custom exception is being thrown here...


Now inside the Finally Block
11/29/2020 VB.Net - FontDialog Control - Tutorialspoint

VB.Net - FontDialog Control

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.

Properties of the FontDialog Control

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

Sr.No. Property & Description

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

Gets or sets the maximum point size a user can select.

9 MinSize

Gets or sets the minimum point size a user can select.

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.

Methods of the FontDialog Control

The following are some of the commonly used methods of the FontDialog control −

Sr.No. Method Name & Description

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.

Events of the FontDialog Control

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

Sr.No. Event & Description

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 −

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


If FontDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
RichTextBox1.ForeColor = FontDialog1.Color
RichTextBox1.Font = FontDialog1.Font
End If
End Sub

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

Enter some text and Click on the Change Font button.

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

VB.Net - OpenFileDialog Control

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 −

Properties of the OpenFileDialog Control


The following are some of the commonly used properties of the OpenFileDialog control −

https://www.tutorialspoint.com/vb.net/vb.net_openfile_dialog.htm 1/5
10/2/2020 VB.Net - OpenFileDialog Control - Tutorialspoint

Sr.No. Property & Description

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.

Methods of the OpenFileDialog Control


The following are some of the commonly used methods of the OpenFileDialog control −

Sr.No. Method Name & Description

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:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
End Sub

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 PrinterSettings control - it is used to configure how a document is printed by specifying


the printer.

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.

The PrintPreviewDialog control - it represents a dialog box form that contains a


PrintPreviewControl for printing from a Windows Forms application.

Following is the Print dialog box:

Properties of the PrintDialog Control


The following are some of the commonly used properties of the PrintDialog control:

S.N Property Description

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.

3 AllowSelection Gets or sets a value indicating whether the Selection option


button is enabled.

4 AllowSomePages Gets or sets a value indicating whether the Pages option button
is enabled.

5 Document Gets or sets a value indicating the PrintDocument used to obtain


PrinterSettings.

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.

8 ShowHelp Gets or sets a value indicating whether the Help button is


displayed.

9 ShowNetwork Gets or sets a value indicating whether the Network button is


displayed.

Methods of the PrintDialog Control


The following are some of the commonly used methods of the PrintDialog control:

S.N Method Name & Description

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.

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.

Change the text of the button to 'Print'.

Double-click the Print button and modify the code of the Click event as shown:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


PrintDialog1.Document = PrintDocument1
PrintDialog1.PrinterSettings = PrintDocument1.PrinterSettings
PrintDialog1.AllowSomePages = True
If PrintDialog1.ShowDialog = DialogResult.OK Then
PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings
PrintDocument1.Print()
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:

Click the Print button to make the Print dialog box appear.
11/29/2020 VB.Net - Sub Procedures - Tutorialspoint

VB.Net - Sub Procedures

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.

Defining Sub Procedures

The Sub statement is used to declare the name, parameter and the body of a sub procedure. The
syntax for the Sub statement is −

[Modifiers] Sub SubName [(ParameterList)]


[Statements]
End Sub

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 −

Total Pay: $250.00


Total Pay: $800.00
Total Pay: $825.00

Passing Parameters by Value


This is the default mechanism for passing parameters to a method. In this mechanism, when a
method is called, a new storage location is created for each value parameter. The values of the
actual parameters are copied into them. So, the changes made to the parameter inside the method
have no effect on the argument.

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

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

It shows that there is no change in the values though they had been changed inside the function.

Passing Parameters by Reference


A reference parameter is a reference to a memory location of a variable. When you pass
parameters by reference, unlike value parameters, a new storage location is not created for these
parameters. The reference parameters represent the same memory location as the actual
parameters that are supplied to the method.

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 −

Before swap, value of a : 100


Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

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.

Following is the Save File dialog box:

Properties of the SaveFileDialog Control


The following are some of the commonly used properties of the SaveFileDialog control:

S.N Property Description

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 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.

3 CheckPathExists Gets or sets a value indicating whether the dialog


box displays a warning if the user specifies a path
that does not exist.

4 CreatePrompt Gets or sets a value indicating whether the dialog


box prompts the user for permission to create a file if
the user specifies a file that does not exist.

5 DefaultExt Gets or sets the default file name extension.

6 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.

7 FileName Gets or sets a string containing the file name


selected in the file dialog box.

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.

10 FilterIndex Gets or sets the index of the filter currently selected


in the file dialog box.

11 InitialDirectory Gets or sets the initial directory displayed by the file


dialog box.

12 OverwritePrompt Gets or sets a value indicating whether the Save As


dialog box displays a warning if the user specifies a
file name that already exists.

13 RestoreDirectory Gets or sets a value indicating whether the dialog


box restores the current directory before closing.

14 ShowHelp Gets or sets a value indicating whether the Help


button is displayed in the file dialog box.

15 SupportMultiDottedExtensions Gets or sets whether the dialog box supports


displaying and saving files that have multiple file
name extensions.

16 Title Gets or sets the file dialog box title.

17 ValidateNames Gets or sets a value indicating whether the dialog


box accepts only valid Win32 file names.

Methods of the SaveFileDialog Control


The following are some of the commonly used methods of the SaveFileDialog control:

S.N Method Name & Description

1
OpenFile

Opens the file with read/write permission.

2
Reset

Resets all dialog box options to their default values.

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.

Creating a String Object


You can create string object using one of the following methods:

By assigning a string literal to a String variable

By using a String class constructor

By using the string concatenation operator +

By retrieving a property or calling a method that returns a string

By calling a formatting method to convert a value or object to its string representation

The following example demonstrates this:

Module strings
Sub Main()
Dim fname, lname, fullname, greetings As String
fname = "Rowan"
lname = "Atkinson"
fullname = fname + " " + lname
Console.WriteLine("Full Name: {0}", fullname)

'by using string constructor


Dim letters As Char() = {"H", "e", "l", "l", "o"}
greetings = New String(letters)
Console.WriteLine("Greetings: {0}", greetings)

'methods returning String


Dim sarray() As String = {"Hello", "From", "Tutorials", "Point"}
Dim message As String = String.Join(" ", sarray)
Console.WriteLine("Message: {0}", message)

'formatting method to convert a value


Dim waiting As DateTime = New DateTime(2012, 12, 12, 17, 58, 1)
Dim chat As String = String.Format("Message sent at {0:t} on {0:D}", waiting)
Console.WriteLine("Message: {0}", chat)
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Full Name: Rowan Atkinson


Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 5:58 PM on Wednesday, December 12, 2012

Properties of the String Class


The String class has the following two properties:

S.N Property Name & Description

1
1
Chars

Gets the Char object at a specified position in the current String object.

2
Length

Gets the number of characters in the current String object.

Methods of the String Class


The String class has numerous methods that help you in working with the string objects. The
following table provides some of the most commonly used methods:

S.N Method Name & Description

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

Concatenates two string objects.

4
Public Shared Function Concat str0AsString, str1AsString, str2AsString As String

Concatenates three string objects.

5
Public Shared Function Concat str0AsString, str1AsString, str2AsString, str3AsString As String

Concatenates four string objects.

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

Indicates whether the specified string is null or an Empty string.

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

Returns a copy of this string converted to lowercase.

35
Public Function ToUpper As String

Returns a copy of this string converted to uppercase.

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:

This is test and This is text are not equal.

String Contains String:

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:

The sequence 'test' was found.

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:

Last night I dreamt of San Pedro


San Pedro.

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

Database Programming With ADO.NET

 ADO.NET – introduction and applications


 ADO.NET – architecture (connected and disconnected)
 Database connectivity using ADO.NET
 Use of Data sources, Server Explorer and working with DataSet
 Populating data in a DataGridView

ADO.NET – introduction and applications

 ADO.NET is a part of the Microsoft .Net Framework.


 The full form of ADO.Net is ActiveX® Data Objects.
 ADO.Net has the ability to separate data access mechanisms, data manipulation
mechanisms and data connectivity mechanisms.
 ADO.Net is a set of classes that allow application to read and write information in
databases.
 ADO.Net can be used by any .Net Language.
 It’s concept. It’s not a programming language.
 ADO.Net introduces the concept of disconnected architecture.
 We need to add System.Data namespace for work with ADO.Net
 It’s a next version of ActiveX Data Objects (ADO) technology which was used in VB6.0.

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

Comparison between ADO and 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.

.NET Framework Data Providers


The .NET Framework Data Providers are components that have been explicitly designed for data
manipulation and fast, forward-only, read-only access to data. The Connection object provides
connectivity to a data source. The Command object enables access to database commands to
return data, modify data, run stored procedures, and send or retrieve parameter information. The
DataReader provides a high-performance stream of data from the data source. Finally, the
DataAdapter provides the bridge between the DataSet object and the data source. The
DataAdapter uses Command objects to execute SQL commands at the data source to both load
the DataSet with data and reconcile changes that were made to the data in the DataSet back to
the data source.

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.

Selecting a DataReader or a DataSet


When you decide whether your application should use a DataReader or a DataSet, consider the
type of functionality that your application requires. Use a DataSet to do the following:
 Cache data locally in your application so that you can manipulate it. If you only need to
read the results of a query, the DataReader is the better choice.
 Remote data between tiers or from an XML Web service.
 Interact with data dynamically such as binding to a Windows Forms control or combining
and relating data from multiple sources.
 Perform extensive processing on data without requiring an open connection to the data
source, which frees the connection to be used by other clients.
If you do not require the functionality provided by the DataSet, you can improve the
performance of your application by using the DataReader to return your data in a forward-only,
read-only manner. Although the DataAdapter uses the DataReader to fill the contents of a
DataSet, by using the DataReader, you can boost performance because you will save memory
that would be consumed by the DataSet, and avoid the processing that is required to create and
fill the contents of the DataSet.

Connected Architecture of ADO.NET

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.

Connection : in connected architecture also the purpose of connection is to just establish


aconnection to database and it self will not transfer any data.

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

Disconnected Architecture in 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

Connection : Connection object is used to establish a connection to database and connectionit


self will not transfer any data.

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.

CommandBuilder : by default dataadapter contains only the select command and it


doesn’tcontain insert, update and delete commands. To create insert, update and delete
commands for the dataadapter, commandbuilder is used. It is used only to create these
commands for the dataadapter and has no other purpose.

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.

A dataset can contain data in multiple tables.

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

Difference between Connected and disconnected architecture

Connected ( DataReader) Disconnected (DataSet)


It is connection oriented. It is disconnection oriented.
Disconnected get low in speed and
Connected methods gives faster performance.
performance

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

For SQL Server


 Imports System.Data.SqlClient namespace.
 It provides data access for Microsoft SQL Server.
For OLEDB
 Imports System.Data.OleDb namespace.
 It provides data sources exposed using OLEDB.
 We can use OLEDB for connect Microsoft Access
For ODBC
 Imports System.Data.Odbc namespace.
 It provides data sources exposed using ODBC
For Oracle
 Imports System.Data.OracleClient namespace.
 It provides data access for oracle.
Data Provider’s common set of classes for all DataSource.
1. Connection
2. Command
3. DataAdapter
4. DataReader
Conncetion
 It establishes or connects a connection to the data source.
 In SQL Server the connection can establish using SqlConnection object.
Command
 Fires SQL commands or perform some action on the data source, such as insert, update,
delete.
 In SQL Server command can fires using SqlCommand object.
DataAdapter
 It’s a bride between Data source and DataSet object for transferring data.
 In SQL Server the Data Adapter can create using SqlDataAdapter object
DataReader
 Used when large list of results one record at a time.
 It reads records in a read-only, forward-only mode.

Page 9 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET

 In SQL Server the datareader can create using SqlDataReader object

Use of Server Explorer


Server Explorer/Database Explorer is the server management console for Visual Studio. Use
this window to open data connections and to log on to servers and explore their system services.
Use Server Explorer/Database Explorer to view and retrieve information from all of the
databases you are connected to. You can do the following:
 List database tables, views, stored procedures, and functions
 Expand individual tables to list their columns and triggers
 Right-click a table to perform actions, such as showing the table's data or viewing the
table's definition, from its shortcut menu.
To access Server Explorer/Database Explorer, choose Server Explorer or Database Explorer
on the View menu. To make the Server Explorer/Database Explorer window close
automatically when not in use, choose Auto Hide on the Window menu.

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.

Consists of the classes that constitute the ADO.NET architecture, which is


the primary data access method for managed applications. The ADO.NET
architecture enables you to build components that efficiently manage data
from multiple data sources. ADO.NET also provides the tools to request,
update, and reconcile data in distributed applications.

System.Data.OleDb The System.Data.OleDb namespace is the.NET Framework Data Provider


for OLE DB.

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.

System.Data.SqlClient The System.Data.SqlClient namespace is the.NET Framework Data


Provider for SQL Server.

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

read results. The System.Data.SqlClient namespace is similar to the


System.Data.OleDb namespace, but is optimized for access to SQL
Server 7.0 and later.

System.Data.SqlTypes The System.Data.SqlTypes namespace provides classes for native data


types in SQL Server. These classes provide a safer, faster alternative to the
data types provided by the .NET Framework common language runtime
(CLR). Using the classes in this namespace helps prevent type conversion
errors caused by loss of precision. Because other data types are converted
to and from SqlTypes behind the scenes, explicitly creating and using
objects within this namespace also yields faster code.

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 :

ConnectionString : Gets/sets the connection string to open a database.


Database : Gets the name of the database to open
DataSource : Gets the name of the SQL Server to use.
State : Gets the connection's current state

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 :

 It’s depended on Connection Object.


 Command objects are used to execute commands to a database across a data connection.
 The Command object in ADO.NET executes SQL statements and stored procedures
against the data source specified in the connection object.
 The Command objects has a property called Command Text, which contains a String
(Query) value that represents the command that will be executed in the Data Source.

There are many ways to initialize Command object:

For Example

Dim con As New SqlConnection


Dim cmd As SqlCommand
Dim str1 As String

Str1 = "Insert into stud values(‘”+ TextBox1.Text +”’, ‘”+ TextBox1.Text +”’)
con.Open()
cmd = New SqlCommand(str1, con)
cmd.ExecuteNonQuery()
con.close()

OR

Dim con As New SqlConnection


Dim cmd As SqlCommand

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

Parameters Gets the command parameters.

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

SelectCommand Gets or sets a Transact-SQL statement or stored procedure used


to select records in the data source.
TableMappings Gets a collection that provides the master mapping between a
source table and a DataTable. (Inherited from DataAdapter.)
UpdateCommand Gets or sets a Transact-SQL statement or stored procedure used
to update records in the data source.

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().)

Dim reader As SqlDataReader


sql = " Select * from stud"
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()

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.

Explain the steps to bind DataGridView.


Step : 1 Take New VB.NET Project
Step : 2 Add database in your project (Named : dbemp.mdf)
Add New Table in database file (Named : emp ) from the Server Explorer Window

Page 18 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET

Add some records in that table


Step : 3 Now add emp table to the DBEmpDataSet.xsd file
Step : 4 Add DataGridView control on the form
Step : 5 Select the Choose Data Source
In that click on Other Data Source
Project Data Source
DBEmpDataSet
Emp  Table Name
Step : 6 At the end, Run the project

Binding Data Grids


As we've already seen, you can use data grids to display entire data tables. To bind a data grid to
a table, you can set the data grid's DataSource property (usually to a dataset, such as dsDataSet)
and DataMember property (usually to text naming a table like "authors"). At run time, you can
set both of these properties at once with the built-in data grid method SetDataBinding (data
grids are the only controls that have this method):

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

Public Class Form1


Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.DataSource = GetDataTable()
End Sub

Private Function GetDataTable() As DataTable


Return New DataTable()
End Function
End Class

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

Syntax: instance.DataMember = value

Properties of BindingNavigator Control:


1) BindingSource: Gets or sets the System.Windows.Forms.BindingSource component that is
the source of data.
Syntax: instance.BindingSource = value

Explain use of “ExecuteScaler” , “ExecuteNonQuery” and “ExecuteReader” method in


detail.

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.

The SqlDataReader Object is a stream-based, forward-only, read-only retrieval of query results


from the Data Source, which do not update the data. The SqlDataReader cannot be created
directly from code, they created only by calling the ExecuteReader method of a Command
Object.

Dim reader As SqlDataReader


sql = " Select * from stud"

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.

sql = " Select Count(*) from stud"


Try
con.Open()
cmd = New SqlCommand(sql, con)
Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
cmd.Dispose()
con.Close()
MsgBox(" No. of Rows " & count)
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try

What are the four common SQL commands used to retrieve and modify data in a SQL
Database? Also explain each of them.

Four Common SQL Commands :


1. Select
2. Insert
3. Update
4. Delete

Page 22 of 26
US05CCSC03 Visual Programming through VB.NET
UNIT 4 : Database Programming With ADO.NET

Select

Retrives data from one or more tables or views.


Systax :
Select * from TableName
Select Columnname1, Columnname2 from TableName
Select * from TableName Where <Condition>
Select * from TableName Order by Columnnane
Example :
Select * from stud
Select Sno,Sname from stud
Select * from stud where city = “Anand”
Select * from stud order by total

Insert

Create a new row and inserts values into specified columns

Syntax:
Insert into TableName values(Value1,Value2,…)

Example :

Insert into stud values (1,’ABC’)


Update

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

Delete one or more rows from a table

Syntax :
Delete from TableName
Delete from TableName where <condition>

Example :

Delete from stud


Delete from stud where sno = 5

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

14 DataSets are loaded from the database using the:


a. Load method. b. Read method.
c. Fill method. d. None of the above.
15 Sorting supports:
a. Ascending order. b. Descending order.
c. Ascending and descending order. d. None of the above.
16 SQL SELECT statements are sent to a database using:
a. SqlConnection and its ExecuteReader b. SqlCommand object and its
method. ExecuteNonQuery method.
c. SqlCommand object and its d. SqlParameter object and its Execute
ExecuteReader method. method.
17 SQL INSERT statements are sent to a database using:
a. SqlConnection and its ExecuteReader b. SqlCommand object and its
method. ExecuteNonQuery method.
c. SqlCommand object and its d. SqlParameter object and its Execute
ExecuteReader method. method.
18 SQL UPDATE statements are sent to a database using:
a. SqlConnection and its ExecuteReader b. SqlCommand object and its
method. ExecuteNonQuery method.
c. SqlCommand object and its d. SqlParameter object and its Execute
ExecuteReader method. method.
19 SQL DELETE statements are sent to a database using:
a. SqlConnection and its ExecuteReader b. SqlCommand object and its
method. ExecuteNonQuery method.
c. SqlCommand object and its d. SqlParameter object and its Execute
ExecuteReader method. method.
20 Stored procedures are invoked using:
a. SqlConnection and its ExecuteReader b. SqlCommand object and its
method. ExecuteNonQuery method.
c. SqlCommand object and its d. SqlParameter object and its Execute
ExecuteReader method. method.
21 Retrieving a single value from a returned row involves using:
a. SqlConnection and its ExecuteReader b. SqlCommand object and its
method. ExecuteNonQuery method.
c. SqlCommand object and its d. SqlParameter object and its Execute
ExecuteScalar method. method.

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

You might also like