Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
The content in this document is retired and is no longer updated or supported. Some links might not work. Retired content represents the
latest updated version of this content.
Visual Basic Language Concepts
Visual Basic
Microsoft Visual Basic 2005 is an evolution of the Visual Basic language that is engineered for productively building type-safe
and object-oriented applications. Visual Basic allows developers to target Windows, Web, and mobile devices. As with all
languages targeting the Microsoft .NET Framework, programs written in Visual Basic benefit from security and language
interoperability.
This generation of Visual Basic continues the tradition of giving you a fast and easy way to create .NET Framework-based
applications.
This version of Visual Basic brings back support for Edit and Continue and has new features for rapid application development.
One of these features, called My, provides quick access to common tasks provided by the .NET Framework, as well as
information and default object instances that are related to the application and its run-time environment. New language
features include loop continuation, guaranteed resource disposal, operator overloading, generic types, and custom events.
Visual Basic also fully integrates the .NET Framework and the common language runtime (CLR), which provide language
interoperability, garbage collection, enhanced security, and versioning support.
In This Section
Getting Started with Visual Basic
Helps you begin working by listing what is new and what is available in various editions of the product.
Visual Basic Guided Tour
Steps you through various aspects of programming with Visual Basic.
Help for Visual Basic 6.0 Users
Discusses the differences in Visual Basic between version 6.0 and the current version.
Upgrading Applications in Visual Basic
Demonstrates how to upgrade various kinds of Visual Basic code.
Developing Applications with Visual Basic
Discusses various aspects of development in Visual Basic, such as the code editor, security, exception handling, debugging,
and making use of the .NET Framework class library.
Visual Basic Programming Guide
Introduces the essential components of Visual Basic, an object-oriented programming language.
Reference (Visual Basic)
Contains the Visual Basic language and compiler information.
Visual Basic Sample Applications
Contains information about samples.
Related Sections
Introducing Visual Studio
Provides information about new features, a high-level overview of Visual Studio and the .NET Framework, and tips for
getting started.
Integrated Development Environment for Visual Studio
Discusses the shared tools that allow you to design, develop, debug, and deploy applications.
Windows-based Applications, Components, and Services
Discusses Windows applications, components of various kinds, XML Web services, Windows services, console applications,
and 64-bit applications.
.NET Framework Programming in Visual Studio
Discusses application development with the .NET Framework.
Visual Web Developer
Discusses how to create Web applications.
.NET Framework Class Library Reference
Provides entry to the library of classes, interfaces, and value types that are included in the Microsoft .NET Framework SDK.
Visual Studio Tools for Office
Guides you in taking advantage of the productivity enhancements in the Microsoft .NET Framework version 2.0 to extend
Microsoft Office Word 2003, Microsoft Office Excel 2003, and Microsoft Office Outlook 2003.
Smart Device Development
Discusses development of software that runs on Windows CE-based smart devices such as Pocket PCs and Smartphones.
Visual Basic Language Concepts
Class Library X X X
Console Application X X X
Device Application X X
Empty Project X X X
Excel Template X
Excel Workbook X
Outlook Add-in X
Test Project X
Windows Application X X X
Windows Service X
Word Document X
Word Template X
For more information on available project templates and items, see Default Project Templates in Visual Studio. For information
on File Types File Types and File Extensions in Visual Basic, Visual C#, and Visual J#.
Visual Tools
The following designers are included in Visual Basic.
Feature Description Microsoft Visual Visual Stu Visual Studio 20
Basic 2005 Expr dio 2005 S 05 Professional
ess Edition tandard and above
Web Forms Designer Provides a set of visual tools for worki X
ng with ASP.NET Web Forms pages an
d controls.
XML Schema Designer (XML Designer) Provides a set of visual tools for worki X
ng with XML schemas, ADO.NET datas
ets, and XML documents.
To see a complete listing of the features in various editions of Visual Studio, see Visual Studio Editions.
See Also
Tasks
How to: Modify Project Properties and Configuration Settings
Reference
Visual Basic Settings
Concepts
Installation and Setup Essentials
Visual Database Tools Editions
Project Types in Visual Basic Express
Other Resources
Visual Studio Editions
Visual Basic Language Concepts
Getting Help
The Help files that are included with Visual Basic Express Edition are a subset of the MSDN Library for Visual Studio 2005
Express Editions, which is in turn a subset of the full MSDN Library. If you are connected to the Internet, you can access any
Help topic in the full library. If you do not have online access or you chose not to install the MSDN Library for Visual Studio
2005 Express Editions, some Help topics may not be available. For more information, see Troubleshooting Visual Basic Express.
See Also
Concepts
Project Types in Visual Basic Express
Other Resources
Getting Started with Visual Basic Express
Visual Basic Guided Tour
Visual Basic Language Concepts
Class Library Template Used to create reusable classes or components that can be shared with other projects.
Console Application Template Used to create command-line applications, programs that run from a Windows command pro
mpt and have no visual interface.
My Movie Collection Starter Used to create the pre-built My Movie Collection sample application, which you can customize
Kit Template to meet your own needs. For more information, see
Starter Kits: Getting Up and Running Quickly.
Screen Saver Starter Kit Tem Used to create the pre-built Screen Saver sample application, which you can customize to meet
plate your own needs. For more information, see Starter Kits: Getting Up and Running Quickly.
Note
Although there is no project template for Windows control libraries, you can still create your own controls using the Class Li
brary template. For more information, see Visible Objects: Creating Your First User Control.
See Also
Concepts
Introduction to Visual Basic Express
Other Resources
Visual Basic Guided Tour
Visual Basic Language Concepts
Write the code. Next you will need to write the Visual Basic code that defines how your application will behave and how
it will interact with the user. Visual Basic Express Edition makes it easy to write code with features like Intellisense, auto-
completion, and code snippets.
Test the code. You will always want to test your application to make sure that it behaves the way that you expect it to—
this process is known as debugging. Visual Basic Express Edition has debugging tools that make it easy to find and fix
errors in your code interactively.
Distribute the application. Once your application is complete, you can install the resulting program on your computer
or distribute it and share it with others. Visual Basic Express Edition uses a new technology known as ClickOnce
Publishing that allows you to easily deploy an application using a wizard, and to automatically provide updated versions
of the application if you later make changes.
Getting Around
At first glance, the user interface for Visual Basic Express Edition, also known as the Integrated Development Environment or
IDE, may seem unfamiliar, but once you learn your way around, you will find it is easy to use. The following sections describe
parts of the IDE that you will use the most.
On Startup
When you first open Visual Basic Express Edition, you see that most of the IDE is filled with the Start Page window. The Start
Page contains a clickable list of your recent projects, a Getting Started area with links to important Help topics, and a list of
links to online articles and other resources. If you are connected to the Internet, this list will be updated on a regular basis.
You can change what appears on the Start Page to match your personal preferences. For more information, see
How to: Customize the News Section of the Start Page.
On the right-hand side of the IDE, you see the Solution Explorer window. It is initially blank, but this is where information
about your project, or groups of projects known as solutions, will be displayed. For more information, see
Using Solution Explorer.
Figure 1: Solution Explorer
On the left-hand side of the IDE, you see a vertical tab marked Toolbox. It is also initially blank, but as you work it will be filled
up with items that can be used for the task you are currently working on. For more information, see Using the Toolbox.
Across the top of the IDE are a menu bar and a toolbar. The available menus and toolbar buttons change based on your current
task—take some time to explore and see what choices are available. You can also customize the menus and toolbar to match
your personal preferences. For more information, see How to: Customize Toolbars (Visual Studio).
Across the very bottom of the IDE is a status bar that displays Ready. As you work in the IDE, the status bar changes, displaying
messages related to your current task—for example, the status bar shows information about the progress of a project you are
building.
Design Mode
When you open or create a project, the appearance of the IDE changes into design mode. This is the visual part of Visual Basic,
where you design the appearance of your application.
Figure 2: IDE in Design Mode
In design mode, the Start Page is covered by another window known as the Form Designer, which is basically a blank canvas
that represents the user interface for your application. Notice that the Start Page is still available by clicking its tab above the
Form Designer.
When the Form Designer is visible, the Toolbox contains a number of controls (representations of buttons, text fields, grids,
and so forth) that can be placed on the form and arranged as you like. For more information, see Windows Forms Designer.
You will also notice that a new window, the Properties window, appears below the Solution Explorer window. This is where
you will set the various properties that define the appearance and behavior of the form and its controls. For more information,
see Properties Window.
The Task List window at the bottom of the IDE isn't shown by default, but it provides a place that you can keep track of tasks
that need to be done or make notes while you are programming. For more information, see Task List (Visual Studio).
If you double-click a form or control, a new window called the Code Editor opens. This is where you write the actual code for
your application. More than just a text editor, the Code Editor uses a technology known as Intellisense to help you write code
by providing relevant information as you type. For more information, see Visual Basic-Specific IntelliSense.
Note
For some types of projects, such as Class Library projects that have no user interface, the Code Editor is shown instead of th
e Form Designer.
Run Mode
When you run or debug your application, the IDE changes into run mode. The application itself is launched, and an additional
window related to debugging appears. While in run mode, you cannot make changes in the Form Designer, Properties
window, or Solution Explorer, but you can make changes to your code in the Code Editor.
Figure 3: Visual Basic form in Break mode
In run mode, a new window known as the Immediate window appears at the bottom of the IDE. If you put the application into
break mode, you can query values and test code in the Immediate window. For more information, see Immediate Window.
Additional windows for watching the value of variables, viewing output, and other debugging tasks can be viewed at run time
by selecting them from the Debug menu.
Other Important Windows
There are numerous additional windows that you may encounter in the IDE, each geared to a specific programming task. Some
of the more common ones are listed below.
The Error List window appears at the bottom of the IDE if incorrect code is entered or other errors occur at design time.
For more information, see Error List Window.
The Object Browser window is used to examine the properties, methods, and events for any object that can be used in
your application. For more information, see Object Browser.
The Project Designer is used to configure properties for your application, including resources, debugging behavior,
deployment settings, and much more. For more information, see Introduction to the Project Designer.
The Database Explorer allows you to view and use existing databases or create and design new ones. For more
information, see Server Explorer/Database Explorer.
Customization
Visual Basic Express Edition allows you to customize the IDE by rearranging the window layout, choosing which windows are
displayed, adding or removing menu commands and toolbar buttons, and much more. For more information, see
Customizing the Development Environment.
Getting Help
As you work in Visual Basic Express Edition, help is always just a key-press away. Whether you are in the Code Editor or any
other window, pressing the F1 key displays the Help topic most closely related to what you are doing at the time. For example,
if you are in the Code Editor and the cursor is on the keyword Inherits, the Help browser is launched and a topic describing the
use of the Inherits statement is displayed.
Note
The Help files that are included with Visual Basic Express Edition are a subset of the MSDN Library for Visual Studio 2005 Exp
ress Editions, which is in turn a subset of the full MSDN Library. If you are connected to the Internet, you can access any Help
topic in the full library. If you do not have online access or you chose not to install the MSDN Library for Visual Studio 2005 E
xpress Editions, some Help topics may not be available.
Help can also be launched from the Help menu, and you can find the topics you are looking for by using the Contents or
Index windows or the Search tab. For more information, see Help on Help (Microsoft Document Explorer Help).
See Also
Other Resources
Creating Your First Visual Basic Program
Visual Basic Guided Tour
Help for Visual Basic 6.0 Users
Visual Basic Programming Guide
Creating Windows-based Applications
Visual Basic Language Concepts
It is also possible that, due to late-breaking changes in the product, steps or code in the lesson may be wrong. The online
versions of these topics are constantly being updated, so a corrected version of the topic may be available online.
To correct errors in a lesson
1. Go back to the step in which the program last worked, and carefully follow each remaining step.
2. Review any code that you entered and make sure that it exactly matches the code in the lesson.
3. Press F5 to run the program.
If the program still doesn't run or behave as expected, check to see if an updated version of the topic is available. For
more information, see "I Can't Access a Help Topic" below.
I Can't Find a Command or Option
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is
described in Help, depending on your active settings or edition. To change your settings, choose Import and Export Settings
on the Tools menu. For more information, see Visual Studio Settings.
I Can't Access a Help Topic
The Help files that are included with Visual Basic Express Edition are a subset of the MSDN Library for Visual Studio 2005
Express Editions, which is in turn a subset of the full MSDN Online Library. During installation you had the option of installing
the MSDN Library for Visual Studio 2005 Express Editions—if you chose not to install it, consider doing so now.
A Link Doesn't Work
Links to topics that are not included in the MSDN Library for Visual Studio 2005 Express Editions will display the Information
Not Found page, but you can still access the topics that the links refer to by searching in the MSDN Online Library.
To access a topic when a link doesn't work
1. On the Help menu, click Search.
The Search Page opens.
2. In the search box, enter the text that was displayed in the link, and then click Search.
A search is performed and the results are displayed.
3. Select the MSDN Online tab on the right-hand side of the Search page.
Note
If MSDN Online is not displayed, your Help system may not be configured for online access. For more information, se
e "How to: Enable Online Access" below.
4. Click the topic title that most closely matches the text of the original link.
The topic is downloaded and displayed.
Pressing F1 Doesn't Work
Pressing F1 anywhere in the IDE should display context-sensitive Help. Even though not all topics are included in the MSDN
Library for Visual Studio 2005 Express Editions, if you are connected to the Internet, you can access any Help topic in the full
library using F1. If you do not have online access or you chose not enable online Help, some help topics may not be available
using F1.
You can change you Help options at any time as described below.
How to: Enable Online Access
The first time you access help from Visual Basic Express Edition you are prompted to choose how online Help is configured.
The choices are to try and find the online version of a topic first, to try locally installed Help first and look online if it isn't found,
or to use local Help only.
Tip
If you have access to the Internet, you should configure Help so that it checks online Help first—if a newer version of a topic i
s available, you will always have the most up-to-date information.
You can change you Help options at any time as described below.
Note
To access online Help, you must have an active connection to the Internet, and any proxy server or firewall must be configure
d to allow access to the MSDN online library.
2. Click the All Windows Forms tab of the Toolbox, select the Panel control, and then drag a panel onto the top-left
corner of the form.
Tip
If you have difficulty finding the correct control, right-click on the Toolbox and then select Sort Items Alphabetically.
3. From the same tab, drag a Button control and place it on top of the Panel.
Tip
You can reposition controls using a drag-and-drop operation. You can also resize controls by clicking and dragging the
edge or corner of the control.
4. From the same tab, drag a TextBox control and place it on top of the Panel.
5. Finally, from the All Windows Forms tab, select a WebBrowser control and place it below the Panel.
Tip
If you kept the Toolbox window open, you may want to close it now to give yourself more room to work. You can do s
o by clicking the Auto Hide icon again.
Closer Look
You just added four controls to the form. Controls contain code that defines what the controls look like and what tasks they can
perform.
Take, for example, the Button control—almost every program has an "OK" button or an "Exit" button. While you could write
your own code to draw a button on the screen, change its appearance when it is pressed, and perform some task when it is
clicked, doing so for every program would quickly become tedious. The Button control already contains the code necessary to
do these things, saving you a lot of unnecessary work.
As you can see, the Toolbox contains many controls, and each control has a unique purpose. Panel controls can be used to
hold other controls, such as the ones you just added. Button controls are typically used to perform tasks when the user clicks
them, for example, closing the program. TextBox controls are used to enter text on a screen through the keyboard. A
WebBrowser control provides built-in Web-browsing capabilities similar to Internet Explorer—you certainly wouldn't want to
write all the code for that!
In upcoming lessons you will learn how to customize the appearance of these and many other controls, as well as how to write
code that defines their behavior. In addition to using the Toolbox controls, you can also create your own controls known as
user controls—these are also covered in an upcoming lesson.
Next Steps
You just added all the necessary controls for your application. It probably looks rough and unfinished—because it is! In the
next lesson, you will use the Properties window to set the properties that will control the look and feel of your application.
Next Lesson: Step 3: Customize Looks and Behavior
See Also
Tasks
Step 1: Create a Project in Visual Basic
Other Resources
Creating Your First Visual Basic Program
Controls to Use on Windows Forms
Visual Basic Language Concepts
3. Click the top box in the property-selection window to set the Dock property to Top. The Panel control expands to fill the
top of the form.
4. In the Form Designer, select the WebBrowser control. In the Properties window, set its Dock property to Fill by
selecting the Dock property, clicking the arrow to the right, and selecting the center box in the property-selection
window.
5. In the Form Designer, select the Button control.
6. In the Properties window, select the Text property of the Button control. In the right-hand column, delete Button1 and
replace it with Go!.
7. Resize or relocate any of the controls, and resize the form to suit your taste.
Note
The TextBox and Button controls must remain on top of the Panel, or you will not be able to see them when you run t
he application.
Closer Look
In this lesson, you set several properties that changed the appearance of the controls for your application. A property in Visual
Basic represents an attribute of an object—in this case, a control. For example, one attribute of a Button control is the text it
displays. In this case, you set the Text property to display "Go!". To learn more about properties, see
Closer Look: Understanding Properties, Methods, and Events.
Properties can take many different types of values besides text. For example, the Dock property used a property-selection
window to show available options. Other property values might be numbers, an option you select from a list, or a true-or-false
option.
If you resized or relocated a control, you also set properties. The Size and Location properties determine the control's size and
location on the form. To see this in action, select the Size property in the Properties window and use the mouse to resize the
control. When you release the mouse, the new Size values display in the Properties window.
In addition to setting properties in the Properties window, most properties can be set by writing code. You will learn more
about writing code to set properties in a following lesson.
Next Steps
Your user interface is now complete! All you have to do is add the instructions (also called code) for how you want your
program to work. In the next lesson, you will add a line of code to your program.
Next Lesson: Step 4: Add Visual Basic Code
See Also
Tasks
Step 1: Create a Project in Visual Basic
Step 2: Create a User Interface
Concepts
Closer Look: Understanding Properties, Methods, and Events
Other Resources
Creating Your First Visual Basic Program
Visual Basic Language Concepts
A balloon has properties (Color, Height, and Diameter), responds to events (Puncture), and can perform methods (Deflate,
MakeNoise).
Properties
If you could program a balloon, the Visual Basic code might resemble the following "code," which sets a balloon's properties.
Balloon.Color = Red
Balloon.Diameter = 10
Balloon.Inflated = True
Notice the order of the code—the object (Balloon), followed by the property (Color), followed by the assignment of the value
(= Red). You could change the balloon's color by substituting a different value.
Methods
A balloon's methods are called like this.
Balloon.Inflate
Balloon.Deflate
Balloon.Rise(5)
The order is similar to that of a property—the object (a noun), followed by the method (a verb). In the third method, there is an
additional item, called an argument, which specifies the distance the balloon will rise. Some methods will have one or more
arguments to further describe the action to be performed.
Events
The balloon might respond to an event as follows.
Sub Balloon_Puncture()
Balloon.MakeNoise("Bang")
Balloon.Deflate
Balloon.Inflated = False
End Sub
In this case, the code describes the balloon's behavior when a Puncture event occurs: call the MakeNoise method with an
argument of "Bang" (the type of noise to make), then call the Deflate method. Since the balloon is no longer inflated, the
Inflated property is set to False.
While you can't actually program a balloon, you can program a Visual Basic form or control. As the programmer, you are in
charge. You decide which properties should be changed, which methods should be invoked, or which events should be
responded to in order to achieve the desired appearance and behavior.
Next Steps
In the next lesson, you will add a line of code to your program.
Next Lesson: Step 4: Add Visual Basic Code.
See Also
Other Resources
Visual Basic Programming Guide
Visual Basic Language Concepts
Closer Look
You may have noticed that when the Code Editor opened, it already contained some code that looked like this:
Private Sub Button1_Click(ByVal sender As System.Object...
|
End Sub
This code is an event handler, also called a Sub procedure. Any code inside this procedure (between Sub and End Sub) runs
each time the button is clicked. You may also have noticed that the cursor was located inside the event procedure, so all you
had to do was type.
The code that you typed (WebBrowser1.Navigate(TextBox1.Text)) tells the program to use the Navigate method of the
WebBrowser control (named WebBrowser1) with an argument of TextBox1.Text (the value contained in the Text property
of the TextBox control). To learn more about properties, methods, and events see
Closer Look: Understanding Properties, Methods, and Events
If you don't understand the code, don't worry—you will learn a lot more about writing code in following lessons.
Next Steps
Your application is now complete! In the next lesson, you will run your first Visual Basic application.
Next Lesson: Step 5: Run and Test Your Program
See Also
Tasks
Step 1: Create a Project in Visual Basic
Step 2: Create a User Interface
Step 3: Customize Looks and Behavior
Concepts
Closer Look: Understanding Properties, Methods, and Events
Other Resources
Creating Your First Visual Basic Program
Visual Basic Language Concepts
3. In the text box, type http://www.microsoft.com and click the Go! button.
The WebBrowser control in your program navigates to the Microsoft home page. From there, you can navigate through
any related links. To visit another Web page, type the address in the text box and click the Go! Button.
4. To close the program, on the Debug menu, click Stop Debugging.
Tip
You can also end the program by clicking the Close button on the top-right corner of the form.
Closer Look
In this lesson you ran your program to see if it worked. For most Visual Basic programs, you will repeat this process many
times. Typically after adding some new code, you will run the program to see if the code does what you expected it to do—if it
doesn't, you will need to fix it. This process is called debugging; it will be discussed in detail in a later lesson.
It may seem like magic that your program navigates to a Web page and displays it, all as a result of you writing a single line of
code. This is the beauty of Visual Basic—all the necessary code is built into the WebBrowser control, saving you time and
effort. If you had to do it all yourself, it would take hundreds or even thousands of lines of code!
Troubleshooting
If your program does not run or display the Web page, there are a few things you can check:
Make sure you are connected to the Internet. Open Internet Explorer and try to navigate to the Microsoft home page. If it
works in Internet Explorer, it should also work in your program.
Make sure that you typed the address (http://www.microsoft.com) correctly.
Go back and check Step 2: Create a User Interface and make sure that you put the correct controls on the form.
Go back to Step 4: Add Visual Basic Code and make sure that you typed the code correctly.
Next Steps
Congratulations! Your first Visual Basic program is complete. You have demonstrated how powerful programs can be
developed quickly and easily by using Visual Basic. In the following lessons, you will be introduced to more features of the
Visual Basic programming language.
Next Lesson: Introduction to the Visual Basic Programming Language
See Also
Tasks
Step 1: Create a Project in Visual Basic
Step 2: Create a User Interface
Step 3: Customize Looks and Behavior
Step 4: Add Visual Basic Code
Other Resources
Creating Your First Visual Basic Program
What Went Wrong? Finding and Fixing Errors through Debugging
Visual Basic Language Concepts
Representing Words, Numbers, and Values with Variables How variables store values and represent information, along w
ith how to use variables.
Words and Text: Using String Variables to Organize Words How to use a String variable to represent words and text.
Arrays: Variables That Represent More Than One Value How to use an Array variable to represent several values of th
e same type.
Arithmetic: Creating Expressions With Variables And Operators How to write code that performs arithmetic.
Comparisons: Using Expressions to Compare Values How to write code that compares numeric values.
Making Your Program Repeat Actions: Looping With the For...Next Loop How to write code that repeats actions in you
r program and counts how many times these
actions have been performed.
Making Your Program Choose Between Two Possibilities: The If...Then Statement How to write code that does different things i
n response to different conditions.
What To Do When Something Goes Wrong: Handling Errors How to write code that handles errors in your
programs. You will also learn about the differ
ent types of errors.
Closer Look: Data Types How data is stored using the different types of v
ariables.
Closer Look: Converting from One Variable Type to Another How to convert data from one type to another, a
long with some common pitfalls of this process.
Closer Look: Using Do...While and Do...Until to Repeat Until a Condition is Met How to use the Do...While and Do...Until state
ments to repeat code based on certain condition
s.
Closer Look: Using Select Case to Decide Between Multiple Choices How to run code based on multiple conditions,
where there are many choices.
Visual Basic Guided Tour More of what you can do with the Visual Basic 2
005 programming language
Visual Basic Language Concepts
You will learn more about syntax later, and tools in Visual Basic such as IntelliSense provide you with guidance in using the
correct syntax when writing programs.
The language you write and speak also has structure: for example, a book has chapters with paragraphs that contain sentences.
Programs written in Visual Basic also have a structure: modules are like chapters, procedures are like paragraphs, and lines of
code are like sentences.
Next Steps
In this lesson, you learned what a programming language is and how it works. In the next lesson, you will start learning how to
use the Visual Basic programming language. Don't worry—you'll be speaking Visual Basic in no time at all!
Next Lesson: Representing Words, Numbers, and Values with Variables
See Also
Tasks
Representing Words, Numbers, and Values with Variables
Concepts
Closer Look: Understanding Properties, Methods, and Events
Introduction to the Visual Basic Programming Language
Other Resources
Creating Your First Visual Basic Program
Visual Basic Programming Guide
Visual Basic Language Concepts
This line of code tells the program that you want to use a variable named aNumber, and that you want it to be a variable that
stores whole numbers (the Integer data type).
Because aNumber is an Integer, it can store only whole numbers. If you had wanted to store 42.5, for example, you would have
used the Double data type. And if you wanted to store a word, you'd use a data type called a String. One other data type
worth mentioning at this point is Boolean, which can store a True or False value.
Here are more examples of how to declare variables.
VB
Dim aDouble As Double
Dim aName As String
Dim YesOrNo As Boolean
For more information about other variable types, see Closer Look: Data Types.
Assigning Variables
You assign a value to your variable with the = sign, which is sometimes called the assignment operator, as shown in the
following example.
VB
aNumber = 42
This line of code takes the value 42 and stores it in the previously declared variable named aNumber.
Declaring and Assigning Variables with a Default Value
As shown above, you can declare a variable on one line of code, and then later assign the value on another line. This can result
in an error if you try to use the variable before assigning it a value.
For that reason, it is a better idea to declare and assign variables on a single line. Even if you don't yet know what value the
variable will hold, you can assign a default value. The code for declaring and assigning the same variables shown earlier would
look like the following.
VB
Dim aDouble As Double = 0
Dim aName As String = "default string"
Dim YesOrNo As Boolean = True
By declaring variables and assigning default values on a single line, you can prevent possible errors. You can still use
assignment to give the variable a different value later on.
Try It!
In this exercise, you will write a short program that creates four variables, assigns them values, and then displays each value in
a window called a message box. Let's begin by creating the project where the code will be stored.
To create the project
1. If it is not already open, open Visual Basic from the Windows Start menu.
2. On the File menu, click New Project.
3. In the New Project dialog box on the Templates pane, click Windows Application.
4. In the Name box, type Variables and then click OK.
Visual Basic will create the files for your program and open the Form Designer.
Next, you'll create the variables.
To create variables and display their values
1. Double-click the form.
The Code Editor opens to a section of code called Form1_Load. This section of code, which is called a procedure, contains
instructions that will be carried out when the form is first loaded into memory.
2. In the Form1_Load procedure, type the following code.
VB
Dim anInteger As Integer = 42
Dim aSingle As Single = 39.345677653
Dim aString As String = "I like candy"
Dim aBoolean As Boolean = True
This code declares four variables—an Integer, a Single, a String, and a Boolean—and assigns their default values.
Tip
As you typed the code, you may have noticed that after you typed As, a list of words appeared below the cursor. This fe
ature is called Intellisense. It allows you to just type the first few letters of a word until the word is selected in the list. O
nce selected, you can press the TAB key to finish the word.
Note
Whenever you represent actual text in a program, you must enclose it in quotation marks (""). This tells the program to
interpret the text as actual text instead of as a variable name. When you assign a Boolean variable a value of True or F
alse, you do not enclose the word in quotation marks, because True and False are Visual Basic keywords with special
meanings of their own.
3. Beneath the code you wrote in the previous step, type the following.
VB
MsgBox(anInteger)
MsgBox(aSingle)
MsgBox(aString)
MsgBox(aBoolean)
VB
End
The first four lines of code tell the program to display each value that you assigned in the previous step in a new window,
using the MsgBox function. The final line tells the program to end after executing this procedure—it uses the End
statement.
4. Press F5 to run your program.
Click OK for each window as it appears. Note that the value of each variable is displayed in turn, and then the program
ends. After the program has finished, you can go back and change the values that are assigned in the code and run the
application again—you'll see that the new values are displayed.
Next Steps
In this lesson, you learned the basics about variables. In the next lesson, you will learn more about String variables.
Next Lesson: Words and Text: Using String Variables to Organize Words
See Also
Tasks
Words and Text: Using String Variables to Organize Words
Closer Look: Converting from One Variable Type to Another
Concepts
The Basics: How Programming Works
Closer Look: Data Types
Visual Basic Language Concepts
When assigning actual text (also called a string literal) to a String variable, the text must be enclosed in quotation marks ("").
You can also use the = character to assign one String variable to another String variable, as shown in this example.
VB
Dim aString As String = "This is a string"
The previous code sets the value of bString to the same value as aString (This is a string).
You can use the ampersand (&) character to sequentially combine two or more strings into a new string, as shown below.
VB
Dim aString As String = "Across the Wide"
Dim bString As String = "Missouri"
Dim cString As String = ""
cString = aString & bString
The previous example declares three String variables and respectively assigns "Across the Wide" and "Missouri" to the first
two, and then assigns the combined values of the first two to the third variable. What do you think the value of cString is? You
might be surprised to learn that the value is Across the WideMissouri because there is no space at the end of aString or at
the beginning of bString. The two strings are simply joined together. If you want to add spaces or anything else between two
strings, you must do so with a string literal, such as " ", as shown below.
VB
Dim aString As String = "Across the Wide"
Dim bString As String = "Missouri"
Dim cString As String = ""
cString = aString & " " & bString
The text contained in cString now reads as Across the Wide Missouri.
Try It!
To join strings
1. On the File menu, click New Project.
2. In the New Project dialog box:
a. In the Templates pane, click Windows Application.
b. In the Name box, type Concatenation.
c. Click OK.
A new Windows Forms project opens.
3. Double-click the form to open the Code Editor.
4. In the Form1.Load event procedure, declare four string variables and assign the string values, as shown below:
VB
Dim aString As String = "Concatenating"
Dim bString As String = "Without"
Dim cString As String = "With"
Dim dString As String = "Spaces"
5. Add the following code to concatenate the strings and display the results:
VB
' Displays "ConcatenatingWithoutSpaces".
MsgBox(aString & bString & dString)
The text displayed in the message box is the result of joining the string variables that were assigned in a previous step. In
the first box, the strings are joined together without spaces. In the second, spaces are explicitly inserted between each
string.
Next Steps
In this lesson, you learned how to declare and assign strings, and how to join strings with the concatenation operator &. In the
next lesson, "Arrays: Variables That Represent More Than One Value," you will learn about creating variables to store groups of
similar items.
Next Lesson: Arrays: Variables That Represent More Than One Value
See Also
Tasks
Arrays: Variables That Represent More Than One Value
Representing Words, Numbers, and Values with Variables
Concepts
Introduction to the Visual Basic Programming Language
Visual Basic Language Concepts
You declare an array variable by putting parentheses after the variable name. If you know how many values you need to store,
you can also specify the size of the array in the declaration as follows.
VB
Dim players(9) As String
The size of the array is 9 because a baseball team has 9 players. An array is made up of a number of values, or elements,
starting with element 0 and ending with one less than the number specified in the declaration. In this case, the array contains
the elements 0 through 8, for a total of nine elements. When you want to refer to one of the players on the team, you just
subtract 1. For example, to reference the first player, you reference element 0, to reference the ninth player, you reference
element 8.
Assigning Values to Arrays
As with other types of values, you need to assign values to arrays. To do so, you refer to the element number as part of the
assignment, as shown below.
VB
players(0) = "John"
players(3) = "Bart"
In the above code, the value John is assigned to the first element of the array (element 0) and the value Brett is assigned to the
fourth element (element 3). The elements of the array don't have to be assigned in order, and any unassigned element will
have a default value—in this case, an empty string.
As with other types of values, you can declare and assign values to an array on a single line as follows.
VB
Dim players() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9}
In this case, curly brackets indicate a list of values. The values are assigned to elements in the order listed. Notice that size of
the array isn't specified—it is determined by the number of items that you list.
Retrieving Values from Arrays
Just as you use numbers to specify an item's position in an array, you use the element number to specify which value you want
to retrieve.
VB
Dim AtBat As String
AtBat = players(3)
The above code retrieves the fourth element of the array and assigns it to the string variable AtBat.
Try It!
To store values in an array
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type MyFirstArray and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag a Textbox control onto the form.
5. From the Toolbox, drag a Button control onto the form.
6. Double-click the Button to open the Code Editor.
7. In the Button1_Click event procedure, add the following code:
VB
Dim players() As String = {"Dan", "Fred", "Bart", "Carlos", _
"Ty", "Juan", "Jay", "Sam", "Pedro"}
Dim i As Integer = CInt(Textbox1.Text)
MsgBox(players(i) & " is on first base.")
Notice that the above code uses the CInt function to convert the String value (TextBox1.Text) to an Integer (i). You can
learn more about conversions in Closer Look: Converting from One Variable Type to Another.
8. Press F5 to run the program.
9. Type a number between 0 and 8 in the text box and click the button. The name corresponding to that element is
displayed in a message box.
Tip
You should write additional code to check that the data entered is valid. For example, you can check that the value enter
ed is a numeric value between 0 and 8. For more information, see
What To Do When Something Goes Wrong: Handling Errors.
Next Steps
In this lesson, you learned how to use arrays to store and retrieve groups of similar values.
In the next lesson, you will learn how to use arithmetic operators to create expressions.
Next Lesson: Arithmetic: Creating Expressions With Variables And Operators
See Also
Tasks
Arithmetic: Creating Expressions With Variables And Operators
Words and Text: Using String Variables to Organize Words
Concepts
Overview of Arrays in Visual Basic
Visual Basic Language Concepts
This example declares a new Integer variable called anInteger and assigns the value returned by 5 + 4 to it.
Arithmetic Operators
A common use for expressions is to perform arithmetic on variables: addition, subtraction, multiplication, or division. The
following table describes the operators commonly used for arithmetic.
Operator Description Example
+ (addition) Returns the sum of two operands 5+4
The kind of variable that you use when performing arithmetic can affect the result. Dividing two numbers often results in a
return value that is not a whole number. For example, when you divide 3 by 2, the result is 1.5. If you assigned the return value
of that expression to an Integer variable, it would be rounded to the nearest whole number, 2. When performing division, you
should use a Double variable to store the return value.
Note
You can also convert a variable from one data type to another by using the conversion functions of Visual Basic. For more inf
ormation, see Closer Look: Converting from One Variable Type to Another.
Try It!
To add numbers
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type Arithmetic and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag two Textbox controls onto the form.
5. From the Toolbox, drag a Button control onto the form.
6. Double-click the Button to open the Code Editor.
7. In the Button1_Click event procedure, type the following code.
VB
Dim A As Double = Textbox1.Text
Dim B As Double = Textbox2.Text
MsgBox(A + B)
MsgBox(A - B)
MsgBox(A * B)
MsgBox(A / B)
The first two lines declare the variables A and B, which will hold the numeric values used in this program, and assign the
values of the two TextBox controls (their text) to the variables A and B.
The final four lines create expressions with the two variables and each of the basic arithmetic operators, and display the
results of those expressions in a message box.
8. Press F5 to run the application.
9. Type a number in each of the text boxes and click Button1.
Note
If you type any other character into the text boxes, an error will occur.
Expressions are created using the two numbers that you enter and each of the four basic arithmetic operators (addition,
subtraction, multiplication, and division). The result of each expression is displayed in a message box.
Next Steps
In this topic, you learned about creating and using expressions. You also learned about operands and operators, and how to
construct an expression. At this point, you can either continue to the next lesson,
Comparisons: Using Expressions to Compare Values or learn more about converting variables to different types in
Closer Look: Converting from One Variable Type to Another. If you choose "Closer Look," you will complete it and then
proceed to the next lesson.
See Also
Tasks
Closer Look: Converting from One Variable Type to Another
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Concepts
This code declares an Integer variable called anInteger, assigns it a value of 54, and then converts that value to text and
displays it in a message box by calling the CStr function.
6. Press F5 to build and run your application. A message box that reads 54 is displayed.
Let's try something just for fun. In the Code Editor, change the line that reads MsgBox(CStr(anInteger)) to read
MsgBox(anInteger), and press F5 to run. What happens? The program behaves exactly as it did before. Visual Basic is
smart enough to know that what you really want is to convert the Integer to text to display in the message box.
However, you cannot rely on this behavior for all cases—there are many variable types that cannot be automatically
converted. Therefore, it is good practice to always use the CStr function, even if a variable would automatically be
converted to text.
In addition to converting Integer variables to text, the CStr function can be used on any numeric data type, such as Double or
Long. It can also be used to convert the Date and Boolean data types to text. For more information on data types, see
Closer Look: Data Types.
Converting Between Numeric Data Types
As you learned in the arithmetic lesson, sometimes the result of an arithmetic operation can't be expressed as an Integer. Just
as Visual Basic has a function for converting numbers to text, it also has functions for converting variables from one numeric
data type to another. For example, you can use the CDbl (Convert to Double) function in an arithmetic operation to return a
fractional number when working with Integer variables. The following procedure shows how to use the CDbl function when
dividing two integers.
Try It!
To convert numeric data types
1. In the Code Editor, delete the code that you entered in the previous procedure and type the following:
VB
Dim A As Integer = 1
Dim B As Integer = 2
MsgBox(CDbl(A / B))
This code declares two Integer variables (A and B), assigns them values of 1 and 2, and then converts the result of the
division operation (A / B) using the CDbl function and displays it in a message box.
2. Press F5 to build and run your application. A message box that reads 0.5 is displayed.
Visual Basic has functions for other types of numeric variables as well. For example, if you add two variables of the type
Double and want to round the result to the nearest whole number, use the CInt function. Other numeric conversion functions
include CByte, CDec, CLng, and CShort. For a list of all the Visual Basic conversion functions, see Type Conversion Functions.
Next Steps
In this lesson, you learned how to convert numeric variables to text, and also how to convert between different types of
numeric variables. In the next lesson, Comparisons: Using Expressions to Compare Values, you will learn how to evaluate
expressions.
See Also
Tasks
Arithmetic: Creating Expressions With Variables And Operators
Concepts
Closer Look: Data Types
Other Resources
Type Conversions in Visual Basic
Visual Basic Language Concepts
<> (not equal to) Returns True if the number on the left is not equal to the number on the right. 5 <> 4 (true
)
4 <> 5 (true
)
4 <> 4 (fals
e)
> (greater than) Returns True if the number on the left is greater than the number on the right. 5 > 4 (true)
4 > 5 (false)
4 > 4 (false)
< (less than) Returns True if the number on the left is less than the number on the right. 5 < 4 (false)
4 < 5 (true)
4 < 4 (false)
>= (greater than or equal Returns True if the number on the left is greater than or equal to the number on the ri 5 >= 4 (true
to) ght. )
4 >= 5 (fals
e)
4 >= 4 (true
)
<= (less than or equal to) Returns True if the number on the left is less than or equal to the number on the right. 5 <= 4 (fals
e)
4 <= 5 (true
)
4 <= 4 (true
)
Try It!
To compare expressions
1. On the File menu, click New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type Comparison and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag two Textbox controls onto the form.
5. From the Toolbox, drag a Button control onto the form.
6. Double-click the Button to open the Code Editor.
7. In the Button1_Click event handler, type the following code:
VB
Dim A As Double = CDbl(Textbox1.Text)
Dim B As Double = CDbl(Textbox2.Text)
MsgBox(A > B)
MsgBox(A < B)
MsgBox(A = B)
The first two lines declare the variables A and B, which will hold the numeric values used in this program; they use the
CDbl statement to convert the text from Textbox1 and Textbox2 into numeric values. Finally, the last three lines create
expressions to compare the two variables using three basic comparison operators, and display the results of those
expressions in three message boxes.
8. Press F5 to run the application.
9. Type a number in each of the text boxes and click Button1.
The first message box will display True if A (the number that you entered in the first text box) is greater than B (the
number that you entered in the second text box); otherwise it will display False. The second message box will display
True if A is less than B, and the third message box will display True if both numbers are the same.
Try typing different numbers into the text boxes to see how the results change.
Next Steps
In this lesson, you learned how to use comparison operators to compare numeric values. In the next lesson, you will learn how
to create and call a procedure—code that performs an action.
Next Lesson: Making Your Computer Do Something: Writing Your First Procedure
See Also
Tasks
Arithmetic: Creating Expressions With Variables And Operators
Closer Look: Converting from One Variable Type to Another
Making Your Program Choose Between Two Possibilities: The If...Then Statement
Concepts
Comparison Operators in Visual Basic
Visual Basic Language Concepts
That's all there is to it! When the program reaches that line, it will jump to the PlaySound procedure and execute the code
contained there. The program will then jump back to the next line that follows the call to PlaySound.
You can call as many procedures as you like. Procedures are run in the order that they are called. For example, you might also
have a procedure called DisplayResults; to execute it after executing the PlaySounds procedure, call the procedures as shown
below.
PlaySounds
DisplayResults
Functions are different, because functions not only execute code, they also return a value. For example, imagine a function
called GetDayOfWeek that returns an Integer indicating the day of the week. You call this function by first declaring a
variable in which to store the return value, and then assigning the returned value to the variable for later use, as shown below.
Dim Today As Integer
Today = GetDayOfWeek
In this example, the value returned by the function is copied to the variable named Today and stored for later use.
Writing Procedures
You write procedures by first writing a procedure declaration. A procedure declaration does several things: states whether the
procedure is a function or a sub, names the procedure, and details any parameters the procedure might have (parameters will
be discussed in detail later in this lesson). The following is an example of a simple procedure declaration.
VB
Sub MyFirstSub()
End Sub
The Sub keyword tells the program that this procedure is a sub and will not return a value. The name of the sub (MyFirstSub)
comes next, and the empty parentheses indicate that there are no parameters for this procedure. Finally, the End Sub keyword
indicates the end of the subroutine. All code that is to be executed by this sub goes between these two lines.
Declaring functions is similar, but with the added step that the return type (such as Integer, String, etc.) must be specified. For
example, a function that returned an Integer might look like this.
VB
Function MyFirstFunction() As Integer
End Function
The As Integer keywords indicate that this function will return an Integer value. To return a value from a function, use the
Return keyword, as shown in the following example.
VB
Function GetTheNumberOne() As Integer
Return 1
End Function
This function uses the built-in Now procedure to get the current time, then uses the CStr function to convert the value
returned by Now into a human-readable String. Finally, that String value is returned as the result of the function.
6. Above the function you added in the previous step, add the following Sub.
VB
Sub DisplayTime()
MsgBox(GetTime)
End Sub
This sub calls the function GetTime and displays the result returned by it in a message box.
7. Finally, add a line to the Form1_Load event handler that calls the DisplayTime sub, as shown below.
VB
DisplayTime()
8. Press F5 to run the program.
When the program starts, the Form1_Load event procedure is executed. This procedure calls the DisplayTime sub, so
program execution jumps to the DisplayTime sub procedure. That sub in turn calls the GetTime function, so program
execution then jumps to the GetTime function. This function returns a String representing the time to the DisplayTime
sub procedure, which then displays that string in a message box. After the sub is finished executing, the program
continues normally and displays the form.
Parameters in Functions and Subs
At times you will need to provide additional information to your procedures. For example, in the PlaySound procedure, you
may want to play one of several different sounds. You can provide the information on which sound to play by using
parameters.
Parameters are a lot like variables. They have a type and a name, and they store information just like variables. They can be
used just like variables in a procedure. The two main differences between parameters and variables are:
Parameters are declared in the procedure declaration, not in individual lines of code.
Parameters are usable only in the procedure they are declared in.
Parameters are declared in the procedure declaration in the parentheses that follow the procedure name. The As keyword is
used to declare the type, and each parameter is generally preceded by the ByVal keyword. This keyword will be added
automatically by Visual Basic if you do not add it, and it has a fairly advanced function that is beyond the scope of this lesson to
explain.
An example of a sub with parameters is shown below.
VB
Sub PlaySound(ByVal SoundFile As String, ByVal Volume As Integer)
My.Computer.Audio.Play(SoundFile, Volume)
End Sub
You would then call the sub with the values for the parameters as shown below.
VB
PlaySound("Startup.wav", 1)
You can also declare parameters for functions in exactly the same way you would for subs.
Try It!
To create a function with parameters
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type parameters and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag two Textbox controls onto the form.
5. From the Toolbox, drag a Button control onto the form.
6. Double-click the Button to open the Code Editor.
7. Immediately after the End Sub line of the Button1_Click event handler, add the following procedure:
VB
Function AddTwoNumbers(ByVal N1 As Integer, ByVal N2 As Integer) _
As Integer
Return N1 + N2
End Function
This code declares two integers and converts the text in the two text boxes to integer values. It then passes those values
to the AddTwoNumbers function and displays the value returned in a message box.
9. Press F5 to run the program.
10. Type a number value in each text box and click the button. The two numbers are added, and the result is displayed in a
message box.
Next Steps
In this lesson, you learned the difference between functions and subs, and how to create each of these two procedures. You
have also learned how to call procedures and how to create procedures that have parameters.
In the next lesson, you will learn how to use the For...Next statement to repeat actions.
Next Lesson: Making Your Program Repeat Actions: Looping With the For...Next Loop
See Also
Tasks
Comparisons: Using Expressions to Compare Values
Concepts
Procedures in Visual Basic
Visual Basic Language Concepts
The For...Next loop begins with a counter variable, i. This is a variable that the loop uses to count the number of times it has
executed. The next line (For i = 1 to 10) tells the program how many times to repeat the loop and the values i is going to
have.
When the code enters the For...Next loop, it starts with i containing the first value (in this case 1). The program then executes
the lines of code between the For line and the Next line, in this case calling the DisplayNumber method with a parameter of i
(in this case also 1).
When the line Next is reached, 1 is added to i and program execution jumps back to the For line again. This repeats until the
value of i is larger than the second number in the For line, in this case 10. When this occurs, the program continues with any
code after the Next line.
Try It!
To use the For...Next statement
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type ForNext and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag one TextBox control and one Button control onto the form.
5. Double-click the Button to open the Code Editor
6. In the Button1_Click event handler, type the following code:
VB
Dim i As Integer = 0
Dim NumberOfRepetitions As Integer = CInt(Textbox1.Text)
For i = 1 To NumberOfRepetitions
MsgBox("This line has been repeated " & i & " times")
Next
In the above code, the Do While line evaluates the variable sum to see if it is less than 100: If it is, the next line of code is run; if
not, then it moves to the next line of code following Loop. The Loop keyword tells the code to go back to the DoWhile line and
evaluate the new value of sum.
Try It!
To use a Do...While statement
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type DoWhile and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag one TextBox control and one Button control onto the form.
5. Double-click the Button to open the Code Editor.
6. In the Button1_Click event handler, type the following code:
VB
Dim sum As Integer = 0
Dim counter As Integer = 0
Do While sum < 100
sum = sum + CInt(Textbox1.Text)
counter = counter + 1
Loop
MsgBox("The loop has run " & CStr(counter) & " times!")
This code is similar to the code for the Do...While statement, except that this time the code is evaluating the sum variable to see
if it is equal to or greater than 100.
Try It!
To use a Do...Until statement
1. Add the following code beneath the MsgBox line.
VB
Dim sum2 As Integer = 0
Dim counter2 As Integer = 0
Do Until sum2 >= 100
sum2 = sum2 + CInt(Textbox1.Text)
counter2 = counter2 + 1
Loop
MsgBox("The loop has run " & CStr(counter2) & " times!")
When this code is run, the condition (the part between If and Then) is evaluated. If the condition is true, the next line of code is
run and a message box is displayed; if it is false, the code skips to the End If line. In other words, the code states "If today is
Monday, then display the message."
Try It!
To use the If...Then statement
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type IfThen and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor.
5. In the Form1_Load event handler, type the following code.
VB
If My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Saturday Or _
My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Sunday Then
MsgBox("Happy Weekend!")
End If
7. On the Debug menu, choose Stop Debugging to end the program. Keep this project open. You will add to it in the next
procedure, "To use the Else clause".
You may have noticed in the above example that the If...Then statement used the Or operator to evaluate multiple conditions
("if it is Saturday Or if it is Sunday"). You can use the Or and And operators to evaluate as many conditions as you want in a
single If...Then statement.
The Else Clause
You have seen how to use the If...Then statement to run code if a condition is true—but what if you want to run one set of
code if a condition is true, and another if it is false? In this case, you can use the Else clause. The Else clause allows you to
specify a block of code that will be run if the condition is false. The following example demonstrates how the Else clause works.
VB
If My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Friday Then
MsgBox("Today is Friday!")
Else
MsgBox("It isn't Friday yet!")
End If
In this example, the expression is evaluated; if it is true, then the next line of code is run, and the first message box is displayed.
If it is false, then the code skips to the Else clause, and the line following Else is run, displaying the second message box.
Try It!
To use the Else clause
1. Change the code in the If...Then statement to the following.
VB
If My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Saturday Or _
My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Sunday Then
MsgBox("Happy Weekend!")
Else
MsgBox("Happy Weekday! Don't work too hard!")
End If
2. Press F5 to run your program. Your program will now display a message box stating whether it is a weekend or a
weekday, with appropriate content.
Note
You can change the day of the week by double-clicking the time on the Windows taskbar, if you want to test the executi
on of both code blocks. (The taskbar is the bar that contains the Windows Start button; by default, it is at the bottom of
the desktop, and the time appears in the right corner.)
Next Steps
In this lesson, you learned how to use the If...Then statement together with the Else clause to make your program selectively
run blocks of code based on conditions at run time. For your next lesson, you can choose to either explore how to select code
to run by reading Closer Look: Using Select Case to Decide Between Multiple Choices, or, you can continue with the next
lesson, What To Do When Something Goes Wrong: Handling Errors.
See Also
Tasks
Making Your Program Repeat Actions: Looping With the For...Next Loop
Comparisons: Using Expressions to Compare Values
Reference
If...Then...Else Statement (Visual Basic)
Visual Basic Language Concepts
When this code is run, the Select Case line determines the value (Color) of the expression. Assume that Color is a String
variable and that this variable is a parameter for a method that contains the Select Case statement. The value of Color is then
compared to the value for first Case statement. If the value matches, the next line of code is run, and then the code skips to the
End Select line; if the value doesn't match, then the next Case line is evaluated.
The Case statement can take many different forms—in the example above, it is a String. However, it can be any data type or
expression.
You can evaluate a range of numbers by using the To keyword, as follows:
VB
Case 1 To 10
In the above code, if the value of Color is yellow, the code compares it with the first three Case lines without finding a match.
When the Case Else line is reached, the next line of code is run before moving to End Select.
To use the Select Case statement
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type SelectCase and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag one TextBox control and one Button control onto the form.
5. Double-click the button to open the Code Editor.
6. In the Button1_Click event handler, type the following code.
VB
Dim Number As Integer = CInt(Textbox1.Text)
Select Case Number
Case 1
MsgBox("Less than 2")
Case 2 To 5
MsgBox("Between 2 and 5")
Case 6, 7, 8
MsgBox("Between 6 and 8")
Case 9 To 10
MsgBox("Greater than 8")
Case Else
MsgBox("Not between 1 and 10")
End Select
First, the code in the Try block is executed. If it runs without error, the program skips the Catch block and runs the code in the
Finally block. If an error does occur in the Try block, execution immediately jumps to the Catch block, and the code there is
run; then the code in the Finally block is run.
Try It!
To use the Try...Catch block
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type TryCatch and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag one TextBox control and one Button control onto the form.
5. Double-click the Button to open the Code Editor.
6. In the Button1_Click event handler, type the following code:
VB
Try
Dim aNumber As Double = CDbl(Textbox1.Text)
MsgBox("You entered the number " & aNumber)
Catch
MsgBox("Please enter a number.")
Finally
MsgBox("Why not try it again?")
End Try
Now that you have created a basic user interface, you will need to add a little bit of code to your program, and then it will be
ready to test!
To add code and test your program
1. Double-click the Button control to open the Code Editor.
The Code Editor opens the Button1_Click event handler.
2. Add the following line of code to the Button1_Click event handler.
VB
MsgBox("Your Name is " & Textbox1.Text)
3. Press F5 to run your program.
4. When the form appears, type your name in the TextBox control and click the button. A message box appears, displaying
the text in the TextBox control. Change the text and click the button again. Each time you click the button, the updated
text is displayed.
Next Steps
In this topic, you learned about the Label and TextBox controls, and how they can be used to display and receive text. In the
next topic, you will learn how to create methods that handle control events. Though you've already learned how to create some
basic event handlers, such as the Button_Click event handler, you will learn how to create methods to handle some of the
other events that happen to controls.
Next Lesson: Making Your Program React to the User: Creating an Event Handler
See Also
Tasks
Interacting with the User: Using Buttons
Reference
Label Control Overview (Windows Forms)
TextBox Control Overview (Windows Forms)
Visual Basic Language Concepts
10. Press F5 to run your application. Pass the mouse pointer over the button. Note that when the mouse pointer passes over
Button1, the text of the button changes.
Adding another Event Handler
You might have noticed in the previous example that though the text of Button1 changes when the mouse pointer passes over
it, the text does not change back when the mouse pointer leaves. If you want the text to change when the mouse is no longer
over the button, you must handle the MouseLeave event in addition to the MouseEnter event.
To handle the MouseLeave event
1. In the Code Editor, make certain that Button1 is selected in the left-hand drop-down box, and then select MouseLeave
from the right-hand drop-down box.
A new event handler called Button1_MouseLeave appears in the Code Editor.
2. In the Button1_MouseLeave event handler, type the following code.
VB
Button1.Text = "The mouse has left"
You now have a single method that handles the MouseEnter event for both controls, but how does the event handler knows
which control raised the event? If you look again at the Method declaration, you will notice the clause ByVal sender As
Object—the Sender keyword tells the event handler which object (in this case which control) raised the event.
Try It!
To share an event handler
1. Open the EventHandler project that you created in the previous lesson. If you didn't save it, you will first need to go back
to the previous lesson, Making Your Program React to the User: Creating an Event Handler, and complete the procedures
in that lesson.
2. In Solution Explorer, select Form1.vb, and then on the View menu choose Designer.
3. From the Toolbox, drag another Button control onto the form.
4. In the Properties window, set the AutoSize property to True.
5. On the View menu, choose Code to open the Code Editor.
6. In the Button1_MouseEnter method declaration (Private Sub Button1_MouseEnter(ByVal sender As Object, ByVal
e As System.EventArgs) Handles Button1.MouseEnter), change the Handles clause to read Handles
Button1.MouseEnter, Button2.MouseEnter.
7. In the body of the event declaration, replace the code with the following.
VB
If sender.Equals(Button1) Then
Button1.Text = "The mouse has entered Button1"
Else
Button2.Text = "The mouse has entered Button2"
End If
This code checks to see if the sender was Button1—if so, then Button1's Text property is updated; if not, then
Button2's Text property is updated.
8. In the Button1_MouseLeave method declaration, change the Handles clause to read as follows.
Handles Button1.MouseLeave, Button2.MouseLeave.
9. In the body of the event declaration, replace the code with the following.
VB
sender.Text = "The mouse has left"
In this case, the code sets the Text property of the sender (either Button1 or Button2) to the same string.
10. Press F5 to run your application.
Now when the mouse pointer passes over the button, the text changes to The mouse has entered, along with the name
of the button, and when the mouse is no longer over the button, the text changes back to The mouse has left.
Try adding more controls to the form and modifying the Handles clauses to include them—they don't even have to be
the same kind of controls!
Next Steps
In this lesson, you learned how to share a single event handler between multiple controls. In the next lesson, you will learn how
to use two new kinds of controls, the CheckBox and RadioButton controls, to present choices to users.
Next Lesson: Getting User Choices: Using Check Boxes and Radio Buttons
See Also
Tasks
Making Your Program React to the User: Creating an Event Handler
Visual Basic Language Concepts
6. In the Properties window, change the Text property of Button1 to read Order Pizza.
7. In the form, double-click the button; this opens the Button1_Click event handler in the Code Editor.
8. Add the following code to the Button1_Click event handler:
VB
Dim toppings As String = ""
If CheckBox1.Checked = True Then
toppings &= "Cheese "
End If
If CheckBox2.Checked = True Then
toppings &= "Peppers "
End If
If CheckBox3.Checked = True Then
toppings &= "Mushrooms"
End If
If toppings <> "" Then
MsgBox("Your pizza has the following toppings: " & toppings)
End If
9. Press F5 to run your program. When the form appears, select some toppings and click the button. A message box
indicating your choice of pizza toppings is displayed.
Using Radio Buttons to Make Exclusive Choices
You just learned how to allow a user to choose any or all of several options. But what if you want the user to choose only one
of several options? In this case, you can use the RadioButton control.
Unlike check boxes, radio buttons (also known as option buttons) always work as part of a group. Selecting one radio button
immediately clears all the other radio buttons in the group. Defining a group of radio buttons tells the user, "Here is a set of
choices from which you can choose one and only one."
You can use groups of RadioButton controls to allow users to choose between exclusive options. For example, you might
allow users to choose either regular sauce or spicy sauce on their pizza, but not both. Like a CheckBox control, you can get
information about the status of the RadioButton control from the RadioButton.Checked property.
To use radio buttons
1. From the Toolbox, drag two RadioButton controls onto the form.
2. In the Properties window, set the Text property for RadioButton1 to Regular Sauce.
3. Set the Checked property for RadioButton1 to True.
Tip
When defining a group of choices, you should always set one choice to be the default.
4. In the Properties window, set the Text property for RadioButton2 to Spicy Sauce.
5. In the form, double-click the button to open the Button1_Click event handler in the Code Editor.
6. In the Button1_Click event handler, add the following code:
VB
If RadioButton1.Checked = True Then
MsgBox("You chose regular sauce")
Else
MsgBox("You chose spicy sauce")
End If
7. Press F5 to run your program. Choose one of the radio buttons and then click the Order Pizza button. A message box
noting your choice is displayed.
Try to select both radio buttons at the same time. Notice that the radio buttons are exclusive. After you click one, the
other is cleared automatically.
Next Steps
In this lesson, you learned how to use the CheckBox and RadioButton controls to give users choices in the user interface. At
this point, you can either go to the next lesson, Picture This: Displaying Images, or learn how to create multiple groups of radio
buttons with Closer Look: Using Multiple Groups of Radio Buttons. If you choose the second option, you should save your
UserChoices project for use in the next lesson.
See Also
Reference
CheckBox Control Overview (Windows Forms)
RadioButton Control Overview (Windows Forms)
Visual Basic Language Concepts
5. With the GroupBox control still selected, drag two RadioButton controls from the Toolbox, and drop them on top of
the GroupBox control.
6. In the Properties window, change the Text properties of RadioButton3 and RadioButton4 to Thin crust and Thick
crust, respectively.
7. In the form, double-click the Order Pizza button to open the Button1_Click event handler in the Code Editor.
8. In the Button1_Click event handler, add the following code.
VB
If RadioButton3.Checked = True Then
MsgBox("You chose a thin crust")
Else
MsgBox("You chose a thick crust")
End If
9. Press F5 to run your program. Choose one of the radio buttons, and then click the Order Pizza button. A message box
noting your choice is displayed. Notice that your choice of sauce is preserved.
Next Steps
In this lesson, you learned how to use a container control to group RadioButton controls. In the next lesson, you will learn
how to display pictures.
Next Lesson: Picture This: Displaying Images
See Also
Tasks
Getting User Choices: Using Check Boxes and Radio Buttons
How to: Group Controls with the Windows Forms GroupBox Control
Reference
Panel Control Overview (Windows Forms)
Visual Basic Language Concepts
VB
PictureBox1.Image = My.Resources.MyPictureName2
8. Press F5 to run your program. When the form appears, click the picture to make the second picture appear.
Displaying a Background Image on a Form
In addition to displaying a picture in a PictureBox control, you can also display a picture as the background for your form. The
BackgroundImage property of a form is used to display a picture that will appear behind any other controls on the form, much
the same as wallpaper on the Windows desktop.
Just as Windows allows you to choose whether wallpaper is centered, tiled, or stretched to fill the screen, the
BackgroundImageLayout property can be used to do the same for a form.
Tip
Many of the other controls, such as the Panel, GroupBox, and even the Button control also have a BackgroundImage proper
ty. Try them and see!
Try It!
To display a background image on a form
1. In Solution Explorer, select Form1.vb, and then on the View menu, choose Designer.
2. Select the form by clicking on it anywhere outside of the PictureBox.
3. In the Properties window, click the … button next to the BackgroundImage property to open the Select Resource
dialog box.
4. From the Entry list, choose one of the pictures that you added earlier, and then click OK.
Notice that the picture is displayed on the form behind the PictureBox and is tiled by default.
Note
If the picture in the PictureBox control is too large, you may not be able to see the background picture. In this case, sel
ect the PictureBox control, and drag it to the bottom of the form to get it out of the way.
9. Press F5 to run your program. When the form appears, click it to change the layout.
Next Steps
In this lesson, you learned how to use the PictureBox control to display images, and also how to use the BackgroundImage
property of a form. In the next lesson, you will learn how to create menus to present choices to users.
Next Lesson: Giving Users Choices: Creating Menus at Design Time
See Also
Tasks
Getting User Choices: Using Check Boxes and Radio Buttons
How to: Set the Background of a Windows Forms Panel
Reference
PictureBox Control Overview (Windows Forms)
Visual Basic Language Concepts
9. Press F5 to run your program. Using the mouse, click the File menu, and then choose Exit. Your application closes.
In this lesson, you learned how to use the MenuStrip control to design menus. At this point, you can continue to the next
lesson about timers, or you can explore more advanced ways to use menus in Closer Look: More About Menus, and then
proceed to the timers lesson.
Next Lesson: On Time: Using Timers to Perform Regular Actions
See Also
Tasks
Picture This: Displaying Images
Visual Basic Language Concepts
10. Press F5 to run your program. Click the Edit menu—the Copy menu item is disabled. Type something into the TextBox
control, and then click the Edit menu again—the Copy menu item is now enabled.
Creating Pop-up Menus
Many programs use pop-up menus, also known as context menus, to provide easy access to commonly used commands. You
access a context menu by right-clicking a form or control at run time. You can create your own context menus in Visual Basic
using a ContextMenuStrip control.
As with the MenuStrip control, when you drag a ContextMenuStrip control onto a form, the ContextMenuStrip control
appears as a box in the upper part of the form with the words "Type Here" inside, and an icon is added to the component tray.
Unlike MenuStrip, additional items can only be added below the first menu item, creating a vertical menu.
In addition, a ContextMenuStrip needs to be associated with the form or control where you want it to appear. You do this by
setting the ContextMenuStrip property of the form or control to the name of the ContextMenuStrip control. You can
associate a single ContextMenuStrip with as many controls as you like.
Try It!
To create a context menu
1. On the File menu, select New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type ContextMenus and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag a ContextMenuStrip control onto the form.
5. In the Properties window, select the ContextMenuStrip property of the form and choose ContextMenuStrip1 from
the drop-down list.
6. In the form, click the ContextMenuStrip control and type Option1, and then press ENTER.
7. In the box beneath the first box, type Option2, and then press ENTER.
8. Double-click the Option1 menu item to open the Code Editor.
9. In the Option1ToolStripMenuItem_Click event handler, type the following code.
VB
MsgBox("You chose Option 1")
10. In the Code Editor, select Option2ToolStripMenuItem in the left-hand drop down box, and then choose Click from
the right-hand drop down box.
A new event handler called Option2ToolStripMenuItem _Click appears in the code editor.
11. In the Option2ToolStripMenuItem _Click event handler, type the following code.
VB
MsgBox("You chose Option 2")
12. Press F5 to run your program. Right-click the form and click one of the items on the context menu—a message box
appears telling you which option you chose.
Next Steps
In this lesson, you learned how to enable and disable menus, and also how to create a context menu. In the next topic, you will
learn how to use a different type of control—a Timer—to perform actions.
Next Lesson: On Time: Using Timers to Perform Regular Actions
See Also
Tasks
Giving Users Choices: Creating Menus at Design Time
How to: Associate a ContextMenuStrip with a Control
Reference
MenuStrip Control Overview (Windows Forms)
Visual Basic Language Concepts
6. Press F5 to run the program. The program will halt and an exception dialog box is shown with the message
"InvalidCastException was unhandled".
The exception occurred because there is a typographical error in the code. The wrong variable was used—it should be
number, the Integer variable, not numbers, which is a String variable.
Notice that the program is still running; it is just in the debugging break mode. Using Edit and Continue, you can fix the
error without having to stop the program (and re-running to check it).
7. In the Code Editor, change numbers + 1 to number + 1.
If the variable Hours has a value of 0, the division operation fails and causes a run-time error. The program must run in order
for this error to be detected, and if Hours contains a valid value, it will not occur at all.
When a run-time error does occur, you can use the debugging tools in Visual Basic to determine the cause. You will learn how
to find and fix run-time errors in the lesson Ouch! My Program Didn't Like That! Finding and Eliminating Run-Time Errors.
Logic Errors
Logic errors are errors that prevent your program from doing what you intended it to do. Your code may compile and run
without error, but the result of an operation may produce a result that you did not expect.
For example, you might have a variable named FirstName that is initially set to a blank string. Later in your program, you
might concatenate FirstName with another variable named LastName to display a full name. If you forgot to assign a value to
FirstName, only the last name would be displayed, not the full name as you intended.
Logic errors are the hardest to find and fix, but Visual Basic has debugging tools that make this job easier, also. You will learn
how to find and fix logic errors in What? It Wasn't Supposed To Do That! Tracking Down Logic Errors.
Next Steps
In this lesson, you learned about the three categories of programming errors. In the next lesson you will learn about debugging
compiler errors.
Next Lesson:Oops, a Typo: Finding and Getting Rid of Compiler Errors
See Also
Tasks
Finding the Errors: Introduction to Visual Basic Debugging
Other Resources
What Went Wrong? Finding and Fixing Errors through Debugging
Visual Basic Language Concepts
6. Press ENTER. You will see a wavy blue line underneath End If.
If you hold the mouse over the line, you will see the message "'End If' must be preceded by a matching 'If'."
7. Change the code to look like the following.
VB
If 1 < 2 Then
End If
9. Press F5 to run the program. A dialog box appears with the message "There were build errors. Would you like to
continue and run the last successful build?"
10. Click No. The Error List window displays the error message "Name 'MgBox' is not declared."
11. Double-click the error message in the Error List, and change the code to MsgBox("Hello").
12. Press F5 again. This time the program should run, causing a message box to appear.
Next Steps
In this lesson, you learned how to find and fix compiler errors. In the next lesson, you will learn how to fix a different type of
error—run-time errors. Next Lesson: Ouch! My Program Didn't Like That! Finding and Eliminating Run-Time Errors
See Also
Tasks
Know Your Bugs: Three Kinds of Programming Errors
Finding the Errors: Introduction to Visual Basic Debugging
Visual Basic Language Concepts
VB
miles = 55
speed = miles / hours
MsgBox(CStr(speed) & " miles per hour")
6. Press F5 to run the program. An Exception Assistant dialog box is shown with the message "OverflowException was
unhandled".
A dotted line from the dialog box to your code file shows you which line of code caused the error.
Notice that the first troubleshooting tip in the Exception Assistant suggests that you should make sure you are not
dividing by zero.
7. Move your mouse over the variable miles, and hold it there for a few seconds. You should see a ToolTip that reads "miles
55".
8. Now move your mouse over the variable hours—the ToolTip should read "hours 0".
Because you cannot divide by zero and the value of hours is zero, you found the cause of the error—not updating the
value of hours.
9. Add the following line of code above the line miles = 55.
VB
hours = 2
10. Click the yellow arrow in the left-hand margin of the code and drag it up to the line hours = 2.
This allows the program to continue from that line, rather than the line that contains the error. This is required to execute
the new line of code you just added, in order for your error fix to be recognized.
11. Press F5 to continue the program. A dialog box appears, displaying "28 miles per hour".
Next Steps
In this lesson, you learned how to find and fix run-time errors. In the next lesson, you will learn about the third type of
programming error—logic errors. You can explore more advanced debugging techniques in
Closer Look: What If... Testing Code in the Immediate Window, and then proceed to the logic errors lesson.
Next Lesson:What? It Wasn't Supposed To Do That! Tracking Down Logic Errors
See Also
Tasks
Oops, a Typo: Finding and Getting Rid of Compiler Errors
Know Your Bugs: Three Kinds of Programming Errors
Finding the Errors: Introduction to Visual Basic Debugging
Visual Basic Language Concepts
You can execute code in the Immediate Window by typing it in as you would in the Code Editor, and then pressing ENTER. To
evaluate a variable or expression, type a question mark followed by the variable or expression you want to evaluate, and then
press ENTER—the result is then displayed on the following line.
Try It!
To test code in the Immediate window
1. On the File menu, choose New Project.
2. On the Templates pane, in the New Project dialog box, click Windows Application.
3. In the Name box, type Immediate, and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag two TextBox controls and a Button control onto the form.
5. Double-click the button to open the Code Editor.
6. In the Button_Click event handler, add the following code.
VB
Dim miles As Integer = 0
Dim hours As Integer = 0
Dim speed As Integer = 0
VB
miles = CInt(Textbox1.Text)
hours = CInt(Textbox2.Text)
speed = miles / hours
MsgBox(CStr(speed) & " miles per hour")
7. Press F5 to run the program. Enter 100 in the first text box, and then enter 0 in the second text box.
8. Click Button1. The program stops, and the Exception Assistant dialog box appears with the message
"OverflowException was unhandled".
9. In the Immediate window at the bottom of the IDE, type ?miles, and then press ENTER.
The value 100 should appear on the next line.
Tip
You can open the Immediate window at any time by choosing Windows, Immediate from the Debug menu.
Notice that the value of hours is now 4, the value you entered on the previous line. You could change the value of hours
in the Immediate window without changing the program's code.
12. Press F5 to continue. A message box is displayed with the result.
Tip
To prevent this run-time error from occurring, add an error handler to check for a valid number in the Try block, and th
en display a message to the user in the Catch block. For more information on error handlers, see
What To Do When Something Goes Wrong: Handling Errors.
Next Steps
In this lesson, you learned how to use the Immediate window to check values and run code. In the next lesson, you will learn
how to find and fix logic errors.
Next Lesson: What? It Wasn't Supposed To Do That! Tracking Down Logic Errors
See Also
Tasks
Ouch! My Program Didn't Like That! Finding and Eliminating Run-Time Errors
What To Do When Something Goes Wrong: Handling Errors
Visual Basic Language Concepts
VB
Function GetMPH(ByVal miles As Double, ByVal hours As Double) _
As String
GetMPH = CStr(miles / hours)
End Function
8. Press F5 to run the program. In the first text box, enter 10 (to represent 10 minutes) and in the second text box, enter 5 (to
represent 5 miles), and then click Button1.
A message box is displayed with the message "Average speed 0.03333334"; however, if you are traveling five miles in
ten minutes, the correct answer would be 30 mph.
Keep the project open—in the next procedure, you will learn how to find the logic error.
Finding Logic Errors
In the last example, something is obviously wrong with the program logic. According to the result, you are traveling less than
one mile per hour, not thirty miles per hour as you would expect—but where is the error?
In the next procedure, you will set a breakpoint and step through the code to find the error.
Try It!
To set a breakpoint and step through code
1. In the Code Editor, find the line hours = minutes / 60, and then click in the left-hand margin next to that line of code.
A red dot should appear in the margin, and the code should be highlighted in red, representing a breakpoint.
2. Press F5 to run the program again. In the first text box, enter 10, and in the second text box, enter 5. Then click Button1.
The program stops when it reaches the breakpoint. The line hours = minutes / 60 is highlighted in yellow.
Inspect the values of the variables by holding the mouse over them—the value of hours should be 0, and the value of
minutes should be 10.
3. Press F8 to execute the line hours = minutes / 60, and step to the next line.
Inspect the values of the variables in the line MsgBox("Average speed " & GetMPH(hours, miles))—the value of hours
should now be 0.166666672, and the value of miles should be 5.0.
4. Press F8 again to execute the current line.
Notice that the execution steps down to the line Function GetMPH.
Inspect the values of the variables on this line—you should notice that the value of miles is now 0.166666672, and the
value of hours is now 5.0, the opposite of what they were on the previous line. You've found the error.
Keep the project open—in the next procedure, you will learn how to fix the logic error.
Fixing Logic Errors
In the last procedure, the values for the variables miles and hours switched places. Can you spot the cause?
If you look at the line MsgBox("Average speed " & GetMPH(hours, miles)), you will see that the GetMPH function is being
passed two arguments, hours and miles, in that order. If you look at the function declaration Function GetMPH(ByVal miles
As Double, ByVal hours As Double)..., you will notice that the arguments are listed as miles first and hours second.
An error in logic occurred because the arguments were passed in the wrong order, resulting in an incorrect calculation. If the
arguments had been of different types, you would have seen a run-time error; because the arguments were the same type, no
run-time error occurred. It was a simple mistake, but the resulting bug was difficult to find.
In the next procedure, you will set a breakpoint and step through the code to find the error.
Try It!
To fix the logic error
1. In the Code Editor, change the line MsgBox("Average speed " & GetMPH(hours, miles)) to read as follows:
VB
MsgBox("Average speed " & GetMPH(miles, hours))
2. Clear the breakpoint by clicking the red dot in the left-hand margin.
3. Press F5 to run the program. In the first text box, enter 10, and in the second text box, enter 5. Then click Button1.
This time the message box should display the correct result, "Average speed 30".
It may appear that the program is fixed, but there is another even harder-to-find logic error. If you want to try and find it,
keep the project open—you will use it again in the lesson Extra Credit: Something is Still Wrong.
Next Steps
In this lesson, you learned how to find and fix a logic error. At this point, you can go on to the next lesson on using comments,
or you can try your hand at finding another logic error in Extra Credit: Something is Still Wrong.
Next Lesson: Making Notes in Your Programs: Using Comments
See Also
Tasks
Ouch! My Program Didn't Like That! Finding and Eliminating Run-Time Errors
Know Your Bugs: Three Kinds of Programming Errors
Finding the Errors: Introduction to Visual Basic Debugging
Visual Basic Language Concepts
2. Press F5 to run the program. In the first text box, enter 0 (to represent minutes), and in the second text box, enter 5 (to
represent miles), and then click Button1.
A message box is displayed with the message "Average speed Infinity".
Keep the project open—in the next procedure, you will learn how to find the logic error.
5 Divided by 0 = Infinity?
In the previous procedure, "Infinity" might not be what you expected, but it is mathematically correct—0 goes into 5 an infinite
number of times. That, however, is not the result you would want users of your program to see. Can you think of a way to
prevent this?
You might think of adding an error handler, a procedure you learned in the lesson
What To Do When Something Goes Wrong: Handling Errors. However, in this case that wouldn't work—the result "Infinity"
isn't an error; it's just not what you want.
Since it is probably not useful to show a speed of zero, one way to fix the problem is to test for a value of zero, then warn the
user that they must enter a higher number. While you are at it, you might as well prevent the user from entering negative
numbers as well, since negative numbers can also produce a false result.
In the next procedure, you will modify the code in the Button1_Click event handler to call the GetMPH function only if the
values are greater than zero.
Try It!
To fix the bug
1. In the Code Editor, change the code in the Button1_Click event handler as follows:
VB
Dim minutes As Integer = CInt(Textbox1.Text)
Dim miles As Double = CDbl(Textbox2.Text)
Dim hours As Double = 0
If minutes <= 0 Or miles <= 0 Then
MsgBox("Please enter a number greater than zero")
Else
hours = minutes / 60
MsgBox("Average speed " & GetMPH(miles, hours))
End If
2. Press F5 to run the program again. In the first text box, enter 0, and in the second text box, enter 5. Then click Button1.
You should see the message box instructing you to enter a number greater than 0. Try testing your program with other
combinations of numbers until you are satisfied that the bug is fixed.
Next Steps
In this lesson, you learned how to find and fix a logic error that caused unexpected behavior. In the next lesson, you will learn
how to use comments in your code.
Next Lesson: Making Notes in Your Programs: Using Comments
See Also
Tasks
What? It Wasn't Supposed To Do That! Tracking Down Logic Errors
What To Do When Something Goes Wrong: Handling Errors
Know Your Bugs: Three Kinds of Programming Errors
Finding the Errors: Introduction to Visual Basic Debugging
Reference
/ Operator (Visual Basic)
Visual Basic Language Concepts
You can add comments to the ends of lines, as well, also by using the ' character. This is frequently done to provide comments
about individual lines of code, as seen in the following example.
VB
MsgBox("Hello World!") ' This line causes a message box to appear.
As with single-line comments, anything following the ' character on that line is ignored by the program.
Using Comments for Debugging
Another common use for comments is to temporarily prevent a line of code from executing while you debug your program.
For example, suppose you had a line of code that displayed a message box.
VB
MsgBox("Hello World!")
If you wanted to run the program without displaying it, but did not want to delete it permanently, you could use the comment
character (') to temporarily hide it from your program, as shown below.
VB
' MsgBox("Hello World!")
Because everything after the ' character is ignored, the program will run without executing this line. You can later remove the '
character, and the message box will be displayed.
Try It!
To insert comments
1. On the File menu, choose New Project.
2. On the Templates pane in the New Project dialog box, click Windows Application.
3. In the Name box, type Comments and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor.
5. In the Form1_Load event handler, type the following code.
VB
' This code will cause two message boxes to appear
MsgBox("This is Message Box 1") ' Display Message Box 1
MsgBox("This is Message Box 2") ' Display Message Box 2
Each table is organized into a grid of columns and rows. The columns represent categories for the data in a record, and the
rows represent individual records. For example, in the above illustration, the Orders table contains a separate row or record
representing each order, and columns representing the product ordered, along with the quantity and the price.
Getting Started with Data
To access the data in a database from your program, you first must have a database to access. Using Visual Basic, it is easy to
create your own database, or to use a database that someone else created.
With Visual Basic Express Edition, you can access two different types of databases: Microsoft SQL Server databases or
Microsoft Access databases. For the purpose of these lessons, you will use a SQL Server database.
Once you have a database, you connect it to your program using an object called a DataSet, and then you connect the fields or
controls on a form to the data in the database using a technique called data binding.
When a field in your program, for example a TextBox control, is bound to a column in a database table, you can display the
data from that column in the text box, modify the data in the text box and save it in the database, or enter data for a new record
and add it to the database.
Although this may sound complicated, it really is not difficult. The database tools in Visual Basic make working with data a
snap, as you will see in the next few lessons.
Next Steps
In this lesson, you learned what a database is and how it relates to your program. In the next lesson, you will learn how to
create a database that can be used by your programs.
Note
To create and access a SQL Server database with Visual Basic Express Edition, you must also install SQL Server Express Editio
n. It is installed by default when you install Visual Basic Express Edition; however, if you chose not to install it, you will need to
do so before continuing on to the next lesson.
b. FirstName: Andrea, LastName: Dunker, StreetAddress: 722 Moss Bay Blvd, City: Kirkland, Phone: 2065550102.
7. On the File menu, choose Save All to save the project and the database.
As you were entering the data, you may have noticed that a small pencil icon appeared next to the data; when you used the
TAB key to move to the next row, the icons disappeared. The pencil icon means that the data hasn't been saved to the database.
When you move away from the row where you are entering data, the data for the entire row is saved to the database
automatically.
Next Steps
In this lesson, you created a database, added a database table, and then added records to the table in the IDE. In the next lesson,
you will learn how to use a database in your program.
Next Lesson: Getting the Information You Need: Connecting to an Existing Database.
See Also
Tasks
Storing and Accessing Data
Other Resources
Managing Your Records: Using Data in Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts
Try It!
To connect to an existing database
1. On the File menu, click New Project.
2. On the Templates pane in the New Project dialog box, click Windows Application.
3. In the Name box, type Addresses and then click OK.
A new Windows Forms project opens.
4. On the Data menu, click Show Data Sources.
5. In the Data Sources window, click Add New Data Source.
The Data Source Configuration Wizard opens.
6. Select Database and click Next.
7. Click the New Connection button.
The Add Connection dialog box opens.
8. In the Add Connection dialog box, if the Data source is not Microsoft SQL Server Database File (SQL Client), click
the Change button and select Microsoft SQL Server Database File from the Change Data Source dialog box. Click
OK.
9. Click the Browse button and navigate to the location where you saved the FirstDatabase.mdf database, and then click
Open.
10. Click OK to close the dialog box, and then in the Data Source Configuration Wizard, click Next. If prompted to copy
the data file to your project, click Yes.
11. On the next page of the wizard, the Yes, save the connection as check box should be selected. Click Next to continue.
12. On the Choose Your Database Objects page, expand the Tables node, and then select the check box for the Addresses
table.
13. Click Finish to finish.
A local database file has been added to your project. Notice that a FirstDatabaseDataSet object has been added to the
Data Sources window.
14. In Solution Explorer, select the FirstDatabase.mdf node.
15. In the Properties window, select the Copy to Output Directory property and change the value to Copy if newer.
16. On the File menu, choose Save All to save your project.
Next Steps
In this lesson, you learned how to add a local database to your project. In the next lesson, you will learn how to create a user
interface to display the records in your database.
Next Lesson: Showing Information to the User: Displaying Data in Your User Interface
See Also
Tasks
Creating Your First Database
Other Resources
Managing Your Records: Using Data in Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts
5. Select the AddressesDataGridView control, and in the Properties window, set the Dock property to Fill (click the
center button).
This will expand the grid to fill the form.
6. Press F5 to run your program.
The data from the Addresses table is displayed in the DataGridView control on the form. You can use the controls in the
BindingNavigator to navigate between rows, and even add or delete records. You can also make changes to the
records by modifying the data displayed in the grid, but these changes will not be saved unless you click the Save Data
icon. You will learn how to automatically save changes to your data in the next topic.
Next Steps
In this lesson, you learned how to use the Visual Basic visual tools to create a basic data-oriented user interface. In the next
lesson, you will learn how to create a data entry form and save changes to your database.
Next Lesson: Adding or Modifying Your Records: Updating Data
See Also
Tasks
Getting the Information You Need: Connecting to an Existing Database
Other Resources
Managing Your Records: Using Data in Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts
Me.AddressesBindingSource.EndEdit()
Me.AddressesTableAdapter.Update(Me.FirstDatabaseDataSet.Addresses)
This code causes the AddressesTableAdapter to copy any changes in the dataset back to the local database.
10. Press F5 to run your program.
Make changes to some of the data, or add a new record, and then close the form.
11. Press F5 again. Your changes should be saved.
In this set of lessons, you learned how to create a database and a program to access the database. In the next set of lessons,
you will learn about classes, the blueprints for objects that you can reuse in your programs.
Next Lesson: Programming With Objects: Using Classes
See Also
Tasks
Getting the Information You Need: Connecting to an Existing Database
Other Resources
Managing Your Records: Using Data in Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts
What is a Class?
In this lesson, you will learn how to use classes to represent objects in your programs.
As you learned in an earlier lesson, Visual Basic programs are built with objects such as forms or controls. Objects can also be
used to represent real-world things, such as a person, a computer, or even something more abstract, such as a bank account.
A class is simply a representation of a type of object; think of it as a blueprint that describes the object. Just as a single blueprint
can be used to build multiple buildings, a class can be used to create multiple copies of an object.
Although you may not have realized it, you have already used classes. For example, the TextBox control is defined by a
TextBox class, which defines its appearance and its capabilities. Each time you drag a TextBox control onto a form, you are
actually creating a new instance of the TextBox class.
Each TextBox control is an exact yet distinct copy of the class that defines it, the TextBox class. Because each object is a
separate "instance" of a class, the act of creating a class is called instantiation.
So far you have added TextBox controls to your form by dragging them from the Toolbox, but you can also instantiate a
TextBox object in your code by declaring it with the New keyword.
VB
Dim Textbox1 As New TextBox
You will learn more about creating and using classes in the next few lessons.
What's in a Class?
In an earlier lesson, Closer Look: Understanding Properties, Methods, and Events, you learned that all objects have properties
that describe their attributes, methods that define their actions, and events that define their responses. Likewise, the class that
defines an object has its own properties, methods, and events (sometimes called members) that are passed on to all instances
of that class.
For example, a class that represents a bank account might have properties such as AccountNumber or AccountBalance, methods
such as CalculateInterest, and events such as BalanceChanged. Once you instantiate a bank-account object, you can access
its properties, methods and events just as you would with an object such as TextBox.
Some members of a class are private—they can only be accessed by code within the class. For example, a bank-account class
might have a method to calculate a balance. You would allow a program to read that balance, but you would not want the
program to be able to change the balance directly.
You can hide members in a class by declaring them as Private, or you can expose them by declaring them as Public. You can
also allow access to a property but prevent the program from changing its value by declaring it as ReadOnly. The following
code shows what a BankAccount class might look like.
VB
Class BankAccount
Private AccountNumber As String
Private AccountBalance As Decimal
Public Sub UpdateBalance()
' add code to recalculate balance.
End Sub
ReadOnly Property Balance() As Decimal
Get
Return AccountBalance
End Get
End Property
End Class
Next Steps
In this topic, you learned the basics of classes, as well as some new terminology. In the next lesson, you will learn how to create
a class.
Next Lesson: Modeling a Real-World Object: Creating Your First Class.
See Also
Concepts
Closer Look: Understanding Properties, Methods, and Events
Classes: Blueprints for Objects
Other Resources
Programming With Objects: Using Classes
Visual Basic Language Concepts
End Sub
End Class
That's right—the form is actually a class, marked by Class and End Class statements, and any code that you enter between
those two statements is part of the class. Although by default a form module contains only a single class, you could create
additional modules by adding code below the End Class statement as follows:
The drawback to creating classes this way is that they are available only within the project in which you created them. If you
want to share a class with other projects, you'll want to put it in a class module.
Class Modules
A class module is a separate code file that contains one or more classes. Because it is a separate file, it can be reused in other
projects. Class modules can be created in two ways—as a module added to a Windows Application project, or as a stand-
alone Class Library project.
You can add a new class module to an existing project by selecting Class in the Add New Item dialog box, available from the
Project menu. For the purpose of this set of lessons, you will be creating a stand-alone Class Library project.
Try It!
To create a Class Library project
1. On the File menu, choose New Project.
2. On the Templates pane, in the New Project dialog box, click Class Library.
3. In the Name box, type Persons and then click OK.
A new Class Library project opens, and the Code Editor displays the class module Class1.vb.
4. In Solution Explorer, right-click Class1.vb and select Rename, and then change the name to Persons.vb.
Notice that the name in the Code Editor also changed to Persons.vb.
5. On the File menu, choose Save All.
6. In the Save Project dialog box, click Save.
Tip
Rather than saving the project in the default location, you may want to create a directory where you can store all of you
r classes for reuse. You can enter that folder in the Location field of the Save Project dialog box before you save.
For now, keep the project open—you will add to it in the next lesson.
Next Steps
In this lesson, you learned how to create a class module. An empty class is of little use though—in the next lesson, you will
learn how to add properties to your class.
Next Lesson: Adding Properties to Your Class
See Also
Tasks
How to: Add New Project Items
Concepts
What is a Class?
Other Resources
Programming With Objects: Using Classes
Visual Basic Language Concepts
Most properties, however, are more complex than that—in most cases you will want to use a property procedure to add a
property to a class. Property procedures have three parts: a declaration of a private variable to store the property value; a Get
procedure that exposes the value; and a Set procedure that, as it sounds, sets the value.
For example, a property procedure for a Name property for the Persons class would look like the following.
VB
Private nameValue As String
Public Property Name() As String
Get
Name = nameValue
End Get
Set(ByVal value As String)
nameValue = value
End Set
End Property
The first line of code declares a private String variable, nameValue, which will store the value of the property. The property
procedure itself begins with Public Property and ends with End Property.
The Get procedure contains the code that will be executed when you want to read its value—for example, if you read the
Persons.Name property, the code would return the value stored in the nameValue variable.
The Set procedure contains code used to assign a new value to the nameValue variable using a value passed to it as a value
argument. For example, if you wrote the code Persons.Name = "John", the String value John would be passed as the value
argument; the code in the Set procedure would then assign it to the NameValue variable for storage.
You might ask why you would go to all that trouble rather than use a field to represent the Name property. In the real world,
there are certain rules for names—for example, names do not usually contain numbers. You could add code to the Set
procedure to check the value argument and return an error if it contains numbers.
In the following procedure, you will add a field and three properties to the Persons class.
Try It!
To add properties to your class
1. Open the Persons project that you created in the previous lesson. If you did not save it, you will first need to go back to
the previous lesson, Modeling a Real-World Object: Creating Your First Class, and complete the procedures in that lesson.
2. In Solution Explorer, select Persons.vb, and then on the View menu, choose Code.
3. Add the following declaration code below the Public Class Persons line.
VB
Private firstNameValue As String
Private middleNameValue As String
Private lastNameValue As String
Public Alive As Boolean
Likewise, the WriteOnly keyword allows a property value to be set but not read—for example, you would not allow a
password property to be read by other programs. You might use that value to do things within your class, but you would want
to keep it private.
To create a write-only property, you would create a property with a Set procedure but no Get procedure, as follows.
VB
Private passwordValue As String
WriteOnly Property Password() As String
Set(ByVal value As String)
passwordValue = value
End Set
End Property
ReadOnly and WriteOnly property procedures are also useful when you want to take one property value and convert it to a
different value. For example, consider a person's age. Unlike a name, age changes over time—if you assigned your age to a
class and read it back a year later, it would be wrong.
In the Persons class, you could prevent this by adding two properties—a WriteOnly BirthYear property that represents the
year of your birth, which never changes, and a ReadOnly Age property that returns a value by calculating the difference
between the current year and your birth year.
Try It!
To add ReadOnly and WriteOnly properties to your class
1. Add the following declaration code below the other declarations at the top of the class module.
VB
Private birthYearValue As Integer
While most class methods are public, you might also want to add methods that can only be used by the class itself. For
example, the Persons class might have its own function for calculating a person's age. By declaring the function as Private, it
can not be seen or called from outside the class.
The code for a private function might look like the following:
VB
Private Function CalcAge(ByVal year As Integer) As Integer
CalcAge = My.Computer.Clock.LocalTime.Year - year
End Function
You could later change the code that calculates the value of CalcAge, and the method would still work fine without changing
any code that uses the method. Hiding the code that performs the method is known as encapsulation.
In the Persons class, you will create a public method that returns a full name, and a private function to calculate the age.
Try It!
To add a method to your class
1. Open the Persons project that you created in the previous lesson. If you did not save it, you will first need to go back to
the previous lesson, Adding Properties to Your Class, and complete the procedures.
2. In Solution Explorer, select Persons.vb, and then on the View menu choose Code.
3. Add the following code below the property procedures.
VB
Public Function FullName() As String
If middleNameValue <> "" Then
FullName = firstNameValue & " " & middleNameValue & " " _
& lastNameValue
Else
FullName = firstNameValue & " " & lastNameValue
End If
End Function
VB
Private Function CalcAge(ByVal year As Integer) As Integer
CalcAge = My.Computer.Clock.LocalTime.Year - year
End Function
4. Modify the code in the Age property procedure to use the private function.
VB
ReadOnly Property Age() As String
Get
' Age = My.Computer.Clock.LocalTime.Year - birthDateValue
Age = CalcAge(birthYearValue)
End Get
End Property
If you were to call this method from your code and pass it a string, the first overload would be executed and a message box
would display the string; if you passed it a number, the second overload would be executed, and the number would be
converted to a string and then displayed in the message box.
You can create as many overloads as you need, and each overload can contain a different number of arguments.
In the Persons class, you will add a method with two overloads to return a person's middle initial: one with just the initial, the
other with the initial followed by a period.
Try It!
To create an overloaded method
1. Open the Persons project that you created in the previous lesson. If you did not save it, go back to the previous lesson,
Adding Methods to Your Class, and complete the procedures.
2. In Solution Explorer, select Persons.vb, and then on the View menu, choose Code.
3. Add the following code below the existing methods.
VB
Public Function MiddleInitial() As String
MiddleInitial = Left$(middleNameValue, 1)
End Function
To use and test the Persons class, you must first create a test project and add a reference to the class module.
Try It!
To create a test project for your class
1. Open the Persons project that you created in the previous lesson. If you did not save it, you will first need to go back to
the previous lesson, Adding Methods to Your Class, and complete the procedures.
2. On the File menu, point to Add, and choose New Project.
3. On the Templates pane in the New Project dialog box, click Windows Application.
4. In the Name box, type PersonsTest and then click OK.
A new Windows Forms project is added to Solution Explorer, and a new form is displayed.
5. In Solution Explorer, select the PersonsTest project, and then on the Project menu, choose Set as StartUp Project.
6. In the Solution Explorer, select the PersonsTest project, and then on the Project menu, choose Add Reference.
The Add Reference dialog box opens.
7. Click the Projects tab, and then select Persons and click OK.
8. Double-click the form to open the Code Editor, and then enter the following declaration just below the line Public Class
Form1.
VB
Dim person1 As New Persons.Persons
This declares a new instance of the Persons class. You might wonder why you needed to type Persons twice—the first
instance is the Persons.vb class module; the second instance is the Persons class within that module.
9. On the File menu, choose Save All.
Testing Your Class
The next step is to add a user interface and code that uses the Persons class. You will add text boxes into which the user will
enter values for each of the properties (except the read-only Age property), a check box for the Alive field, and buttons to test
each of the public methods.
Try It!
To test your class
1. In Solution Explorer, select Form1, and then on the View menu, choose Designer.
2. From the Toolbox, drag four TextBox controls, a CheckBox control, and two Button controls onto the form.
3. Select the first Button control, and then in the Properties window set its Text property to Update.
4. Select the second Button control, and then in the Properties window set its Text property to Full Name.
5. Double-click the first button (Update) to open the Code Editor, and then in the Button1_Click event handler, add the
following code.
VB
With person1
.FirstName = Textbox1.Text
.MiddleName = Textbox2.Text
.LastName = Textbox3.Text
.BirthYear = Textbox4.Text
.Alive = CheckBox1.Checked
End With
Notice that as you type, a list containing all of the members of the Persons class is displayed. Since it was added as a
reference, IntelliSense displays information about your class just as it would for any other class.
6. In the Button2_Click event handler, add the following code.
VB
' Test the FullName method.
MsgBox(person1.FullName)
Notice that as you type, a list containing all of the members of the Persons class is displayed. Since it was added as a
reference, IntelliSense displays information about your class, just as it would for any other class.
6. In the Button4_Click event handler, add the following code.
VB
MsgBox(person1.FirstName & " " & person1.MiddleInitial & _
" " & person1.LastName)
The new class, DerivedClass, can then be instantiated, its properties and methods accessed just like BaseClass, and you can
add new properties and methods that are specific to the new class. For an example, look at the Persons class that you created
in the previous lessons.
Suppose you wanted a class that represented baseball players—baseball players have all of the attributes defined in the
Persons class, but they also have unique attributes such as number and position. Rather than adding those properties to the
Persons class, you will create a new derived class that inherits from Persons, and add the new properties to that class.
Try It!
To create a derived class
1. Open the Persons project that you created in the previous lesson. If you did not save it, go back to, Testing Your Class,
and complete the procedures.
2. In Solution Explorer, select the Persons project node.
3. On the Project menu, choose Add Class.
4. In the Add New Item dialog box, type Players in the Name box, and then click Add.
A new class module is added to the project.
5. In the Code Editor, add the following just below the Public Class Players line.
VB
Inherits Persons
VB
Dim player1 As New Persons.Players
Dim player2 As New Persons.Players
3. In Solution Explorer, select Form1 in the PlayerTest project, and then on the View menu, choose Designer.
4. From the Toolbox, drag two Button controls onto the form.
5. Select the first Button control, and then in the Properties window, set its Text property to At Bat.
6. Select the second Button control, and then in the Properties window, set its Text property to On Deck.
7. Double-click the first button (At Bat) to open the Code Editor, and then enter the following code in the Button1_Click
event handler.
VB
MsgBox(player1.Position & " " & player1.FullName & ", #" & _
CStr(player1.Number) & " is now at bat.")
Notice that you are using the FullName method, which was inherited from the base class Persons.
8. In the Button2_Click event handler, add the following code.
VB
MsgBox(player2.Position & " " & player2.FullName & ", #" & _
CStr(player2.Number) & " is on deck.")
9. Press F5 to run the program. Click each button to see the results.
10. On the File menu, choose Save All.
Next Steps
In this lesson, you learned how to inherit from an existing class and how to extend the derived class. You can learn more about
inheritance in Closer Look: Overriding Members, or you can go on to the next lesson and learn about collections.
Next Lesson: Keeping Track Of Things: Using Collections to Manage Multiple Objects
See Also
Concepts
Inheritance Basics
Visual Basic Language Concepts
When inheriting from a base class, properties and methods that are marked as Overridable can be used as is, or they can be
modified to suit your needs by declaring them with the Overrides keyword.
Public Overrides Property EngineType As String
Public Overrides Sub StartEngine(ByVal EngineType As String)
In the Players class that you created in the previous lesson, you might want to override the FullName method to include the
player's number and to eliminate the code that returns a middle name.
Try It!
To override the FullName method
1. Open the Persons project that you created in the previous lesson. If you did not save it, go back to the previous lesson,
Building Your Class on an Existing Class: Using Inheritance, and complete the procedures.
2. In Solution Explorer, select the Persons.vb node, and then on the View menu, choose Code.
3. In the Code Editor, modify the declaration for the FullName method as follows.
VB
Public Overridable Function FullName() As String
4. In Solution Explorer, select the Players.vb node, and then on the View menu, choose Code.
5. In the Code Editor, add the following code to the class.
VB
Public Overrides Function FullName() As String
FullName = FirstName & " " & LastName & ", #" & numberValue
End Function
6. In Solution Explorer, select the Form1.vb node in the PlayerTest project, and then on the View menu, choose Code.
7. In the Code Editor, modify the Button1_Click event code as follows.
VB
MsgBox(player1.Position & " " & player1.FullName & _
" is now at bat.")
8. Modify the Button2_Click event code as follows.
VB
MsgBox(player2.Position & " " & player2.FullName & _
" is on deck.")
9. Press F5 to run the program, and click each button to display the results.
Notice that the results are the same as before, even though you are now using the overridden FullName method.
10. On the File menu, choose Save All.
Next Steps
In this lesson, you learned how to override a method. In the next lesson, you will learn about using collections to manage
groups of similar objects.
Next Lesson: Keeping Track Of Things: Using Collections to Manage Multiple Objects
See Also
Tasks
Building Your Class on an Existing Class: Using Inheritance
Reference
Overridable
Overrides
Visual Basic Language Concepts
Once you create the Collection object, you can use the Add method to add items to it, and the Remove method to delete the
items. When adding items, first specify the item to add, and then specify the String value to be used as a key.
VB
baseballTeam.Add(playerObject, "Player's Name")
When removing an item, use the key to specify the item to remove.
VB
baseballTeam.Remove("Player's Name")
In the following procedure, you will add two new Players objects, and then create a team collection and add the Players
objects to it, using the Position property as a key.
Try It!
To create a collection of objects
1. Open the Persons project that you created in the previous lesson. If you did not save it, go back to the previous lesson,
Building Your Class on an Existing Class: Using Inheritance, and complete the procedures.
2. In Solution Explorer, in the PlayerTest project, select the Form1.vb node, and then on the View menu, choose Code.
3. In the Code Editor, add the following to the declarations section (below the declaration for player2).
VB
Dim player3 As New Persons.Players
Dim player4 As New Persons.Players
Dim team As New Collection
With player4
.FirstName = "Karl"
.LastName = "Jablonski"
.Number = 22
.Position = "Pitcher"
End With
team.Add(player1, player1.Position)
team.Add(player2, player2.Position)
team.Add(player3, player3.Position)
team.Add(player4, player4.Position)
5. In Solution Explorer, in the PlayerTest project, select the Form1.vb node. Then on the View menu, choose Designer.
6. From the Toolbox, drag a ComboBox control onto the form.
7. In the Properties window, select the Items property and click the … button.
8. In the String Collection Editor, enter the following, and then click OK.
Catcher
First Base
Pitcher
Shortstop
9. Double-click the ComboBox control to open the Code Editor, and then enter the following code in the
ComboBox1_SelectedIndexChanged event handler.
10. Press F5 to run the program. Select a position from the drop-down list—the player for that position is displayed in a
message box.
Next Steps
In this lesson, you learned how to use a Collection object to manage a group of objects. At this point, you can learn more
about collections in Closer Look: Using a For Each...Next Loop in a Collection, or you can go on to the next group of lessons and
learn about creating your own controls.
Next Lesson: Visible Objects: Creating Your First User Control
See Also
Tasks
Closer Look: Using a For Each...Next Loop in a Collection
Closer Look: Overriding Members
Building Your Class on an Existing Class: Using Inheritance
Concepts
Visual Basic Collection Class
Other Resources
Visible Objects: Creating Your First User Control
Visual Basic Language Concepts
In this case, no matter how many Players you have, the ComboBox1.Items.Add method is executed once for each Players
object in the team collection, and the Position value is added to the list.
Try It!
To loop through a collection
1. Open the Persons project from the previous lesson. If you did not finish it, go back to the previous lesson,
Keeping Track Of Things: Using Collections to Manage Multiple Objects, and complete the procedures.
2. In Solution Explorer, select the Form1.vb node in the PlayerTest project, and then from the View menu, choose
Designer.
3. Select the ComboBox control. Then, in the Properties window, select the Items property and click the … button.
4. In the String Collection Editor, delete the four existing entries, and then click OK.
5. Double-click the form to open the Code Editor.
6. In the Code Editor, add the following to the declarations section (below the declaration for team).
VB
Dim player As Persons.Players
For Each player In team
ComboBox1.Items.Add(player.Position)
Next
7. Press F5 to run the program. Select a position from the drop-down list. The player for that position is displayed in a
message box.
Next Steps
In this lesson, you used a For Each...Next loop in a collection. In the following lessons, you will create another type of object—
a user control.
Next Lesson: Visible Objects: Creating Your First User Control
See Also
Tasks
Keeping Track Of Things: Using Collections to Manage Multiple Objects
Reference
For Each...Next Statement (Visual Basic)
Other Resources
Programming With Objects: Using Classes
Visual Basic Language Concepts
Try It!
To add code to a user control
1. Open the NamesUserControl project that you created in the previous lesson. If you did not save it, you will first need to go
back to the previous lesson, Understanding the User Control Designer, and complete the procedures in that lesson.
2. In the Solution Explorer, select NamesControl.vb, and then on the View menu choose Code.
3. In the Code Editor, add the following code for the FirstName_TextChanged event handler.
4. Press F5 to run the program. The UserControl TestContainer opens and displays your user control.
5. Enter your first, middle and last names in the three text boxes—as you type, your name is displayed in the FullName label.
If you look at the code that you entered above, you will notice that the Handles clause in the declaration handles the
TextChanged event for all three TextBox controls. No matter which text box you type in first, the FullName label is always
updated as you type.
Exposing Properties in a User Control
Properties of standard controls allow you to set and retrieve values for a control at design time and at run time. You will also
want to make certain properties of your user control available so that you can set them in the Properties window at design
time and reference them in your code.
Exposing properties in a user control is very similar to exposing properties in a class, the main difference being that you can
also expose the properties of the controls contained in your user control. As with classes, you declare a Property and add code
to the Get and Set procedures. If you are exposing a property of a contained control, you do not need to declare a private
variable to store the value—the control's property stores it for you.
As it stands now, there is no way to retrieve the text that is entered into the FirstName, MiddleName, and LastName controls or
the value of the FullName label. You need to expose their values as properties to make the control useful. Since you do not
want the value of the FullName label to be changed outside of your own code, you will want to expose it as a read-only
property.
Try It!
To add properties
1. In the Code Editor, add the following code to expose the FirstName, MiddleName, and LastName values as properties.
2. Add the following code to expose the value of the FullName label as a read-only property.
2. In the Code Editor, select (NamesControl Events) from the left drop-down box, and then select the Validating event
from the right drop-down box.
3. Add the following code to the NamesControl_Validating event handler.
6. Press F5 to run the program. You should see three lines on the form.
Next Steps
In this lesson, you learned the basics of graphics, as well as how to draw lines. In the next lesson, you will learn to draw shapes
such as rectangles and circles.
Next Lesson: Drawing Shapes on Your Form
See Also
Tasks
Picture This: Displaying Images
Other Resources
Drawing Pictures: Using Graphics
Visual Basic Guided Tour
Visual Basic Language Concepts
6. Press F5 to run the program. You should see four shapes on the form.
Keep the project open—you will add to it in the next procedure.
Drawing Filled Shapes
So far, the shapes that you have drawn are just outlines. To draw shapes with solid colors, you need to use one of the fill
methods such as FillRectangle or FillEllipse. The fill methods use a Brush object, another type of graphics object that can
paint.
When filling a shape with a different color, you will need to define coordinates that are smaller than the shape; otherwise the
border will be covered. For example, to fill a square with the coordinates 0, 0, 150, 150 you would specify a fill with the
coordinates 1, 1, 148, 148, accounting for the one pixel thickness of the line.
To draw filled shapes
1. In the Form1_Paint event handler, add the following code below the code that you entered earlier.
VB
' Fill the circle with the same color as its border.
e.Graphics.FillEllipse(Brushes.Red, 0, 0, 150, 150)
' Fill the square with a different color.
e.Graphics.FillRectangle(Brushes.Aquamarine, 31, 31, 148, 148)
4. Press F5 to run the program. You should see the text displayed on the form.
Keep the project open—you will be adding to it in the next procedure.
Drawing Rotated Text
In order to draw text at an angle, you need to use another type of graphics method called a transform. There are several types
of transforms available for different graphics effects; in this case, you will use the RotateTransform method.
The RotateTransform method takes a single argument, the angle at which to rotate the text. The transformation is performed
on the line of code following the RotateTransform method; you could also use it to rotate shapes or lines drawn using the
other draw methods.
Try It!
To draw rotated text
1. In the Form1_Paint event handler, add the following code below the code that you entered earlier.
VB
' Rotate the text 45 degrees.
e.Graphics.RotateTransform(45)
e.Graphics.DrawString("And exciting too!", aFont, Brushes.Red, _
100, 0)
2. Press F5 to run the program. You should see the rotated text displayed on the form.
Next Steps
In this lesson, you learned how to use the DrawString method to display text. In the next lesson, you will learn to display an
image using graphics methods.
Next Lesson: Drawing an Image on Your Form
See Also
Tasks
Drawing Shapes on Your Form
Other Resources
Drawing Pictures: Using Graphics
Visual Basic Guided Tour
Visual Basic Language Concepts
Note
Replace picture with the name of the resource that you added in an earlier step.
10. Press F5 to run the program. You should see the rotated image on the form.
Next Steps
In this lesson, you learned how to display a rotated image on a form. That completes the lessons on graphics. In the next set of
lessons, you will learn how to share the programs you create.
Next Lesson: Distributing Your Program
See Also
Tasks
Drawing Text on Your Form
Other Resources
Drawing Pictures: Using Graphics
Visual Basic Guided Tour
Visual Basic Language Concepts
Including Prerequisites
To include prerequisites with your program, change the Publishing property in the Project Designer. Notice that if you
include one prerequisite, you must include all prerequisites—you cannot include one prerequisite and have another
downloaded from the Internet.
Try It!
To include prerequisites
1. Open your project from the previous lesson, Distributing Your Program on CD: Publishing with ClickOnce.
2. In Solution Explorer, select the project node, and then on the Project menu, choose Properties.
The Project Designer opens.
3. In the Project Designer, click the Publish tab.
4. Click the Prerequisites button to open the Prerequisites dialog box.
5. In the Prerequisites dialog box, select the Download prerequisites from the same location as my application
check box and then click OK
6. On the Build menu, choose Publish ProjectName, where ProjectName is the name of your project.
The Publish Wizard is launched.
7. Click Finish to publish the program.
Note
You may be prompted to download the .NET Framework redistributable files if you have not already done so.
8. In Windows Explorer, browse to the location the program was published, and verify that both the Setup.exe and
Dotnetfx.exe files are there.
Next Steps
In this lesson, you learned how to publish prerequisites along with your program. At this point, you have several choices for
where to go next.
If you have access to a Web server and want to learn how to publish your program to the Internet, see
Closer Look: Distributing Your Program on the Internet.
If you were unable to burn a CD-ROM or DVD-ROM, see
Sending Your Program through E-mail: Creating a Compressed (zipped) File.
Otherwise, you are done with the lessons in the guided tour. You can go on to the next topic for some suggestions on other
resources for learning more about Visual Basic.
Next Lesson: Moving Forward: Where Do I Go From Here?
See Also
Tasks
Distributing Your Program on CD: Publishing with ClickOnce
Concepts
Sharing Your Program: Introduction to Deployment
Visual Basic Language Concepts
For most simple programs, you can package the executable file (.exe) and the configuration file (.config) in a compressed file
and distribute it. For example, if you have a simple program named Calculator, you will need the Calculator.exe file and the
Calculator.exe.config file, which you can find in the your Visual Studio Projects/Calculator/Calculator/bin directory, where
your Visual Studio Projects is the directory that your Visual Studio projects are kept in, usually My Documents/Visual
Studio/Projects.
Note
All programs created with Visual Basic require the Microsoft .NET Framework version 2.0. If you distribute your program thro
ugh e-mail, make sure that the .NET Framework is already installed on the computers of any recipients.
Tip
The .NET Framework is distributed with many other programs; it can also be downloaded from the Microsoft Web site. You c
an check if the .NET Framework is installed by going to the Control Panel, opening Add or Remove Programs, and looking
for Microsoft .NET Framework version 2.0.
For more complicated programs, such as programs that include a local database, you might need to include additional files. In
this case, it is best to publish your program using ClickOnce publishing instead of sending it through e-mail.
Try It!
The following procedure shows you how to compress a file using the default Compressed (zipped) Folders feature in Windows.
If you installed a different program to work with .zip files, the steps needed to compress a file may be different.
To send a simple program through e-mail
1. Select a project that you have completed and run, and then in Windows Explorer, navigate to the project folder.
2. In the project folder, open the folder that has the name of the project, open the folder named Bin, and then select the
Debug folder.
3. Select the ProjectName.exe file (where ProjectName is the name of your project), right-click the file, and choose Send To,
Compressed (zipped) Folder.
A new file named ProjectName.zip is created and added to the directory. You can send this file as an attachment to an e-
mail message.
Next Steps
In this lesson, you learned how to package your program for sending through e-mail. In the next lesson, you will learn how to
extract and run a program that you have received.
Next Lesson: Getting a Program through E-mail: Extracting a Compressed (zipped) Program
See Also
Tasks
Distributing Your Program on CD: Publishing with ClickOnce
Concepts
Sharing Your Program: Introduction to Deployment
Other Resources
Distributing Your Program
Visual Basic Language Concepts
Try It!
To extract a compressed (zipped) program
1. Navigate to the .zip file you created in the previous lesson. If you have not completed this lesson, take a moment to
complete Sending Your Program through E-mail: Creating a Compressed (zipped) File.
2. Right-click the .zip file and choose Extract All.
The Extraction Wizard opens.
3. In the wizard, click the Next button.
The Select a Destination pane displays.
4. Type the path for the folder into which you want to install the program, or click the Browse button to navigate to the
folder, and then click Next.
The files are extracted and the Extraction Complete pane displays.
5. Select the Show extracted files check box, and then click Finish.
A new Windows Explorer window opens, bringing you to the folder that you chose in the previous step.
6. Double-click the ProgramName.exe file (where ProgramName is the name of the program) to run the program.
Note
All programs created with Visual Basic require the Microsoft .NET Framework version 2.0. If you are going to distribute
your program through e-mail, make sure that the .NET Framework is already installed on the computers of any recipie
nts.
Tip
The .NET Framework is distributed with many other programs. It can also be downloaded from the Microsoft Web site.
You can check to see if the .NET Framework is installed by going to the Control Panel, opening Add or Remove Prog
rams, and looking for Microsoft .NET Framework version 2.0.
Next Steps
In this lesson, you learned how to extract and run a program that you received through e-mail from a trusted source. You also
learned that it is dangerous to execute any file from a source that you do not trust. You have now completed the basics! You
can take some time to explore Visual Basic on your own and write a few programs, or you can read suggestions for learning
more about Visual Basic.
Next Lesson: Moving Forward: Where Do I Go From Here?
See Also
Tasks
Sending Your Program through E-mail: Creating a Compressed (zipped) File
Other Resources
Distributing Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts
Code Snippets
One way to increase your productivity is to avoid writing the same code over and over again. Visual Basic 2005 includes a code
library of approximately 500 pieces of code, called IntelliSense code snippets, which are ready to be inserted into your
application. Each snippet performs a complete programming task, such as creating a file, sending an e-mail message, or
drawing a circle. You can insert a snippet into your source code with a few mouse clicks.
Once the snippet has been inserted, the parts of the code that need to be replaced are highlighted; you can enter your own
values if you like. For example, a code snippet to draw a line on a form has values for the color, location, and length of the line.
You can change these values to meet your needs, or you can do nothing and draw a line using the default values.
You can also create your own snippets that suit your own needs, add them to the library, and then use them when needed.
When creating your own snippets, you decide which parts of the code will be highlighted and what the default values are. For
more information, see Creating and Using IntelliSense Code Snippets.
One common task that can be accomplished using code snippets is reading and writing text to a file. The following procedure
shows how code snippets can make you more productive.
Try It!
To use code snippets
1. On the File menu, choose New Project.
2. In the Templates pane, in the New Project dialog box, click Windows Application.
3. In the Name box, type Snippets and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor.
5. In the Code Editor, right-click the Form1_Load event handler, and choose Insert Snippet from the drop-down menu.
A list of snippet categories is displayed.
6. Double-click Processing Drives, Folders, and Files.
A list of code snippets is displayed.
7. Double-click Write Text to a File.
The following code will be inserted, and "C\Test.txt" and "Text" will be highlighted.
Note
The WriteAllText method will create the file if it doesn't exist. If it already exists, it will add the text at the end of the file
.
8. Replace "C\Test.txt" with "C\MySnippetTest.txt", and replace "Text" with "This is really fast!".
9. Add a second snippet—right-click and choose Insert Snippet from the menu.
10. Double-click Processing Drives, Folders, and Files.
11. Double-click Read Text from a File.
The following code will be inserted, and "C\Test.txt" will be highlighted.
MsgBox(fileContents)
As you can see, the My way is much simpler (and much easier to discover), saving you time and effort. You could still use the
other way of determining the version number, by why would you?
Although you may not have noticed, you have already used My in a number of earlier lessons. As you enter code for your next
application, explore the My objects by typing My and drilling down through the list of items that appears. For more information,
see Development with My.
IntelliSense
As you have worked through the lessons and entered code, you probably noticed that as you type, a drop down list of choices
appears in the Code Editor. This is one example of the feature known as IntelliSense.
IntelliSense provides a number of features that make language references easily accessible. When writing code, you do not
need to leave the Code Editor to get information about language elements. You can stay where you are, find the information
you need, insert language elements directly into your code, and even have IntelliSense complete your typing for you.
IntelliSense is also helpful when you are debugging. In the Code Editor, you can move the cursor over a variable in your code
to display a ToolTip with the current value of the variable. IntelliSense is also available when entering code in the Immediate
window. For more information, see Using IntelliSense.
Next Steps
In this lesson, you learned about some of the productivity features in Visual Basic 2005. There are many other features that
help to make Visual Basic 2005 the best tool for rapid application development; links to a few of them are listed below.
In the next lesson you will learn about some of the more surprising things that you can do with Visual Basic 2005.
Next Lesson: Tips and Tricks: I Didn't Know I Could Do That.
See Also
Concepts
Moving Forward: Where Do I Go From Here?
How Do I in Visual Basic Express
Other Resources
Distributing Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts
An individual question or answer in a forum is known as a post; a collection of posts on a single topic is known as a thread. If
you can't find a previous thread that answers your question, you can post a message to the forum with your specific question,
and then check the thread later to see if anyone has answered your question.
Some tips for using forums:
Read the Visual Basic documentation first. If a topic is covered in Help, don't expect other users to research it for you. On
the other hand, if the Help is there but you don't understand it, ask away.
Search the forum to see if the question has already been asked and answered. If you are asking a frequently asked
question, your post may be ignored.
Choose the correct forum. If you post a question about the Visual Basic language in a Windows Forms forum, you are
less likely to get an answer than if you post to the Visual Basic Language forum.
Use a descriptive title for your post. Asking "Can someone help me?" is less likely to get a response than asking "Does
anyone know how to make a user control with a transparent background?"
Phrase your question clearly. Explain what you are trying to do and what isn't working; include what you have already
tried and what the results were.
Include code where appropriate. If a particular line of code is causing an error, include enough code to make it clear what
that line is trying to accomplish. Do not, however, try to post you entire application and expect someone else to debug it
for you.
If you ask a question, try to answer someone else's question. The more you are willing to help others in the community,
the more they will be willing to help you.
Always be polite. If someone answers your question, thank them. Remember that everyone answering questions on the
forum is doing so voluntarily.
In addition to the MSDN Community Forums, there are many other forums related to Visual Basic, Windows Forms, and other
technologies. Some of these may be available by choosing Codezone Community from the Community menu in Visual
Basic 2005, or you can search online.
Try It!
To visit a forum
1. On the Community menu in Visual Basic 2005, select Ask a Question.
The MSDN Community Forums search page is displayed.
2. In the Enter Keywords field, type VB Transparent User Control, and then click Go.
Previous posts that match the keywords are displayed if any are available.
3. Review the posts to see if any of them explain how to create a transparent user control.
If none of the posts answers your question, you could post a more specific question by choosing Visual Basic General
from the Can't find the answer? list.
4. To check and see if your question has been answered, on the Community menu, choose Check Question Status.
Tip
You can also choose to be notified by e-mail, instant messenger, or even by a text message to your cell phone when a t
hread is responded to. When you enter a post or reply to a post on a forum, just click the Alert Me button.
The Search function in Help allows you to search not only in the local Help system, but also in the MSDN Online Library and in
the Codezone community, a collection of online resources for Visual Basic. The MSDN Online Library may contain newer
versions of Help topics, as well as articles that aren't in the documentation; the Web sites that make up the Codezone
community contain helpful information from many Visual Basic experts.
Note
To access the MSDN Online Library and the Codezone community, you must have an active connection to the Internet, and a
ny proxy server or firewall must be configured to allow access. In addition, your Help settings must be configured for online
access. For more information, see How to: Include Online Content in Search and F1 Help Results.
The Visual Basic team at Microsoft is always interested in hearing from you, whether you want to suggest an improvement to
Visual Basic 2005, report a product bug, or make suggestions regarding the documentation.
The Product Feedback Center allows you to enter both product and documentation suggestions and report bugs, as well as to
see those entered by others. You can also track the progress of your suggestions and bug reports, vote on suggested features,
and much more. To access the Product Feedback Center, on the Community menu, choose Send Feedback.
The Microsoft Visual Basic Developer Center contains frequently updated articles and other information about Visual Basic. To
access the Developer Center, on the Community menu, choose Developer Center.
The CodeWise Community site is a resource for third-party tips, code samples, advice, and news from independent experts on
the Microsoft .NET Framework and Microsoft Visual Studio 2005. To access the CodeWise Community site, on the Community
menu, choose Codezone Community.
User groups are local organizations of programmers with similar interests—there are many user groups throughout the world
dedicated to Visual Basic and Visual Basic 2005. Most user groups meet on a regular basis to demonstrate coding techniques,
exchange information, and make contacts with other programmers. If you live in or near a major city, chances are there is a
Visual Basic user group near you.
Next Steps
In this lesson, you learned about some of the resources available to the world-wide Visual Basic community. In the next lesson
you will learn about resources for learning more about Visual Basic 2005.
Next lesson: Tell Me More: Resources for Learning Visual Basic.
See Also
Tasks
Tips and Tricks: I Didn't Know I Could Do That
Concepts
Moving Forward: Where Do I Go From Here?
How Do I in Visual Basic Express
Other Resources
Visual Basic Guided Tour
Visual Basic Language Concepts
5. Double-click the form to open the Code Editor, and enter the following in the Form1_Load event handler.
6. Place the cursor inside the word Name and press F1.
A Help topic for the My.User.Name property is displayed.
7. Place the cursor inside the word User and press F1 again.
A Help topic for the My.User object is displayed.
Product Documentation
The product documentation for Visual Basic 2005 contains a wealth of information for learning Visual Basic, including
numerous "How to" topics, walkthroughs, and in-depth conceptual information, as well as reference topics for every member
of the .NET Framework. Taking some time to browse through the documentation is a good way to learn about features of
Visual Basic 2005 that you might not know about.
Depending on the choices that you made when you installed Visual Basic Express Edition, you may find that some of the topics
are not available. The Help files that are included with Visual Basic Express Edition are a limited subset of the MSDN Library for
Visual Studio 2005 Express Editions, which is, in turn, a subset of the full MSDN Online Library. During installation you had the
option of installing the MSDN Library for Visual Studio 2005 Express Editions—if you chose not to install it, you should
consider doing so now.
Additional product documentation and updated versions of topics included in the MSDN Library for Visual Studio 2005
Express Editions are available in the MSDN Online Library. To access the MSDN Online Library, on the Community menu,
choose Developer Center, and then on the Microsoft Visual Basic Developer Center home page, choose Library.
Note
To access the MSDN Online Library, you must have an active connection to the Internet, and any proxy server or firewall mus
t be configured to allow access.
Online Resources
With several million programmers world-wide using Visual Basic, it's not surprising that there are numerous online resources
for learning more about Visual Basic. An MSN search on the keyword Visual Basic returns over 49 million results; a search on
the keyword Visual Basic 2005 returns over 2 million. With that many online resources, where do you start?
The best place to start looking for online learning resources is the Microsoft Visual Basic Developer Center, available from the
Community menu. The Developer Center is constantly updated with new articles on Visual Basic, as well as links to online
books, multimedia and Webcasts, walkthroughs, and much more. Just click on the Learning Visual Basic link on the Microsoft
Visual Basic Developer Center home page.
Another good starting place is the CodeWise Community, also available from the Community menu. The CodeWise
Community site is an online resource for third-party tips, code samples, advice, and news from independent experts on Visual
Basic and Visual Basic 2005.
Members of the CodeWise Community have established expertise in Microsoft developer tools and technologies. They provide
you with a wide range of content through their online communities and opportunities to share your opinions and learn from
others.
Additional Resources
If you prefer more traditional methods of learning, there are many additional opportunities available.
There are numerous books available covering Visual Basic 2005, ranging from beginner-level books to books on specific uses
for Visual Basic 2005, such as programming games. You can browse the Computer Programming section of your local library,
bookstore, or online bookseller to see what is currently available.
Tip
Make sure that the books that you select cover Visual Basic 2005 and not an earlier version of Visual Basic. Although much of
the material written for older versions still applies, in some cases there are newer and better techniques available in Visual Ba
sic 2005.
Many colleges, universities, and technical schools offer courses covering Visual Basic 2005, some even specifically focused on
Visual Basic Express Edition. Check in your area to see what courses are available.
Next Steps
In this lesson, you learned about some of the ways to continue learning Visual Basic. In the next lesson, you will learn how to
find and use sample code.
Next Lesson: Stealing is Okay: Samples and Starter Kits.
See Also
Tasks
Community Resources: A Little Help From My Friends
Concepts
Moving Forward: Where Do I Go From Here?
How Do I in Visual Basic Express
Other Resources
Visual Basic Guided Tour
Visual Basic Language Concepts
Copying Code
You may have noticed as you worked through the lessons that wherever there were blocks of code in the Help topics there
were also links marked Copy Code. Clicking the Copy Code link in a Help topic copies the code in that block to the Clipboard;
you can then paste it directly into the Code Editor instead of typing it.
Many Help topics contain code examples to show how you might use a particular language element, property, or function.
Although they may not match exactly what you want to do, you can copy them into your code as a starting point, and then
modify them to fit your needs by changing variable names and references.
Using Sample Applications
Visual Basic 2005 includes a number of sample applications that can give you a head start in creating your own programs.
Sample applications are complete projects that can be loaded into Visual Basic 2005 and run without modification. In most
cases they aren't very useful as programs; however, they often contain a lot of useful code.
For example, the Game sample application demonstrates a simple Windows Forms game, complete with GDI+ graphics, timer
features, user configuration, and high-score storage. If you are writing your own card game, the user interface code in the
Game sample probably won't be of much use. However, the code for storing and displaying high scores might be very useful;
you might be able to copy it and use it in your program as is.
In other cases, you might want to take the sample application and use it as a starting point, modifying and adding to it to meet
your own needs. Even if the sample doesn't do exactly what you want, it is often easier than starting from scratch. For more
information, see Visual Basic Express Sample Applications.
Starter Kits
Starter Kits are similar to sample applications, but unlike most samples, they are complete applications that can be used on
their own. For example, the My Movie Collection Starter Kit is a complete application for keeping track of your DVD movie
collection.
Like sample applications, Starter Kits can be used as a starting point for your own program. If you want to create a program for
keeping track of music files instead of movies, you can easily customize the My Movie Collection to meet your needs. Starter
Kits contain suggestions for customization, along with sample code, to help you. For more information, see
Starter Kits: Getting Up and Running Quickly.
Reusing Your Own Code
After you have been programming for a while, you will probably find that you are writing the same code over and over again.
For example, you might write code for a TextBox control to allow only numbers to be entered. Rather than writing the same
code for every program, you can write the code once and save it by dragging it to the Toolbox. The next time you need that
piece of code, you can drag it back onto the Code Editor to insert it in your code.
Tip
If you find that you are saving a lot of code to the Toolbox, you may find it difficult to find the code that you need. You can al
so save code as a Code Snippet and access it just like the Code Snippets that ship with Visual Basic 2005.
Finding Code
In addition to the code that is included in Visual Basic Express Edition, there are many other sources for obtaining code, both
from Microsoft and from third parties. You can search for code snippets, templates and starter kits, samples, and controls by
choosing Community Search on the Community menu. For more information, see How to: Search for Code Snippets Online.
You can also search Help to find topics that contain code. For more information, see How to: Find Topics with Sample Code.
Next Steps
In this lesson, you learned about several options for finding code so you don't have to write it yourself. In the next lesson, you
will find out where to get in-depth information about different features of Visual Basic Express Edition.
Next Lesson: Digging Deeper: I Want to Know More About....
See Also
Tasks
Tell Me More: Resources for Learning Visual Basic
Concepts
Moving Forward: Where Do I Go From Here?
How Do I in Visual Basic Express
Other Resources
Visual Basic Guided Tour
Visual Basic Concepts
What's New in the Visual Basic Language for Visual Basic 6.0
Users
Visual Basic 2005 has many new and improved language features—such as inheritance, interfaces, and overloading—making
it a powerful object-oriented programming language. This page highlights some of the biggest changes and provides links to
in-depth information.
Note
If you are familiar with Visual Basic 6.0, see Language Changes for Visual Basic 6.0 Users for an introduction to the new conc
epts.
Tip
For a hands-on introduction to new language features in Visual Basic 2005, see Visual Basic Guided Tour.
What's New
The following are new language features in Visual Basic 2005.
Inheritance
Visual Basic 2005 supports inheritance by allowing you to define classes that serve as the basis for derived classes. Derived
classes inherit and can extend on the properties and methods of the base class. They can also override inherited methods with
new implementations of the base class. All classes created with Visual Basic 2005 are inheritable by default. Because the forms
you design are really classes, you can use inheritance to define new forms based on existing ones. For details, see
Inheritance in Visual Basic.
Exception Handling
Visual Basic 2005 supports structured exception handling, using an enhanced version of the Try...Catch...Finally syntax
supported by other languages such as C++. Structured exception handling combines a modern control structure (similar to
Select Case or While) with exceptions, protected blocks of code, and filters. Structured exception handling makes it easy to
create and maintain programs with robust, comprehensive error handlers. For details, see Introduction to Exception Handling.
Overloading
Overloading is the ability to define properties, methods, procedures, or operators that have the same name but use different
data types. You can use overloaded procedures to provide as many implementations as necessary to handle different kinds of
data, while giving the appearance of a single, versatile procedure. For details, see Overloaded Properties and Methods.
Overriding Properties and Methods
The Overrides keyword allows derived objects to override characteristics inherited from parent objects. Overridden members
have the same arguments as the members inherited from the base class, but they have different implementations. A member's
new implementation can call the original implementation in the parent class by preceding the member name with MyBase.
For details, see Overriding Properties and Methods.
Constructors and Destructors
Constructors are procedures that control initialization of new instances of a class. Conversely, destructors are methods that free
system resources when a class leaves scope or is set to Nothing. Visual Basic 2005 supports constructors and destructors
using the Sub New and Sub Finalize procedures. For details, see Object Lifetime: How Objects Are Created and Destroyed.
Data Types
Visual Basic 2005 introduces three new data types. The Char data type is an unsigned 16-bit quantity used to store Unicode
characters. It is equivalent to the .NET Framework System.Char data type. The Short data type, a signed 16-bit integer, was
named Integer in earlier versions of Visual Basic. The Decimal data type is a 96-bit signed integer scaled by a variable power
of 10. In earlier versions of Visual Basic, it was available only within a Variant. In addition, Visual Basic now supports unsigned
integer data types (UShort, UInteger, and ULong), as well as the signed type SByte. For details, see Data Types in Visual Basic.
Interfaces
Interfaces describe the properties and methods of classes, but unlike classes, interfaces do not provide implementations. Use
the Interface statement to declare interfaces; use the Implements statement to write code that puts the items described in the
interface into practice. For details, see Interfaces in Visual Basic.
Delegates
Delegates are objects that can call the methods of objects on your behalf and are sometimes described as type-safe, object-
oriented function pointers. You can use delegates to let procedures specify an event handler method that runs when an event
occurs. You can also use delegates with multithreaded applications. For details, see Delegates and the AddressOf Operator.
Shared Members
Shared members are properties, procedures, and fields that are shared by all instances of a class. Shared data members are
useful when multiple objects need to use information that is common to all objects. You can use shared class methods without
first creating an object from a class. For details, see Shared Members in Visual Basic.
References
You can use References to use objects defined in other assemblies. In Visual Basic 2005, references point to assemblies instead
of type libraries. For details, see References and the Imports Statement.
Namespaces
Namespaces prevent naming conflicts by organizing classes, interfaces, and methods into hierarchies. For details, see
Namespaces in Visual Basic.
Assemblies
Assemblies replace and extend the capabilities of type libraries by describing all the required files for a particular component or
application. An assembly can contain one or more namespaces. For details, see Assemblies.
Attributes
You can use attributes to provide additional information about program elements. For example, you can use an attribute to
specify which methods in a class should be exposed when the class is used as a XML Web service. For details, see
Attributes in Visual Basic.
Multithreading
You can use Visual Basic 2005 to write applications that can perform multiple tasks independently. A task that can hold up
other tasks can execute on a separate thread, a process known as multithreading. By causing complicated tasks to run on
threads that are separate from your user interface, multithreading makes your applications more responsive to user input. For
details, see Multithreaded Applications.
Bit Shift Operators
Visual Basic 2005 now supports arithmetic left- and right-shift operations on integral data types (Byte, Short, Integer, and
Long) as well as on unsigned types (UShort, UInteger, and ULong). Arithmetic shifts are not circular, which means the bits
shifted off one end of the result are not reintroduced at the other end. The corresponding assignment operators are provided
as well. For details, see Bit Shift Operators and Assignment Operators.
Loop Variable Declaration
You can use Visual Basic 2005 to declare a loop variable as part of a For or For Each loop. You can include an As clause for the
variable in the For or For Each statement, provided no variable of that name has been declared outside the loop. The scope of
a loop variable declared in this manner is the loop itself. For details, see For...Next Statement (Visual Basic) and
For Each...Next Statement (Visual Basic).
What's New in the Visual Basic Language for Visual Basic 2005
In this version of Visual Studio, new language features in Visual Basic 2005 include loop continuation, guaranteed resource
disposal, mixed access properties, unsigned data types, operator overloading, generic types, and much more. For more
information, see What's New in the Visual Basic Language.
See Also
Concepts
What's New for Visual Basic 6.0 Users
What's New in Windows Forms for Visual Basic 6.0 Users
What's New in the Visual Studio IDE for Visual Basic 6.0 Users
Visual Basic Concepts
What's New
The following are all a part of client application development with Windows Forms.
Windows Forms
Windows Forms is the new platform for Microsoft Windows-based application development, based on the .NET Framework.
You can use this framework to create powerful and rich Windows-based applications using a clear, object-oriented, extensible
set of classes. For details, see Windows Forms Overview.
Windows Forms Controls
Visual Basic 2005 includes all of the controls that you are familiar with from Visual Basic 6.0, and most controls are enhanced
with new properties, methods, and events that make them more powerful. Also, there are a number of new controls and
components to create your user interface. For more information, see Controls to Use on Windows Forms.
Windows Forms as the Presentation Layer of a Three-Tier Application
Using HTTP calls to a server connected to a database, Windows Forms can act as the user interface combining the user
interface of a client application with the advanced processing of an application server. For details, see
Walkthrough: Creating a Distributed Application.
Creating a Client Application
You can use Windows Forms to create a rich client application using Visual Basic. This application can access a wide variety of
data sources and provide data-display and data-editing facilities using Windows Forms controls. For details, see
Walkthrough: Creating a Simple Windows Form.
Windows Forms Security Model
Windows Forms security is based on the security policies established within the .NET Framework. The System.Security
namespace provides the underlying structure of the .NET Framework security system, including base classes for permissions.
For details, see Windows Forms Security.
Tag and Name Properties
The Tag and Name properties are now part of the Control class. The Tag property is a repository within memory to store
data about the control. The Name property contains the name of the control. The Name property can be used at run time to
evaluate the object by name rather than by type and programmatic name. For more information about the Tag property, see
Control.Tag Property. For more information about the Name property, see Control.Name Property.
Nonrectangular Windows Forms
It is easy to customize the shape of Windows Forms. For nonrectangular forms, you just need an image file and a few property
settings. For details, see How to: Create a Shaped Windows Form.
Smart Device Programmability
You can now use Visual Basic to develop rich applications for resource-constrained devices. You can use the tools provided by
Visual Studio 2005 and the .NET Compact Framework, a subset of the .NET Framework, to create, build, and debug applications
that run on smart devices.
While almost the entire Visual Basic language is supported for device development, certain Visual Basic 2005 features were
changed or dropped to accommodate for the inherent differences in device applications. For more information, see
Differences from Desktop in .NET Compact Framework Development.
What's New in Windows Forms and Controls for Visual Studio 2005
In addition to the features listed above, there are a number of features and enhancements that are brand new in Visual Basic
2005, including several new controls, support for background operations, and custom drawing of several controls. For more
information, see What's New in Windows Forms and Windows Forms Controls.
See Also
Concepts
What's New for Visual Basic 6.0 Users
What's New in the Visual Basic Language for Visual Basic 6.0 Users
What's New in the Visual Studio IDE for Visual Basic 6.0 Users
Visual Basic Concepts
What's New in the Visual Studio IDE for Visual Basic 6.0 Users
At first glance, the Visual Basic 2005 integrated development environment (IDE) may seem unfamiliar, but as you start to use it,
you will find that it has many new features that make you more productive. This page highlights some of the biggest changes
and provides links to in-depth information.
Note
If you are familiar with Visual Basic 6.0, see Integrated Development Environment for Visual Basic 6.0 Users.
Tip
For a hands-on introduction to new features in Visual Basic 2005, see Visual Basic Guided Tour.
What's New
The following are a few of the new IDE features in Visual Basic 2005.
Shared IDE
All of the .NET languages, including Visual Basic, Visual C#, Visual C++ and more, are hosted within the Visual Studio IDE.
Sharing a single IDE provides many benefits, including consolidating similar tools from the various products into a set of
shared tools used throughout Visual Studio.
Window Management
Visual Studio makes it easier than ever to view more of your code on-screen at one time.
Tabbed documents automatically tab document windows together within the IDE. For example, when you edit multiple
documents in an editor or designer, the documents all appear in the multiple-document interface (MDI) area as tabs at the top.
Auto Hide allows you to minimize tool windows such as Solution Explorer and the Toolbox along the edges of the IDE so
that the windows do not occupy valuable space. By minimizing tool windows, you can increase the viewable space of the
editor.
For more information, see Window Management.
Editing Features
Visual Studio now has a unified Code Editor for all languages in the IDE; it includes specialized features for each language. The
Code Editor has several enhancements, such as word wrap, incremental search, code outlining, collapse to definition, line
numbering, color printing, and shortcuts. You can access these features from the Edit or context menus. For more information,
see What's New in Code Editing.
Code Snippets are segments of sample code ready to insert into Visual Basic projects. To display a list of available code
snippets, right-click the active document in the Code Editor and then click Insert Snippet on the shortcut menu. Click the
name of the snippet you want, and the code is inserted into the editor, ready for you to modify as needed. For more
information, see How to: Manage Code Snippets.
Similar to Office smart tags, Visual Studio smart tags make common tasks available that apply to the context of your work. For
example, using smart tags, you can now correct some common errors in Visual Basic with a click of a button.
Deployment
ClickOnce deployment allows you to deploy self-updating Windows-based applications that can be installed and run as easily
as Web applications. You can deploy Windows client and command-line applications. There is a new Publish Project
command on the Project menus. For more information, see ClickOnce Deployment.
You can now include required system components, such as the .NET Framework runtime, as a part of a deployment project or
ClickOnce deployment. For more information, see Deploying Prerequisites (Visual Studio).
Using Setup and Deployment projects, you can distribute applications using Microsoft Windows Installer technology, deploy
to production and staging servers, deploy tiers of your application to different test computers, and deploy ASP.NET Web
applications to Web servers. For more information, see Windows Installer Deployment.
Microsoft Build Engine
The Microsoft Build Engine (MSBuild) is the new build platform for Microsoft and Visual Studio. MSBuild introduces a new
XML-based project file format that is simple to understand, easy to extend, and fully supported by Microsoft. The MSBuild
project file format enables developers to fully describe what items need to be built, as well as how they need to be built, with
different platforms and configurations. In addition, the project file format enables developers to author re-usable rules that can
be factored into separate files so that builds can be done consistently across different projects within their product. For more
information, see MSBuild.
What's New in the Visual Studio IDE for Visual Basic 2005
In this version of Visual Studio, new IDE features in Visual Basic 2005 include predefined settings, task list and error list
enhancements, improved docking behavior, the IDE Navigator window, and much more. For more information, see
What's New in the Development Environment.
See Also
Concepts
What's New for Visual Basic 6.0 Users
What's New in the Visual Basic Language for Visual Basic 6.0 Users
What's New in Windows Forms for Visual Basic 6.0 Users
What's New in Visual Basic
Visual Basic Concepts
In Visual Basic 2005, events are tied to event handlers by means of delegates, allowing you to create a single event handler for
multiple objects.
VB
Private Sub HelpButton_Click(ByVal sender As Object, ByVal e As _
System.EventArgs) Handles HelpButton.Click, HelpMenu.Click
sender.Text = "Help me!"
End Sub
In the above example, notice that the event declaration has a Handles clause that defines which events will be handled—in this
case, the Click events for both the HelpButton and HelpMenu objects. The objects and events do not have to be of the same
type; for example you might have a single event handler that handles the Click event of a button, the DoubleClick event of a
text box, and the Tick event of a timer.
Notice also that the event declaration contains two parameters: ByVal sender As Object and ByVal e As System.EventArgs.
The first parameter, sender, provides a reference to the object that raised the event. The second parameter, e, passes an object
specific to the event that is being handled. By referencing the object's properties (and, sometimes, its methods), you can obtain
information such as the location of the mouse for mouse events, or data being transferred in drag-and-drop events.
In the following example, the MouseDown event handler uses the sender parameter to determine the type of object that
generated the event, and if the object is a PictureBox, the e parameter is used to move a label to the location where the click
took place. To duplicate this example, add two PictureBox controls and a Label control to a form.
VB
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As _
System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown, _
PictureBox1.MouseDown, PictureBox2.MouseDown
If TypeOf sender Is PictureBox Then
Label1.Location = sender.Location + e.Location
Else
MsgBox("Please click a picture")
End If
End Sub
Typically, each event produces an event handler with a different event-object type for the second parameter. Some event
handlers, such as those for the MouseDown and MouseUp events, have the same object type (MouseEventArgs) for their
second parameter. For these types of events, you can use the same event handler to handle both events.
For events that pass different event object types, you must create separate event handlers. For example, the TextChanged
event of a TextBox control passes the generic EventArgs event object, and the MouseDown event passes the more
specialized MouseEventArgs event object. The MouseEventArgs object contains properties that are specific to mouse events
such as Button, to determine which mouse button was pressed; these properties do not apply to a TextBox control and would
cause an error if you tried to reference them.
In addition to the conceptual differences in event handling, the names and behavior of some events for various objects are
different in Visual Basic 2005. For more information, see Windows Forms Controls for Visual Basic 6.0 Users.
See Also
Concepts
Event Handlers Overview (Windows Forms)
Other Resources
Creating Event Handlers in Windows Forms
Visual Basic Concepts
The following table shows some Visual Basic 6.0 windows and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005
Color Palette New implementation
Menu Changes
Menu commands in Microsoft Visual Studio 2005 are standardized for all languages; in some cases, Visual Basic 6.0 menu
commands are replaced by different commands in Microsoft Visual Studio 2005.
In Visual Basic 6.0, all menu commands are visible at all times but are dimmed when out of context; in Visual Basic 2005, the
set of available commands differs according to context.
The following table lists some common Visual Basic 6.0 commands and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005
Add-Ins, Add-In Manager Tools, Add-in Manager
Debug, Edit Watch New implementation. Watches are edited in the Watch window.
Debug, Run To Cursor Run To Cursor (context menu only)
Debug, Set Next Statement Set Next Statement (context menu only)
Debug, Show Next Stateme Show Next Statement (context menu only)
nt
File, Save Project Group File, Save SolutionName or File, Save All
Format, Size to Grid New implementation. Controlled by Snap to Grid environment option.
Project, Add Data Environm New implementation. Data Environment is not supported.
ent
Project, Add Data Report New implementation. Data Reports are not supported.
Project, Add DHTML Page New implementation. DHTML Pages are not supported.
Project, Add File Project, Add New Item or Project, Add Existing Item
Note In Visual Basic 6.0, the file itself is added to the project; in Visual Basic 2005 a copy of the fil
e is added.
Project, Add Form Project, Add Windows Form or Project, Add Inherited Form
Project, Add MDI Form Project, Add Windows Form or Project, Add Inherited Form
Project, Add Property Page New implementation. Property Pages are not supported.
Project, Add User Documen New implementation. ActiveX Documents are not supported.
t
Project, Add Web Class New implementation. Web Classes are not supported.
Run, Start With Full Compil New implementation. You can still run without debugging by pressing CTRL+F5.
e
Tools, Add Procedure New implementation. Procedures are added in the Code Editor.
Tools, Menu Editor New implementation. The Menu Editor is replaced by the MainMenu and ContextMenu componen
ts.
View, Data View Window New implementation. There is no Data View window.
View, Definition Go To Definition (context menu only)
View, Form Layout Window New implementation. There is no Form Layout window.
View, Immediate Window Debug, Windows, Immediate
Compile options New implementation. For more information, see Visual Basic Compiler.
Icon Icon
Application tab of the Project Designer.
Project Description Description—Assembly Information dialog box, accessible from the Applicatio
n tab of the Project Designer.
Title Title
Assembly Information dialog box, accessible from the Application tab of the Pr
oject Designer.
See Also
Concepts
Component Authoring for Visual Basic 6.0 Users
Other Resources
Project Properties (Visual Studio)
Project Management for Visual Basic 6.0 Users
Visual Basic Concepts
ActiveX Document No equivalent. Visual Basic 2005 can interoperate with ActiveX Documents.
DHTML Application No equivalent. Use a Visual Web Developer ASP.NET Web Site Application.
IIS Application (Web No equivalent. Use a Visual Web Developer ASP.NET Web Site Application.
Class)
See Also
Concepts
Default Project Templates in Visual Studio
Web Programming for Visual Basic 6.0 Users
Other Resources
Project Management for Visual Basic 6.0 Users
Visual Basic Concepts
As Any keyword phr Not supported in Visual Basic 2005. See Does not apply
ase Declaration Syntax for Visual Basic 6.0 Users.
Chr$, ChrB, function Chr Function Visual Basic Run-Time Library Members
s , Strings module
Currency data type Decimal Data Type; see Visual Basic Run-Time Library Members
Data Type Changes for Visual Basic 6.0 Users , VariantType Enumeration
Date function, Date Now Property, Today Property Visual Basic Run-Time Library Members
statement , DateAndTime module
Date$ function DateString Property Visual Basic Run-Time Library Members
, DateAndTime module
Deftype statements Not supported in Visual Basic 2005. See Does not apply
Data Type Changes for Visual Basic 6.0 Users
Eqv operator = Operator; see Boolean Operator for Visual Basic 6.0 Users Does not apply
GoSub statement Not supported in Visual Basic 2005; use the Return Statement. S Does not apply
ee Control Statement for Visual Basic 6.0 Users.
Imp operator Not supported in Visual Basic 2005. See Not and Or operators, a Does not apply
nd Boolean Operator for Visual Basic 6.0 Users.
Initialize event Not supported in Visual Basic 2005; use Sub New. See Does not apply
Class_Initialize Changes for Visual Basic 6.0 Users and
Using Constructors and Destructors
Input #, Input$ stat Input Function Visual Basic Run-Time Library Members
ements, Input$, Inp , FileSystem module
utB, InputB$ functio
ns
Instancing property Not supported in Visual Basic 2005. For class-level declarations, Does not apply
see Private (Visual Basic) and Public (Visual Basic). For procedur
e-level declarations, see Shared (Visual Basic).
Left$, LeftB, LeftB$ Left Function Visual Basic Run-Time Library Members
functions , Strings module
Let, Set assignment Not supported in Visual Basic 2005; the new Set statement is un Does not apply
statements related to the older one. See
Default Property Changes for Visual Basic 6.0 Users.
Line Input # statem LineInput Function Visual Basic Run-Time Library Members
ent , FileSystem module
Load statement New (Visual Basic) keyword, Show method, Load event Visual Basic Run-Time Library Members
, System.Windows.Forms namespace
Lock statement Lock, Unlock Functions Visual Basic Run-Time Library Members
, FileSystem module
LSet, RSet statement LSet Function, PadRight, PadLeft; see Visual Basic Run-Time Library Members
s Data Type Changes for Visual Basic 6.0 Users , Strings module; and
System Namespace, String Class
On ... GoSub constr Not supported in Visual Basic 2005; use Select...Case Statement. Does not apply
uction See Control Statement for Visual Basic 6.0 Users.
On ... GoTo construc Not supported in Visual Basic 2005; use Select...Case Statement. Does not apply
tion See Control Statement for Visual Basic 6.0 Users.
Option Base statem Not supported in Visual Basic 2005. See Does not apply
ent Array Bounds for Visual Basic 6.0 Users.
Option PrivateMod Not supported in Visual Basic 2005; use Module Statement. Does not apply
ule statement
Print # statement Print, PrintLine Functions Visual Basic Run-Time Library Members
, FileSystem module
Property Get, Prop Not supported in Visual Basic 2005. See Does not apply
erty Let, Property S Property Procedure Changes for Visual Basic 6.0 Users.
et statements
Right$, RightB func Right Function Visual Basic Run-Time Library Members
tions , Strings module
RSet, LSet statement RSet Function; see Data Type Changes for Visual Basic 6.0 Users Visual Basic Run-Time Library Members
s , Strings module
Scale method Not supported in Visual Basic 2005 Does not apply
Set, Let assignment Not supported in Visual Basic 2005; the new Set statement is un Does not apply
statements related to the older one. See
Default Property Changes for Visual Basic 6.0 Users
String ($) functions Not supported in Visual Basic 2005. See Does not apply
String ($) Function for Visual Basic 6.0 Users.
Terminate event Not supported in Visual Basic 2005; use Sub Dispose and Sub Does not apply
Finalize. See Using Constructors and Destructors.
Time function, Time TimeOfDay Property; see DateTime Structure, Date Data Type Visual Basic Run-Time Library Members
statement , DateAndTime module
Trim$ function LTrim, RTrim, and Trim Functions Visual Basic Run-Time Library Members
, Strings module
Type statement Not supported in Visual Basic 2005; use Structure Statement. Se Does not apply
e Structure Declaration for Visual Basic 6.0 Users.
Unlock statement Lock, Unlock Functions Visual Basic Run-Time Library Members
, FileSystem module
Variant data type Object Data Type; see Does not apply
Universal Data Type Changes for Visual Basic 6.0 Users
Wend keyword While...End While Statements and End Statement; see Does not apply
Control Statement for Visual Basic 6.0 Users
Write # statement Write, WriteLine Functions Visual Basic Run-Time Library Members
, FileSystem module
See Also
Other Resources
Language Changes for Visual Basic 6.0 Users
Help for Visual Basic 6.0 Users
Common Language Runtime
Visual Basic Concepts
This causes the array to have a fixed size, which you cannot change with the ReDim statement.
Visual Basic 2005
In Visual Basic 2005, an array does not have a permanent size. The preceding example can be rewritten as either of the
following declarations:
VB
Dim Month(11) As Integer ' Reserves 12 elements -- (0) through (11).
VB
Dim Month() As Integer = New Integer(11) {}
These declarations are equivalent. Each specifies an initial size, which you can change during execution with the ReDim
statement. To initialize the elements, you can use the following syntax:
VB
Dim Month() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
If you specify –1 for one of the dimensions, the array does not contain any elements. A ReDim statement can change an array
back and forth between empty and nonempty.
Number of Dimensions
Although an array's size can change in Visual Basic 2005, the number of dimensions must be fixed. The following example
declares a three-dimensional array:
VB
Dim Point(,,) As Double
The ReDim statement can set or change the size of each dimension, but the array always remains three-dimensional.
See Also
Reference
Dim Statement (Visual Basic)
New (Visual Basic)
ReDim Statement (Visual Basic)
Concepts
Programming Element Support Changes Summary
Other Resources
Arrays in Visual Basic
Visual Basic Concepts
On 32-bit systems, 32-bit integer operations are faster than either 16-bit or 64-bit integer operations. This means that in Visual
Basic 2005, Integer and UInteger are the most efficient and fundamental numeric types. You can improve performance in
your applications by changing your Long declarations to Integer when you migrate to Visual Basic 2005.
Note
If you are interfacing with components created on platforms other than Visual Basic 2005, you must take care that your data
types correspond to those of the other components. For example, if you use a Declare statement to refer to an external proc
edure created in Visual Basic 6.0, and the procedure defines an Integer argument (two bytes in Visual Basic 6.0), you must id
entify that argument as Short in the Declare statement, because that is the two-byte integer type in Visual Basic 2005.
See Also
Reference
Data Type Summary (Visual Basic)
Declare Statement
Concepts
Type Characters
Programming Element Support Changes Summary
Visual Basic Concepts
See Also
Reference
Object Data Type
VarType Function (Visual Basic)
VariantType Enumeration
System
Object
Type
Concepts
Data Types in Visual Basic
Value Types and Reference Types
Programming Element Support Changes Summary
Visual Basic Concepts
Or
VB
Dim I As Object, J As Integer ' I is Object, J is Integer.
Dim L, M As Integer ' L is Integer, M is Integer.
Dim N As Integer, X As Double ' N is Integer, X is Double.
See Also
Reference
String Data Type (Visual Basic)
Dim Statement (Visual Basic)
Concepts
Attributes Used in Visual Basic
Programming Element Support Changes Summary
Visual Basic Concepts
Visual Basic 2005 unifies the syntax for structures and classes. Structures support most of the features of classes, including
methods.
See Also
Reference
Structure Statement
Dim Statement (Visual Basic)
Public (Visual Basic)
Private (Visual Basic)
Concepts
Programming Element Support Changes Summary
Visual Basic Concepts
Because the For statement declares I as part of the For block, I has block scope only.
However, a variable's lifetime is still that of the entire procedure. This is true whether the variable has block scope or procedure
scope. If you declare a variable inside a block, and if you enter that block several times during the lifetime of the procedure, you
should initialize the variable to avoid unexpected values.
See Also
Concepts
Programming Element Support Changes Summary
Visual Basic Concepts
"M" and "m" mean different things, so they are case sensitive. Use uppercase "M" only for the month in the date portion of a
date/time format, and lowercase "m" only for the minutes in the time portion.
The Quarter format specifier is not supported. Instead, you can use the DatePart function, as the following example shows.
VB
Format(DatePart(DateInterval.Quarter, Now))
To display the minute as a number with or without leading zeros, use "mm" or "m", respectively. The "ttttt" format is no longer
supported. "H" and "h" mean different things, so they are case sensitive. Use uppercase "H" only for a 24-hour clock, and
lowercase "h" only for a 12-hour clock. The AM/PM formats are replaced with "t" and "tt."
The "c" specifier is used for currency formatting. For date/time formatting, use "g" for the short date/time specifier and "G" for
the general date/time specifier. Both "g" and "G" use your current locale setting to determine the appropriate date and time
formats.
User-Defined Numeric Formats
Visual Basic 6.0
In Visual Basic 6.0, the Format function converts strings to numbers if necessary before formatting them. Format displays a
trailing decimal point if there is no fractional part.
Visual Basic 6.0 supports four sections in the formatting string. These are separated by semicolons (;) and specify how to
format positive, negative, zero, and null values, respectively. Negative numbers with an empty negative section of the format
string display an empty string.
Scientific notation formatting supports both the "0" and "#" digit placeholders following the exponent.
Visual Basic 2005
In Visual Basic 2005, the Format function does not convert strings to numbers before formatting. You must pass a number in
the first argument, not a string. In the following example, the first line of code does not produce the intended result in Visual
Basic 2005, while the second one does.
VB
MsgBox(Format("1.234", "#.#")) ' Displays "#.#".
... MsgBox(Format(CSng("1.234"), "#.#")) ' Displays "1.2".
Trailing decimal points are not displayed, as the following example shows.
VB
MsgBox(Format(123, "###.")) ' Displays "123"
... MsgBox(Format(123, "###.#")) ' Displays "123"
Visual Basic 2005 supports three sections in the formatting string, for formatting of positive, negative, and zero values. If a
non-zero value rounds to zero according to the first or second format section, it is formatted according to the third section.
Negative numbers with an empty negative section of the format string display a minus sign, as the following example shows.
VB
MsgBox(Format(-1, ";")) ' Displays "-".
Scientific notation formatting supports only the "0" digit placeholder and not "#". In the following example, the first line of code
does not produce the intended result in Visual Basic 2005, while the second one does.
VB
MsgBox(Format(123, "#e+#")) ' Displays "12e+3".
... MsgBox(Format(123, "#e+0")) ' Displays "1e+2".
String Format
Visual Basic 6.0
In Visual Basic 6.0, you can create expressions for user-defined format strings with the @, &, <, >, and ! specifiers.
Visual Basic 2005
Visual Basic 2005 eliminates expression support for user-defined format strings, so the @, &, <, >, and ! format specifiers have
no meaning and are no longer supported.
See Also
Reference
Format Function
DatePart Function (Visual Basic)
Concepts
Date and Time for Visual Basic 6.0 Users
Programming Element Support Changes Summary
Visual Basic Concepts
The Eqv and Imp operators are not supported. Use the equals (=) comparison operator in place of Eqv for both logical and
bitwise evaluations. You can replace the logical Imp operator with an expression using the Not and Or operators, as shown in
the following example:
VB
Result = (Not A) Or B 'Same as A Imp B
'(True unless A is True and B is False.)
You can replace a bitwise Imp in the same manner, using Not and Or on numeric operands.
See Also
Reference
And Operator (Visual Basic)
AndAlso Operator
Or Operator (Visual Basic)
OrElse Operator
Not Operator (Visual Basic)
Xor Operator (Visual Basic)
TimeSpan
Concepts
Programming Element Support Changes Summary
Visual Basic Concepts
FindInFiles Returns a read-only collection of strings representing the names of files containing the specified text.
GetDirectories Returns a String collection representing the path names of subdirectories within a directory.
GetFiles Returns a read-only String collection representing the names of files within a directory.
GetParentPath Returns a String representing the absolute path of the parent of the provided path.
GetTempFileName Creates a uniquely named zero-byte temporary file on disk and returns the full path of that file.
MoveDirectory Moves a directory to the specified location.
SpecialDirectories Gets an object that provides properties for accessing commonly referenced directories.
See Also
Reference
System.IO Namespace
My.Computer.FileSystem Object
My.Computer.FileSystem.SpecialDirectories Object
Concepts
Parsing Text Files with the TextFieldParser Object
File Encodings
Programming Element Support Changes Summary
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Creating, Deleting, and Moving Files and Directories in Visual Basic
File, Directory, and Drive Properties in Visual Basic
Visual Basic Concepts
Passing an argument ByRef allows a procedure to change it in the calling program, which can lead to unexpected behavior.
And if that procedure calls another procedure and passes the same argument ByRef, the chances of unintentionally changing
the original variable are increased.
Visual Basic 2005
When you declare a procedure in Visual Basic 2005, the passing mechanism defaults to ByVal for every parameter. This
protects arguments against modification. The declaration in the preceding example can be rewritten as follows.
VB
Function MinutesPastHour(ByVal Seconds As Integer) As Integer
Passing seconds by value prevents the procedure from accessing the variable in the calling program, and helps avoid the pitfall
just described.
Although ByVal is the default mechanism, specifying it explicitly for every parameter removes uncertainty and makes your
code easier to read.
ByRef Property Arguments
Visual Basic 6.0
In Visual Basic 6.0, a property passed to a procedure as a ByRef argument is copied into the procedure but not copied out. This
means that any modification to such a property argument is not reflected back to the original property in the calling program,
even though it was passed ByRef.
Visual Basic 2005
In Visual Basic 2005, a property argument passed ByRef is copied both into and out of the procedure. The following example
demonstrates how a property can be changed by a procedure.
VB
Sub Reduce(ByRef Height As Single)
' ... ... ... ... ... ... ... ' Code to modify Height argument.
End Sub
VB
Dim Sq As Square = New Square ' Square has property Side of type Single.
Reduce(Sq.Side) ' Side is changed when Reduce returns.
When a procedure modifies a property argument, the value of the original property is not changed immediately in the calling
program. Instead, it is copied out when the procedure returns.
ParamArray Arguments
Visual Basic 6.0
In Visual Basic 6.0, a procedure can specify the ParamArray keyword on the last of its arguments to accept an array of Variant
arguments. You cannot declare the passing mechanism of these arguments. They are always passed ByRef.
Visual Basic 2005
In Visual Basic 2005, ParamArray arguments are always passed ByVal. The arguments in the array must all be of the data
type of the ParamArray argument.
See Also
Reference
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
ByVal
ByRef
ParamArray
Concepts
Procedure Declaration for Visual Basic 6.0 Users
Procedure Calling Sequence for Visual Basic 6.0 Users
Parameter Arrays
Programming Element Support Changes Summary
Visual Basic Concepts
If you are calling a procedure without supplying any arguments, you can include empty parentheses or leave them out
altogether.
Return Statement
Visual Basic 6.0
In Visual Basic 6.0, you use the Return statement only to branch back to the code following a GoSub statement. Both
statements must be in the same procedure.
Visual Basic 2005
In Visual Basic 2005, the GoSub statement is not supported, and you can use the Return statement to return control to the
calling program from a Function or Sub procedure.
See Also
Reference
Return Statement (Visual Basic)
Call Statement (Visual Basic)
Concepts
Declaration Syntax for Visual Basic 6.0 Users
Procedure Declaration for Visual Basic 6.0 Users
Parameter Passing Mechanism for Visual Basic 6.0 Users
Control Statement for Visual Basic 6.0 Users
Programming Element Support Changes Summary
Visual Basic Concepts
While default properties enable a certain amount of shorthand in writing Visual Basic code, they have several drawbacks:
They can make code more difficult to read. In the preceding example, if you are not familiar with the Label control, you
cannot tell from the first assignment whether the string "Important" is being stored directly in the variable lbl or in a
default property.
Given an object that you plan to use in your code, it is not always easy to discover whether it has a default property, and
if so, which property that is.
Default properties make the Set statement necessary in the Visual Basic language. The following example shows how Set
is needed to indicate that an object reference, rather than a default property, is to be assigned.
Let is still a reserved word in Visual Basic 2005, even though it has no syntactical use. This helps avoid confusion with its
former meanings. Visual Basic 2005 uses the Set statement for property procedures that set the value of a property.
Parameterized Properties
Default properties that take arguments are not ambiguous, and they are supported in Visual Basic 2005. Default properties
appear most commonly on collection classes. In the System.Windows.Forms namespace, for example, the Form class supports
the following hierarchy:
Form object
Controls property (returns a ControlCollection object for this form)
ControlCollection object (default property is Item)
Item property (returns a Control object for one item in the collection)
Control object
The Controls property returns a ControlCollection object, and the Item property returns a Control object. The following
example shows both valid and invalid use of default properties in Visual Basic 2005.
VB
Dim F As New Form ' Assume F has been created and initialized.
VB
F.Controls.Item(0).Text = "Stop" ' Valid -- no default properties used.
F.Controls(0).Text = "Stop" ' Valid -- Item is parameterized.
VB
'F(0).Text = "Stop" ' INVALID -- Form does not have a default property.
'F.Controls(0) = "Stop" ' INVALID -- No default property on Control.
You can use any name you want for the parameter for Set. If you do not supply an argument, Value is automatically generated.
This syntax change makes the Property Get and Property Set statements unnecessary, and they are not supported. Because
Visual Basic 2005 does not allow default properties without parameters, Property Let and Property Set are not needed to
distinguish whether an object reference or a default property is to be assigned. Therefore, the Property Let statement also is
not supported.
Visual Basic 2005 does not support ByRef property parameters. If a property procedure had a ByRef parameter and changed
the variable underlying the corresponding argument, the property could behave in an unexpected manner. Therefore, all
declarations of parameterized properties must specify ByVal for the parameters.
See Also
Reference
ByVal
Concepts
Default Property Changes for Visual Basic 6.0 Users
Programming Element Support Changes Summary
Visual Basic Concepts
The code to create a tree and set the property would look like this:
VB
Public Class Tree
Private yearlyGrowthValue As Integer = 5
Public Property YearlyGrowth() As Integer
Get
Return yearlyGrowthValue
End Get
Set(ByVal Value As Integer)
yearlyGrowthValue = Value
End Set
End Property
The code to create a tree and set the property would look like this:
VB
Dim growingTree As New Tree(10)
In this example, it is not possible to create a Tree without specifying the yearly growth. To allow that, you could add another
New method to the class that has no parameters. This is called overloading the constructor.
New Keyword
Visual Basic 6.0
In Visual Basic 6.0, this line of code is generally not recommended:
This is because whenever the growingTree variable is accessed, the compiler checks if the value is Nothing. If so, a new
instance is created and assigned to growingTree. This is not only inefficient, but leads to programming errors.
Visual Basic 2005
In Visual Basic 2005, the instance is not checked and no new instances are created. The only way to create a new instance is to
execute a line of code with the New or As New keywords. In effect, the line of code above is now the recommended way to
handle creating a new instance.
Upgrade Suggestions
The Upgrade Wizard upgrades the Class_Initialize method to this:
VB
'UPGRADE_NOTE: Class_Initialize was upgraded to Class_Initialize_Renamed. Click for more: m
s-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="vbup1061"'
You may be able to eliminate the call to Class_Initialize_Renamed and move the code directly into the constructor. This could
make your code more readable as it eliminates an unneeded call to a procedure. If each call to New is commonly followed by
setting a particular group of properties, consider adding a constructor that sets those properties. The Visual Basic 6.0 code
could be replaced by this code in Visual Basic 2005:
VB
Public Sub New(ByVal newYearlyGrowth As Integer)
Me.YearlyGrowth = newYearlyGrowth
End Sub
See Also
Tasks
How to: Use the New Keyword
Other Resources
Creating and Using Objects
Visual Basic Concepts
In both Visual Basic 6.0 and Visual Basic 2005, the class contains a field, mvarYearlyGrowth or yearlyGrowthValue that holds
the data.
Upgrade Suggestions
The Upgrade Wizard will upgrade a property to this:
VB
Private mvarYearlyGrowth As Short
Public Property YearlyGrowth() As Short
Get
YearlyGrowth = mvarYearlyGrowth
End Get
Set(ByVal Value As Short)
mvarYearlyGrowth = Value
End Set
End Property
The Visual Basic 6.0 Integer is upgraded to the Short in Visual Basic 2005. This could cause some type incompatibility
problems when other code tries to assign an Integer in Visual Basic 2005 to the property. You may need to review the
converted types for fields and properties to avoid other type-safety conflicts.
See Also
Reference
Dim Statement (Visual Basic)
Property Statement
Other Resources
Property Changes for Visual Basic 6.0 Users
Visual Basic Concepts
Method Overloading
Visual Basic 6.0
In Visual Basic 6.0, a class can only contain one method with a given name.
Visual Basic 2005
In Visual Basic 2005, methods can be overloaded. A method is overloaded when more than one version of the method is
defined in the class. The overloaded versions differ in their parameters and returns types. This can simplify the interface of an
object by making it smaller. The following example shows two overloads of the Draw method. For more information, see
Overloaded Properties and Methods.
VB
Public Sub Draw(ByRef theForm As System.Windows.Forms.Form)
' Add code here to draw a tree on the form.
End Sub
VB
Public Sub Draw(ByVal surface As System.Drawing.Graphics)
' Add code here to draw a tree on the graphics surface.
End Sub
Return Keyword
Visual Basic 6.0
In Visual Basic 6.0, the function name is used as a variable to return the value of the function.
Public Function GrowOneYear() As Integer
heightValue = heightValue + 10
GrowOneYear = heightValue
End Function
See Also
Reference
Sub Statement (Visual Basic)
Function Statement (Visual Basic)
Return Statement (Visual Basic)
Visual Basic Concepts
This means that BaseClass cannot appear after the New keyword. Only classes that inherit from BaseClass and that do not
also have the MustInherit modifier can be instantiated. In object-oriented literature and in other object-oriented languages, a
MustInherit class is called an abstract class. A class that is not a MustInherit class, one that can be instantiated, is called a
concrete class.
A related concept is the sealed class, a class that cannot serve as a base class. The NotInheritable keyword on a class
definition indicates this status:
VB
Public NotInheritable Class DerivedClass
End Class
Using inheritance instead of interfaces, the upgraded code can be modified to:
VB
Friend Class BaseClass
Public Sub BaseMethod()
' Add code here to define BaseMethod.
End Sub
End Class
See Also
Other Resources
Inheritance in Visual Basic
Interfaces in Visual Basic
Visual Basic Concepts
Exceptions
Visual Basic 6.0
Exceptions are not supported in Visual Basic 6.0, but raising an error is. Errors are caught using On Error GoTo statements in
conjunction with labeled statements.
Visual Basic 2005
Raising an error is supported in Visual Basic 2005. For more information, see Unstructured Exception Handling Overview.
Exceptions are new in Visual Basic 2005. The Exception class serves as a base class for all exceptions. (For more information,
see Exception Class and Properties.) Rather than creating error numbers, as in Visual Basic 6.0, the programmer creates derived
classes. This can make the code more readable. Instead of GoTo statements and labeled statements, the
Try...Catch...Finally Statement (Visual Basic) block structure is used to respond to exceptions. An example is shown below.
VB
Dim big As Integer = Integer.MaxValue
Dim bigger As Integer = Integer.MaxValue
Try
Dim biggest As Integer = big + bigger
Catch ex As Exception
MsgBox("Addition did not succeed.")
End Try
For more information, see Structured Exception Handling Overview for Visual Basic.
Upgrade Suggestions
Code that raises errors in Visual Basic 6.0 is converted to code that raises errors in Visual Basic 2005. Here is an example of
converted code that raises an error:
VB
Private mvarAge As Short
Public Property Age() As Short
Get
Age = mvarAge
End Get
Set(ByVal Value As Short)
If Value >= 0 Then
mvarAge = Value
Else
Err.Raise(vbObjectError + 2, Me, _
"Age must be greater than or equal to zero.")
End If
End Set
End Property
Using an exception instead requires only replacing the Err.Raise call with a Throw Statement (Visual Basic). Another benefit is
that the error number can be eliminated.
When upgrading events and exceptions to Visual Basic 2005, consider:
Replacing On Error GoTo statements with Try statements.
Replacing Err.Raise with Throw
Using the parameter conventions for events (Public Event StateChanged(ByVal sender As Object, ByVal e As
EventArgs)).
While individual members of the class do not have to contain any code, they may do so.
Visual Basic 2005
Visual Basic 2005 makes a clear distinction between classes and interfaces. One is declared in a Class statement; the other is
declared in an Interface statement. A class cannot act as an interface. To act as an interface, the type must be declared using
Interface. Members of an interface are not implemented. In fact, the syntax does not allow such lines of code as End Sub in an
interface definition. Members of an interface are implemented in the class that declares an interface using the Implements
statement:
VB
Interface Printable
Sub Print()
Property Mode() As Integer
End Interface
Public Class Tree
Implements Printable
Upgrade Suggestions
The only option for implementing inheritance in Visual Basic 6.0 is by using the Implements statement and a base class. In
newer versions of Visual Basic, there are two types of inheritance: implementation inheritance and interface inheritance. The
type you should select depends on your application. Issues to consider include:
Implementation inheritance, using the Inherits Statement, allows you to create new classes without writing more code.
You only add code when you want to modify the base class behavior. With interface inheritance, you have to add code
for every base class member.
Interfaces can be used when you want to inherit from more than one class. Visual Basic 2005 only supports inheriting
from one class, but a class can implement multiple interfaces.
The .NET Framework defines several interfaces that simplify common programming tasks. Examples include
IComparable, ISerializable, and IFormattable.
For many .NET Framework interfaces, the .NET Framework also supplies a class that implements the interface. An
example is the Component class that implements the IComponent interface. By inheriting from Component using the
Inherits Statement, a class gains all the features of the IComponent interface without having to write any code.
See Also
Reference
Interface Statement (Visual Basic)
Class Statement (Visual Basic)
Inherits Statement
Visual Basic Concepts
Shared Methods
Visual Basic 6.0
Visual Basic 6.0 does not support shared class members. Similar functionality is available from modules. The runtime only
creates one instance of the data in a module. The data and methods of a module have a project-wide scope. Here is an example
of a library implemented in a module:
Some advantages of using a class over a module for this library are:
The library has a name, WordLibrary, that is explicitly called out in the code.
The methods are grouped into one class, indicating their relationship to each other.
The use of a private constructor makes it clear that this class provides a set of utility methods.
The client code uses the library name, making the project organization clear to the reader.
In the .NET Framework, shared methods are commonly used to provide functionality that is related to a class, but does not
require an instance of the class. One example is the Parse method that is supported by many of the data types in the .NET
Framework. The Integer Data Type (Visual Basic) supports a Parse method that takes a string as parameter. The Parse method
returns the integer represented by the string. It does not make sense for the Parse method to be a member method. There is
no integer value to manipulate, only a string.
Accessing Shared Members
Visual Basic 6.0
Visual Basic 6.0 does not support shared class members.
Visual Basic 2005
Shared members can be accessed using the class name or instance name, as shown.
VB
WordLibrary.ReplaceTitle("Old Title", "New Title")
Shared methods cannot access any instance data unless a reference to an instance of the class is passed to the shared method.
Upgrade Suggestions
The Visual Basic 6.0 WordLibrary module is upgraded to the following code:
VB
Module WordLibrary
Public Sub GetTitle(ByRef wordXml As String)
' Add code here to find title in Xml string.
End Sub
When upgrading module code from Visual Basic 6.0 to Visual Basic 2005, consider the following:
Organizing module methods and data into classes as shared data and methods.
Moving module methods into existing classes as shared methods, when the method is related to the class.
See Also
Concepts
Shared Members in Visual Basic
Visual Basic Concepts
VB
' For this example, the Tree class has no members.
Option Strict Off
Option Explicit On
Friend Class Tree
End Class
objNewMember = Nothing
End Function
'UPGRADE_NOTE: NewEnum property was commented out. Click for more: 'ms-help://MS.MSD
NQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1054"'
'GetEnumerator = mCol.GetEnumerator
End Function
mCol = Nothing
End Sub
Protected Overrides Sub Finalize()
Class_Terminate_Renamed()
MyBase.Finalize()
End Sub
End Class
The .NET Framework and Visual Basic 2005 offer several generic collections. The advantage to using generic classes is that very
little code is required to implement the class.
To create a collection using generic collections
1. Create the class definition. Here is an example of a Tree class:
VB
Public Class Tree
Public Species As String
End Class
2. Create a generic list class from the .NET Framework. This declaration essentially replaces the entire Forest class in the
procedure above named "To use the Upgrade Wizard to create a collection."
VB
Dim forest As New System.Collections.Generic.List(Of Tree)
3. Write code to access the list object. The following code adds five instances of the Tree class to the collection and then
prints them out.
VB
For count As Integer = 1 To 5
Dim sapling As New Tree
sapling.Species = "oak"
Forest.Add(sapling)
Next
The .NET Framework includes the CollectionBase class. Typed collections are created by inheriting from CollectionBase. This
method uses less code than the Upgrade Wizard method, but more than the generics solution. It is more flexible than the
generics solution, because the programmer can add additional members to the collection class.
To create a collection from the CollectionBase class
1. Create the class definition. Here is an example of a Tree class:
VB
Public Class Tree
Public Species As String
End Class
2. Create a class that inherits from the CollectionBase class. At a minimum, add an Add method and an Item property.
These make the collection class strongly-typed.
VB
Class TreeCollection
Inherits System.Collections.CollectionBase
3. Write code to access the list object. The following code adds five instances of the Tree class to the collection and then
prints them out.
VB
Dim forest As New TreeCollection
VB
For count As Integer = 1 To 5
Dim sapling As New Tree
sapling.Species = "oak"
Forest.Add(sapling)
Next
See Also
Reference
List
CollectionBase
Ienumerable
Visual Basic Concepts
Type Customer
Dim FirstName As String
Dim LastName As String
Dim Id As Long
End Type
The Upgrade Wizard automatically upgrades a Visual Basic 6.0 type to a Visual Basic 2005 structure. The Structure is a type
that supports members, such as methods and properties.
To upgrade a type to a structure
1. Run the Upgrade Wizard.
Note
The Upgrade Wizard is a tool used to upgrade a Visual Basic 6.0 application to Visual Basic 2005. It is automatically la
unched when you open a Visual Basic 6.0 project in Visual Basic 2005. For more information, see
How to: Upgrade a Project with the Visual Basic Upgrade Wizard.
2. If you are interested in taking advantage of other features of the Structure type, look for methods that more properly
belong in the structure. In this example, the FormatFullName method could be converted to a FormatFullName method in
the structure:
VB
Structure Customer
Dim FirstName As String
Dim LastName As String
Dim Id As Integer
The Upgrade Wizard will automatically upgrade a Visual Basic 6.0 type to a Visual Basic 2005 structure. The Class type
supports the same members as a Structure, but is a reference type. A class can serve as a base class, while a structure cannot.
To upgrade to a class
1. Run the Upgrade Wizard.
2. Replace Structure with Class.
3. If you are interested in taking advantage of other features of the Class type, look for methods that more properly belong
in the structure. The following code shows the incorporation of FormatFullName into the class, and the Id property.
VB
Class Customer
Dim FirstName As String
Dim LastName As String
Private idValue As Integer
6. The Interface can then be implemented by another class. The definition is shown below.
VB
Class NewCustomer
Implements Customer
See Also
Tasks
How to: Upgrade a Project with the Visual Basic Upgrade Wizard
Reference
Structure Statement
Class Statement (Visual Basic)
Interface Statement (Visual Basic)
Visual Basic Concepts
The wizard will convert the Account class to an interface (_Account), and create two classes that implement the interface
(Account and Savings.)
VB
Interface _Account
Property Owner() As String
Function Deposit(ByVal amount As Decimal) As Decimal
End Interface
Friend Class Account
Implements _Account
Private mvarBalance As Decimal
Private mvarOwner As String
2. The code to create and use an instance of the Savings account could look like this.
VB
Dim savings As _Account
savings = New Savings
savings.Owner = "Jeff Pike"
If you want Account to be the base class, you can modify the wizard output.
To convert with Interface and Implements
1. Run the Upgrade Wizard.
2. Delete the Account class.
3. Rename the _Account class to Account.
4. In the Savings class, replace _Account with Account.
VB
Friend Class Savings
Implements Account
Private Function Account_Deposit(ByVal amount As Decimal) _
As Decimal Implements Account.Deposit
End Function
5. The code to create and use an instance of the Savings account could look like this.
VB
Dim savings As Account
savings = New Savings
savings.Owner = "Jeff Pike"
If you want the Account class to be a base class, you can modify the wizard output.
To convert with Class and Inherits
1. Run the Upgrade Wizard.
2. Delete the _Account interface.
3. In the Account class, remove references to the _Account in Implements statements.
VB
Friend Class Account
Private mvarBalance As Decimal
Private mvarOwner As String
6. The code to create and use an instance of the Savings account could look like this.
VB
Dim savings As Account
savings = New Savings
savings.Owner = "Jeff Pike"
See Also
Tasks
How to: Upgrade a Project with the Visual Basic Upgrade Wizard
Reference
Class Statement (Visual Basic)
Inherits Statement
Interface Statement (Visual Basic)
Implements Statement
Other Resources
Inheritance in Visual Basic
Interfaces in Visual Basic
Visual Basic Concepts
See Also
Reference
WebClass event is not supported
Concepts
Upgrading WebClass Projects to Visual Basic 2005
Other Resources
ASP.NET Web Pages Introduction (Visual Studio)
Visual Basic Concepts
In Visual Basic 6.0, there are two common methods of implementing data access in an application: at design time, by binding to
an ADODC (ADO data control) or by using a Data Environment, or at run time by creating and interacting with Recordset
objects programmatically.
In Visual Basic 2005, there are two analogous methods of implementing data access: at design time by using data adapters and
datasets, or at run time by adding code to create data adapters and datasets programmatically. For more information, see
Creating Data Adapters.
In Visual Basic 6.0, data binding is accomplished by setting the binding-related properties of a control: DataChanged,
DataField, DataFormat, DataMember, and DataSource. In most cases, the display property of a control (for example, the
Text property of a TextBox control) is bound to a field in a data source.
In Visual Basic 2005, data binding has a much broader definition—you can bind any property of any control to any structure
that contains data. Binding in Windows Forms is accomplished by means of a DataBindings property that contains a
collection of Binding objects for the control. For more information, see Data Binding and Windows Forms.
Note
ADO data binding is supported for backward compatibility with the Microsoft Visual Basic 2005 Compatibility Data Runtime.
In Visual Basic 6.0, data-bound forms are automatically created by dragging database elements from a Data Environment onto
a form.
See Also
Other Resources
Creating Client Data Applications
Connecting to Data with Server Explorer/Database Explorer
Visual Database Tools
Help for Visual Basic 6.0 Users
Data Namespaces in Visual Studio
Visual Basic Concepts
See Also
Concepts
User Controls for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
Label1.Text = My.Application.Info.Version.ToString()
VB
' Visual Basic 2005
PictureBox1.Image = System.Drawing.Bitmap.FromFile( _
My.Application.Info.DirectoryPath & "\Logo.jpg")
VB
' Visual Basic 2005
' Assumes that the Make Single Instance Application checkbox in the
' Project Designer has been checked.
HelpFile New implementation. Use a HelpProvider component. For more information, see
Help Support for Visual Basic 6.0 Users.
HInstance GetHINSTANCE
LogMode New implementation. For more information, see Logging Information from the Application.
LogPath
NonModalAllow New implementation. This is a read-only property related to ActiveX .dll files. The common language runti
ed me automatically manages this behavior.
OleRequestPendi No equivalent. These properties relate to OLE automation, which is not supported by Visual Basic 2005.
ngMsgText
OleRequestPendi
ngMsgTitle
OleRequestPendi
ngTimeout
OleServerBusyMs
gText
OleServerBusyMs
gTitle
OleServerBusyRa
iseError
OleServerBusyTi
meout
PrevInstance IsSingleInstance
Note
The IsSingleInstance property is a Protected property. It can only be set at design time in the Project
Designer by checking or clearing the Multiple Instance check box.
RetainedProject New implementation. Visual Basic 2005 cannot retain a project in memory.
StartLogging met New implementation. For more information, see Logging Information from the Application.
hod
StartMode No equivalent. This property concerns creating ActiveX components, which is not supported in Visual Basic
2005.
TaskVisible New implementation. To create an application that does not appear in the Task Manager, create a Windo
ws Service or Console Application project.
ThreadID New implementation. This property returned the ID of the executing thread; the threading model is signific
antly different in Visual Basic 2005.
UnattendedApp New implementation. For unattended applications in Visual Basic 2005, create a Console Application pro
ject.
Upgrade Notes
When an application is upgraded from Visual Basic 6.0, only the Major and Minor properties are upgraded; Visual Basic 2005
assigns new values to the Revision and Build properties.
See Also
Reference
My.Application Object
Concepts
Help Support for Visual Basic 6.0 Users
Version Numbering for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
Private Sub CheckBox1_CheckStateChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles CheckBox1.CheckStateChanged
If CheckBox1.Checked = True Then
CheckBox1.Text = "Checked"
Else
CheckBox1.Text = "Unchecked"
End If
End Sub
BackColor BackColor
Note
For a list of color constants, see Color Handling for Visual Basic 6.0 Users.
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
Caption Text
Container Parent
DataChanged New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataField
DataFormat
DataMember
DataSource
DisabledPictu New implementation. For more information, see
re How to: Emulate a Visual Basic 6.0 Tri-state Control in an Upgraded Application.
DownPicture
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Handling for Visual Basic 6.0 Users.
FontSize
FontStrikethr
ough
FontUnderlin
e
ForeColor ForeColor
Note
For a list of color constants, see Color Handling for Visual Basic 6.0 Users.
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
HelpContextI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
MaskColor New implementation. For more information, see MaskColor for Visual Basic 6.0 Users.
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDropMod New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
e
Picture Image
RightToLeft RightToLeft
True Yes enumeration value
No enumeration value
Style Appearance
0 (Standard) Normal enumeration value
1 (Graphical) Button enumeration value
Note
There are differences in how the Graphical style is handled in Visual Basic 2005. For more information, see
How to: Emulate a Visual Basic 6.0 Tri-state Control in an Upgraded Application.
Tag Tag
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
UseMaskColo New implementation. For more information, see MaskColor for Visual Basic 6.0 Users.
r
Value CheckState
0 (vbUncheck Unchecked enumeration value
ed)
Checked enumeration value
1 (vbChecked)
Indeterminate enumeration value
2 (vbGrayed)
WhatsThisHel New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
pID
Width Width , Size
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
Methods
Visual Basic 6.0 Me Visual Basic 2005 Equivalent
thod
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
SetFocus Focus
ShowWhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
GotFocus Enter
LostFocus Leave
OLECompl New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
eteDrag
OLEDragDr
op
OLEDragO
ver
OLEGiveFe
edback
OLESetDat
a
OLEStartDr
ag
Validate Validating
Upgrade Notes
When upgrading a Visual Basic 6.0 application using the Upgrade wizard, CheckBox controls are upgraded to Windows Forms
CheckBox controls, and code is updated to use equivalent properties, methods, and events. Where there are no equivalents or
where there are potential behavioral differences, comments are inserted into the code with a link to a Help topic.
See Also
Reference
CheckBox Control Overview (Windows Forms)
Concepts
Data Access for Visual Basic 6.0 Users
Style Property for Visual Basic 6.0 Users
Font Handling for Visual Basic 6.0 Users
Coordinate System for Visual Basic 6.0 Users
Control Arrays for Visual Basic 6.0 Users
Help Support for Visual Basic 6.0 Users
MousePointer for Visual Basic 6.0 Users
ToolTip Support for Visual Basic 6.0 Users
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts
VB
' Visual Basic 2005
My.Computer.Clipboard.Clear()
My.Computer.Clipboard.SetText("Hello")
If My.Computer.Clipboard.ContainsText Then
TextBox1.Text = My.Computer.Clipboard.GetText
End If
vbCFDIB Dib
vbCFEMetafile EnhancedMetafile
vbCFFiles FileDrop
vbCFLink No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
vbCFMetafile MetafilePict
vbCFPalette Palette
vbCFRTF Rtf
vbCFText Text
Note
The DataFormats object is a part of the System.Windows.Forms namespace. In addition to the formats listed above, DataFo
rmats supports several clipboard formats that were not supported in Visual Basic 6.0.
See Also
Tasks
How to: Clear the Clipboard in Visual Basic
How to: Read from the Clipboard in Visual Basic
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
How to: Save an Audio Stream to the Clipboard in Visual Basic
How to: Retrieve an Image from the Clipboard in Visual Basic
How to: Write to the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard Object Members
Visual Basic Concepts
VB
' Visual Basic 2005
ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList
Code Changes for Selecting the Most Recently Added Item in a ComboBox Control
The following code demonstrates how to set the selection to an item that has been added programmatically to a ComboBox
control.
VB
' Visual Basic 2005
Dim i As Integer
i = ComboBox1.Items.Add("This is a new item")
ComboBox1.SelectedIndex = i
VB
' Visual Basic 2005
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
ComboBox1.Items.Add("Nancy Davolio")
Microsoft.VisualBasic.Compatibility.VB6. _
SetItemData(ComboBox1, ComboBox1.Items.Count() - 1, 12345)
ComboBox1.Items.Add("Judy Phelps")
Microsoft.VisualBasic.Compatibility.VB6. _
SetItemData(ComboBox1, ComboBox1.Items.Count() - 1, 67890)
End Sub
VB
' Visual Basic 2005
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
BackColo BackColor
r
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
Container Parent
DataChan New implementation. For more information, see Data Control for Visual Basic 6.0 Users.
ged
DataField
DataForm
at
DataMem
ber
DataSour
ce
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMod
e
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontNam Font Handling for Visual Basic 6.0 Users.
e
FontSize
FontStrik
ethrough
FontUnde
rline
ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
HelpCont New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
extID
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
ItemData New implementation. For more information, see ItemData property cannot be upgraded.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information,
Coordinate System for Visual Basic 6.0 Users.
List Items
ListCount Count
ListIndex SelectedIndex
MousePo Cursor
inter
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
NewInde New implementation. For more information, see NewIndex property cannot be upgraded.
x
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Mode
OLEDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Mode
RightToL RightToLeft
eft
SelLengt SelectionLength
h
SelStart SelectionStart
SelText SelectedText
Style DropDownStyle
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
TopIndex New implementation. For more information, see TopIndex Property and Scroll Event for Visual Basic 6.0 Users.
WhatsThi New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
sHelpID
Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
AddItem Add
AddRange
Insert
Clear Clear
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
RemoveItem Items.Remove
SetFocus Focus
ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his
Click SelectedIndexChanged
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
GotFocus Enter
LostFocus Leave
OLEComplete New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Drag
OLEDragDrop
OLEDragOver
OLEGiveFeed
back
OLESetData
OLEStartDrag
Scroll New implementation. For more information, see TopIndex Property and Scroll Event for Visual Basic 6.0 Users.
Validate Validating
Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, the Change event of the ComboBox control is mapped to
the TextChanged event of the Visual Basic 2005 ComboBox control. The behavior of the TextChanged event differs from
that of the Change event; this difference may cause unintended results in your code.
Any code that references the ItemData, Locked, NewIndex, or TopIndex properties or any code in the Scroll event
procedure is not upgraded; warning comments are added to the code and the code must be removed or modified before
compiling the application.
See Also
Reference
ComboBox Control Overview (Windows Forms)
Concepts
Color Behavior for Visual Basic 6.0 Users
Font Object for Visual Basic 6.0 Users
MousePointer for Visual Basic 6.0 Users
ToolTip Support for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
' Set the first button to respond to the Enter key.
Me.AcceptButton = Button1
' Set the second button to respond to the Esc key.
Me.CancelButton = Button2
VB
' Visual Basic 2005
' Assumes a picture has been assigned to the BackgroundImage property.
Dim ButtonBitmap As New System.Drawing.Bitmap(Button1.BackgroundImage)
ButtonBitmap.MakeTransparent(System.Drawing.Color.White)
Button1.BackgroundImage = ButtonBitmap
BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.
Caption Text
Container Parent
DisabledPict New implementation. For more information, see Style Property for Visual Basic 6.0 Users.
ure
DownPicture
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethr
ough
FontUnderli
ne
HelpContext New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
ID
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
MaskColor New implementation. For more information, see MaskColor for Visual Basic 6.0 Users.
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePoint Cursor
er
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDropMo New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
de
Picture Image
RightToLeft RightToLeft
Style New implementation. For more information, see Style Property for Visual Basic 6.0 Users.
ToolTipText ToolTip component
For more information, see ToolTip Support for Visual Basic 6.0 Users.
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
UseMaskCol New implementation. For more information, see MaskColor for Visual Basic 6.0 Users.
or
Value New implementation. The PerformClick method is the same as setting the Value to True; for any other use of
the Value property there is no equivalent.
WhatsThisHe New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
lpID
Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
SetFocus Focus
ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his
GotFocus Enter
LostFocus Leave
OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag
Upgrade Notes
When upgrading a Visual Basic 6.0 application using the Upgrade Wizard, any CommandButton controls are upgraded to
Windows Forms Button controls and code is updated to use the equivalent properties, methods, and events. Where there are
no equivalents or where there are potential behavioral differences, comments are inserted in the code with links to Help topics.
When an application is upgraded to Visual Basic 2005, if the Style property is set to 1 – Graphical, the FlatStyle property of
the upgraded control is set to Standard, and any image assigned to the Picture property at design time is assigned to the
Image property of the upgraded control.
If the DownPicture or DisabledPicture properties were set at design time or at run time, you will need to modify your
upgraded application to use an ImageList control. For more information, see
How to: Emulate a Visual Basic 6.0 Tri-state Control in an Upgraded Application.
The Upgrade Wizard does not upgrade code that uses the MaskColor property. Upgrade warnings will be inserted into your
code. You will need to modify the code before running the application.
See Also
Concepts
MaskColor for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
' Uses a OpenFileDialog component.
OpenFileDialog1.InitialDirectory = "C:\Program Files"
OpenFileDialog1.ShowDialog()
VB
' Visual Basic 2005
' Uses a SaveFileDialog component.
SaveFileDialog1.InitialDirectory = My.Application.Info.DirectoryPath
SaveFileDialog1.ShowDialog()
VB
' Visual Basic 2005
' Uses PrintDocument and PrintDialog components.
PrintDocument1.DocumentName = My.Application.Info.DirectoryPath _
& "MyFile.txt"
PrintDialog1.Document = PrintDocument1
PrintDialog1.ShowDialog()
VB
' Visual Basic 2005
' Uses the Help.ShowHelp method.
Help.ShowHelp(Me, "file://C:\Windows\Help\calc.chm", _
HelpNavigator.TableOfContents)
CancelErr Cancel
or
Copies Copies
FileName FileNames
FileTitle New implementation. The Visual Basic 6.0 FileTitle property returns the FileName without the path; you can parse
the FileNames property to get the name without the path.
Flags The Visual Basic 6.0 Flags property provides constants for setting various attributes of the different common dialo
gs. Rather than using constants, the dialog components provide properties for setting the attributes.
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontNam Font Handling for Visual Basic 6.0 Users.
e
FontSize
FontStrik
ethrough
FontUnd
erline
FromPag FromPage
e
hDC New implementation. For more information see Graphics for Visual Basic 6.0 Users.
HelpCom HelpNavigator
mand
HelpFile HelpNamespace
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
InitDir InitialDirectory
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
MaxFileSi New implementation. This property Visual Basic 6.0 allocates memory for extremely long file names; it is no longer
ze necessary in managed code.
Orientati Landscape
on
Top P:System.Windows.Forms.Control.Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
ToPage ToPage
Methods
Visual Basi Visual Basic 2005 Equivalent
c 6.0
AboutBox New implementation. The AboutBox property displayed an About box for the CommonDialog control, which w
as created for Microsoft by a third party.
ShowHelp ShowHelp
Upgrade Notes
When upgrading an application from Visual Basic 6.0 to Visual Basic 2005, any CommonDialog controls are upgraded to
their equivalent dialog component (OpenFileDialog, SaveFileDialog, ColorDialog, FontDialog or PrintDialog).
There is no direct equivalent for showing a Help dialog in Visual Basic 2005. If a CommonDialog control is being used as a
Help dialog, a warning will be issued and it will not be upgraded. For more information, see
Help Support for Visual Basic 6.0 Users.
A single CommonDialog control could be used to display different types of dialogs. In this case it will be upgraded to a
OpenFileDialog component; a warning will be issued and you will need to add the other dialog components manually.
In addition, where a CommonDialog control was used as a variable you may need to change it to refer to a specific dialog
component after upgrade.
See Also
Reference
FontDialog Component Overview (Windows Forms)
HelpProvider Component Overview (Windows Forms)
Other Resources
ColorDialog Component (Windows Forms)
OpenFileDialog Component (Windows Forms)
SaveFileDialog Component (Windows Forms)
PrintDialog Component (Windows Forms)
PrintDocument Component (Windows Forms)
Visual Basic Concepts
VB
' Visual Basic 2005
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handl
es Button1.Click
' Create a new TextBox control.
Dim TextBox1 As New System.Windows.Forms.TextBox
TextBox1.Name = "TextBox1"
' Add the new control to the form's Controls collection.
Me.Controls.Add(TextBox1)
' No need to set Visible property.
' Set the initial text.
TextBox1.Text = "Hello"
' Retrieve the text from the new TextBox.
If Me.Controls.Count > 1 Then
MsgBox(Me.Controls("TextBox1").Text)
End If
' Remove the new control.
Me.Controls.Remove(TextBox1)
' Remove the control added at design time.
Me.Controls.Remove(Button1)
End Sub
VB
' Visual Basic 2005
Private Sub ClearChecks(ByVal Container As Control)
Dim ctl As Control
Dim chk As CheckBox
For Each ctl In Container.Controls
If TypeOf ctl Is CheckBox Then
chk = ctl
chk.Checked = False
End If
' Recursively call this function for any container controls.
If ctl.HasChildren Then
ClearChecks(ctl)
End If
Next
End Sub
Upgrade Notes
Because of differences between Visual Basic 6.0 and the Visual Basic 2005 Controls collections, calls to the Add method are
not upgraded. You must add code to recreate the behavior of your application using the new Add method.
See Also
Reference
Control.Controls Property
Form.ControlCollection Class
Visual Basic Concepts
VB
' Visual Basic 2005
Private Sub DataGridView1_EditingControlShowing( _
ByVal sender As Object, ByVal e As System.Windows.Forms. _
DataGridViewEditingControlShowingEventArgs) _
Handles DataGridView1.EditingControlShowing
CType(e.Control, TextBox).SelectionStart = 0
CType(e.Control, TextBox).SelectionLength = Len(CType(e.Control, _
TextBox).Text)
MsgBox("The selected text is " & CType(e.Control, _
TextBox).SelectedText)
End Sub
AllowArr No longer an adjustable property; arrow navigation always allowed. For more information, see
ows Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control.
AllowRo AllowUserToResizeRows
wSizing
ApproxCo New implementation. Data operations are handled in the data source. For more information, see
unt Displaying Data in the Windows Forms DataGridView Control.
BackColo BackgroundColor
r
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
Bookmar New implementation. You can now directly access any item.
k
Col SelectedColumns
ColumnH ColumnHeadersVisible
eaders
CurrentCe CurrentCell
llVisible
Note
If the CurrentCell property is set to a cell that is not visible, the grid scrolls to show that cell (similar to setting C
urrentCellVisible = True).
DataForm DataGridViewCellStyle.object.
ats
Note
Formatting can be set for an individual cell, column, or row.
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMod
e
EditActiv IsCurrentCellInEditMode
e
FirstRow FirstDisplayedScrollingRowIndex
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontNam Font Handling for Visual Basic 6.0 Users.
e
FontSize
FontStrik
ethrough
FontUnde
rline
ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
HeadLine No direct equivalent. Use the WrapMode property of the DataGridViewCellStyle object in combination with
s ColumnHeadersHeight.
HelpCont New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
extID
hWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Marquee No direct equivalent. Use the SelectionMode, CellBorderStyle, and Format properties.
Style
RecordSel RowHeadersVisible
ectors
Row SelectedRows
RowHeig Height
ht
SelBook New implementation. You can now directly access any item.
marks
SelLength No direct equivalent. Use the SelectionLength property in the EditingControlShowing event handler.
SelStart No direct equivalent. Use the SelectionStart property in the EditingControlShowing event handler.
SelText No direct equivalent. Use the SelectedText property in the EditingControlShowing event handler.
Split New implementation. Split views are not directly supported; use a SplitContainer control.
Splits
TabAcros
sSplits
TabActio StandardTab
n
Text CurrentCell.Value
Note
The Value property returns an Object; use CStr or ToString to convert it to a String.
WhatsThi New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
sHelpID
ClearSelCols ClearSelection
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users..
SetFocus Focus
ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his
SplitContaini New implementation. Split views are not directly supported; use a SplitContainer control.
ng
AfterColUpd New implementation. Data operations are handled in the data source. For more information, see
ate Displaying Data in the Windows Forms DataGridView Control.
AfterDelete
AfterUpdate RowsAdded
BeforeColEd CellBeginEdit
it
BeforeColUp New implementation. Data operations are handled in the data source. For more information, see
date Displaying Data in the Windows Forms DataGridView Control.
BeforeDelet
e
BeforeInsert
BeforeUpdat
e
Click SelectedIndexChanged
ColEdit CellBeginEdit
ColResize ColumnWidthChanged
DblClick CellMouseDoubleClick
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
Error DataError
HeadClick ColumnHeaderMouseClick
MouseDown CellMouseDown
MouseMove CellMouseMove
MouseUp CellMouseUp
OLEComplet New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
eDrag
OLEDragDro
p
OLEDragOve
r
OLEGiveFee
dback
OLESetData
OLEStartDra
g
OnAddNew RowsAdded
RowColChan CurrentCellChanged
ge
RowResize RowHeightChanged
SelChange SelectionChanged
SplitChange New implementation. Split views are not directly supported; use a SplitContainer control.
Validate Validating
Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, the Change event of the DataGrid control is mapped to the
TextChanged event of the Visual Basic 2005 DataGridView control. The behavior of the TextChanged event differs from
that of the Change event; this difference may cause unintended results in your code.
Any code related to data-specific methods or events is not upgraded. Warning comments are added to the code, and the code
must be removed or modified before compiling the application.
See Also
Reference
DataGridView Control Overview (Windows Forms)
Controls and Programmable Objects Compared in Different Languages and Libraries
Concepts
DataGridView Control Technology Summary (Windows Forms)
What's New in Windows Forms and Windows Forms Controls
Other Resources
DataGridView Control (Windows Forms)
Windows Forms Controls for Visual Basic 6.0 Users
Windows Forms Data Binding
Visual Basic Concepts
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any existing DirListBox controls are upgraded to the
VB6.DirListBox control that is provided as a part of the compatibility library (Microsoft.VisualBasic.Compatibility).
See Also
Tasks
How to: Add Visual Basic 6.0 File System Controls to Your Application
Reference
OpenFileDialog Component Overview (Windows Forms)
SaveFileDialog Component Overview (Windows Forms)
Visual Basic Concepts
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any existing DriveListBox controls are upgraded to the
VB6.DriveListBox control that is part of the Microsoft.VisualBasic.Compatibility library.
See Also
Tasks
How to: Add Visual Basic 6.0 File System Controls to Your Application
Reference
OpenFileDialog Component Overview (Windows Forms)
SaveFileDialog Component Overview (Windows Forms)
Visual Basic Concepts
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any existing FileListBox controls are upgraded to the
VB6.FileListBox control, which is provided as a part of the Microsoft.VisualBasic.Compatibility library.
See Also
Tasks
How to: Add Visual Basic 6.0 File System Controls to Your Application
Reference
OpenFileDialog Component Overview (Windows Forms)
SaveFileDialog Component Overview (Windows Forms)
Visual Basic Concepts
VB
' Visual Basic 2005
Private Sub Form1_FormClosing(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles _
MyBase.FormClosing
If e.CloseReason.UserClosing Then
e.Cancel = True
End If
End Sub
ERR_HANDLER:
' If validation failed cancel the Unload event.
If Err.Number = 380 Then
Cancel = True
End If
End Sub
VB
' Visual Basic 2005
Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As _
System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If TextBox1.Text = "" Then
MsgBox("Please enter a name")
e.Cancel = True
End If
End Sub
VB
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e _
As System.Windows.Forms.FormClosingEventArgs) Handles _
MyBase.FormClosing
' If validation failed cancel the Closing event.
If Me.Validate = False Then
e.Cancel = True
End If
End Sub
AutoRedraw New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
BorderStyle FormBorderStyle
Caption Text
ClipControls New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Controls Controls
Note
There are differences in the Controls collection in Visual Basic 2005. For more information, see
Controls Collection for Visual Basic 6.0 Users.
Count Count
Note
There are differences in the Controls collection in Visual Basic 2005. For more information, see
Windows Forms Controls for Visual Basic 6.0 Users.
CurrentX New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
CurrentY
DrawMode New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
DrawStyle
DrawWidth
FillColor New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
FillStyle
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline
ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
HasDC New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
HDC New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HWnd Handle
Image New implementation. The Image property in Visual Basic 6.0 returned a handle to a bitmap; images in Visual
Basic 2005 do not have handles.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
LinkMode No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkTopic
MaxButton MaximizeBox
MDIChild MdiParent
Note
MDI behavior is different in Visual Basic 2005. For more information, see MDI for Visual Basic 6.0 Users.
MinButton MinimizeBox
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
Moveable New implementation. For more information, see Moveable Property for Visual Basic 6.0 Users.
Name Name
NegotiateMen New implementation. For more information, see Menu Object for Visual Basic 6.0 Users.
us
OLEDropMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Palette New implementation. For more information, see Palettes for Visual Basic 6.0 Users.
PaletteMode
Picture BackgroundImage
Note
In Visual Basic 6.0, the Picture was displayed in the top left corner of the form; in Visual Basic 2005, the Ba
ckgroundImage is tiled.
RightToLeft: RightToLeft
True Yes enumeration value
False
ScaleHeight New implementation. For more information, see Coordinate System for Visual Basic 6.0 Users.
ScaleLeft
ScaleMode
ScaleTop
ScaleWidth
StartUpPositio StartPosition
n:
Manual enumeration value
0 – Manual
CenterParent enumeration value
1 – CenterOwn
er CenterScreen enumeration value
WhatsThisButt HelpButton
on
Note
There are differences in Help behavior in Visual Basic 2005. For more information, see
Help Support for Visual Basic 6.0 Users.
WhatsThisHelp New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
Form Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Circle New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Cls New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Line New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
PaintPicture New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Point New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
PopupMenu New implementation. For more information, see Menu Object for Visual Basic 6.0 Users.
PrintForm New implementation. For more information, see Printing Changes for Visual Basic 6.0 Users.
Pset New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Scale New implementation. For more information, see Coordinate System for Visual Basic 6.0 Users.
ScaleX
ScaleY
SetFocus Activate
Show Show or ShowDialog
TextHeight New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
TextWidth New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
ValidateControl Validate
s
Note
The Validate method returns True or False; ValidateControls raised an error if validation failed.
WhatsThisMode New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
Form Events
Visual Bas Visual Basic 2005 Equivalent
ic 6.0
Activate Activated
Note
In Visual Basic 6.0, the Activate event is raised only when switching between forms in the application; in Visual
Basic 2005, the Activated event also is raised when switching from other applications.
Click Click
Note
The Click event is not supported for MDI Forms.
DblClick DoubleClick
Deactivat Deactivate
e
Note
In Visual Basic 6.0, the Deactivate event is raised only when switching between forms in the application; in Visu
al Basic 2005, it also is raised when switching to other applications.
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
GotFocus Enter
Initialize New method
Note
The behavior of the New method is different than the Initialize event. For more information, see
Forms Tasks for Visual Basic 6.0 Users.
LinkClose No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkError
LinkExecu
te
LinkOpen
MouseDo MouseDown
wn
Note
The MouseDown event is not supported for MDI Forms.
MouseMo MouseMove
ve
Note
The MouseMove event is not supported for MDI Forms.
MouseUp MouseUp
Note
The MouseUp event is not supported for MDI Forms.
OLECompl New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
eteDrag
OLEDragD
rop
OLEDragO
ver
OLEGiveF
eedback
OLESetDa
ta
OLEStartD
rag
QueryUnl FormClosing
oad
Note
In Visual Basic 6.0, QueryUnload takes two arguments, Cancel and UnloadMode. In Visual Basic 2005, Cancel is
replaced by Cancel; UnloadMode is replaced by CloseReason.
Terminate Dispose method
Note
The behavior of the Dispose method is different than the Terminate event. For more information, see
Form Events for Visual Basic 6.0 Users.
Unload FormClosing
Note
The behavior of the FormClosing event is different than the Unload event. For more information, see
Form Events for Visual Basic 6.0 Users.
See Also
Concepts
Forms Tasks for Visual Basic 6.0 Users
Other Resources
Windows Forms
Visual Basic Concepts
VB
' Visual Basic 2005
MsgBox(CStr(My.Application.OpenForms.Count))
VB
' Visual Basic 2005
For Each f As Form In My.Application.OpenForms
f.Text = "Hello"
Next
See Also
Tasks
How to: Access All Open Forms of an Application
Reference
My.Application.OpenForms Property
Concepts
Form Object for Visual Basic 6.0 Users
Visual Basic Concepts
BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
ClipControls New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Container Parent
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline
ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDropMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
RightToLeft RightToLeft
WhatsThisHelp New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
ID
Frame Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
OLECompleteDrag
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, Frame controls that have their BorderStyle property set
to 0 - None are upgraded to Panel controls; all other Frame controls are upgraded to GroupBox controls.
See Also
Reference
GroupBox Control Overview (Windows Forms)
Concepts
Introduction to the Panel Control
Visual Basic Concepts
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Height Height, Size
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
HelpConte New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
xtID
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
LargeChan LargeChange
ge
Note
The default value in Visual Basic 6.0 was 1, in Visual Basic 2005 the default value is 10.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
Max Maximum
Note
The default value in Visual Basic 6.0 was 32767, in Visual Basic 2005 the default value is 100.
Min Minimum
Note
In Visual Basic 6.0 Min can be set to a value greater than Max; in Visual Basic 2005 the Minimum property can
not be set to a value greater than the Maximum property.
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePoin Cursor
ter
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
RightToLef RightToLeft
t:
Yes enumeration value
True
No enumeration value
False
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
Value Value
Note
In Visual Basic 6.0, when the Value is changed, the Change event is raised. In Visual Basic 2005 the Change ev
ent is not raised; use the ValueChanged event instead.
WhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HelpID
HScrollBar Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
SetFocus Focus
ShowWhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
GotFocus Enter
LostFocus Leave
Scroll Scroll
Note
The behavior of the Change and Scroll events have changed in Visual Basic 2005. For more information, see
Code was changed from an event to a procedure.
Validate Validating
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any code in the Change or Scroll event handlers for the
HScrollBar or VScrollBar controls is changed to a procedure due to a difference in the sequence of events. For more
information, see Code was changed from an event to a procedure.
See Also
Reference
HScrollBar and VScrollBar Controls Overview (Windows Forms)
Visual Basic Concepts
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any Image controls are upgraded to PictureBox
controls.
See Also
Reference
PictureBox Control Overview (Windows Forms)
Concepts
PictureBox Control for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
' Specify the color to be used as a mask and use the mask.
ImageList1.TransparentColor = Color.White
' Don't use the mask.
ImageList1.TransparentColor = Color.Transparent
hImageList Handle
ImageHeight ImageSize
ImageWidth
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
ListImages ImageCollection
MaskColor TransparentColor
Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any ImageList controls are upgraded to Windows Forms
ImageList components. Where properties, methods, and events have no equivalent or have differences in behavior, upgrade
notes or warnings will be added to your code.
See Also
Reference
ImageList Component Overview (Windows Forms)
Other Resources
ImageList Component (Windows Forms)
Visual Basic Concepts
WordWrap Property
In Visual Basic 6.0, the WordWrap property determines if text wraps to multiple lines when it is too long to fit in a label.
In Visual Basic 2005, the text in a Label control automatically wraps. The only way to prevent wrapping is to make the height of
the Label control equivalent to a single line of text.
Other Differences
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag-and-drop functionality, Help support and more. For more information, see
Windows Forms Concepts for Visual Basic 6.0 Users.
Code Changes for the Label Control
The following code example illustrates the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Making a Label Transparent
The following example demonstrates making the background of a label control transparent. In Visual Basic 6.0, if there are
other controls behind the Label, those controls show through. In the Visual Basic 2005 example, any controls behind the Label
can optionally show through using the BringToFront and SendToBack functions.
VB
' Visual Basic 2005
Private Sub MakeTransparent()
Label1.BackColor = System.Drawing.Color.Transparent
' Let controls behind the label show through.
Label1.SendToBack()
' Make the portion of controls behind the label transparent
Label1.BringToFront()
End Sub
AutoSize AutoSize
BackColor BackColor
Note For a list of constants, see Color Handling for Visual Basic 6.0 Users.
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
BackStyle New implementation. For more information, see Conceptual Differences above.
Caption Text
Container Parent
DataChanged New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataField
DataFormat
DataMember
DataSource
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Font Font
FontBold Note Fonts are handled differently in Visual Basic 2005. For more information, see
Font Handling for Visual Basic 6.0 Users.
FontItalic
FontName
FontSize
FontStrikethro
ugh
FontUnderline
ForeColor ForeColor
Note
For a list of constants, see Color Handling for Visual Basic 6.0 Users.
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
LinkItem No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkMode
LinkTimeOut
LinkTopic
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDropMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
RightToLeft: RightToLeft
True Yes enumeration value
False No enumeration value
WhatsThisHelp New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
ID
Label Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
LinkExecute No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkPoke
LinkRequest
LinkSend
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
ShowWhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
LinkClose No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkError
LinkNotify
LinkOpen
OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any Label controls are upgraded to Windows Forms
Label controls, and properties, methods and events are upgraded to their equivalent. Where there may be differences in
behavior, upgrade comments are inserted into the code.
See Also
Concepts
Introduction to the Label Control
Visual Basic Concepts
VB
' Visual Basic 2005
' Using Label controls.
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim Line1 As New System.Windows.Forms.Label
Dim Line2 As New System.Windows.Forms.Label
' Draw a horizontal line 14 pixels from the top of the form.
Line1.Location = New System.Drawing.Point(0, 14)
Line1.Size = New System.Drawing.Size(Me.Width, 1)
Line1.BorderStyle = BorderStyle.None
Line1.BackColor = System.Drawing.Color.Red
Line1.Text = ""
Controls.Add(Line1)
' Draw a vertical line 14 pixels from the left of the form.
Line2.Location = New System.Drawing.Point(14, 0)
Line2.Size = New System.Drawing.Size(1, Me.Height)
Line2.BorderStyle = BorderStyle.None
Line2.BackColor = System.Drawing.Color.Blue
Line2.Text = ""
Controls.Add(Line2)
End Sub
VB
' Visual Basic 2005
' Using Graphics methods
Private Sub Form1Paint(ByVal sender As Object, _
ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a horizontal line 28 pixels from the top of the form.
e.Graphics.DrawLine(Pens.Red, 0, 28, Me.Width, 28)
' Draw a vertical line 28 pixels from the left of the form.
e.Graphics.DrawLine(Pens.Blue, 28, 0, 28, Me.Height)
End Sub
VB
' Visual Basic 2005
Private Sub FormPaint(ByVal sender As Object, _
ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a diagonal line from the top left to the lower right.
e.Graphics.DrawLine(Pens.Black, 0, 0, Me.ClientSize.Width, _
Me.ClientSize.Height)
End Sub
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, vertical or horizontal Line controls are replaced with the
Windows Forms Label control, with the Text property set to an empty string, the BorderStyle property set to None, and the
BackColor, Width, and Height properties set to match the original control.
Line controls that were not vertical or horizontal are not upgraded. You can replace the Line control using the Graphics
functions built into the .NET Framework.
See Also
Concepts
Graphics for Visual Basic 6.0 Users
Visual Basic Concepts
VB
'Visual Basic 2005
' Add an item at the end of the list.
ListBox1.Items.Add("Tokyo")
' Insert an item at the top of the list.
ListBox1.Items.Insert(0, "Copenhagen")
' Remove the first item.
ListBox1.Items.RemoveAt(0)
VB
' Visual Basic 2005
Private Function GetItemText(ByVal i As Integer) As String
' Return the text of the item using the index:
GetItemText = CStr(ListBox1.Items(i))
End Function
VB
' Visual Basic 2005
' Determine if there are any items checked.
If CheckedListBox1.CheckedItems.Count <> 0 Then
' If so, loop through all checked items and print results.
Dim x As Integer
Dim s As String = ""
For x = 0 To CheckedListBox1.CheckedItems.Count - 1
s = s & "Checked Item " & CStr(x + 1) & " = " & _
CStr(CheckedListBox1.CheckedItems(x)) & ControlChars.CrLf
Next x
MessageBox.Show(s)
End If
BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
Container Parent
DataChanged New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataField
DataFormat
DataMember
DataSource
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
HelpContextI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
IntegralHeigh IntegralHeight
t
ItemData New implementation. For more information, see ItemData property cannot be upgraded.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
List Items
ListIndex SelectedIndex
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
MultiSelect SelectionMode
NewIndex New implementation. For more information, see NewIndex property cannot be upgraded.
OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMode
Style New implementation property. 0 – Standard maps to the CheckedListBox control, 1 – Checkbox maps to t
he CheckedListBox control.
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
WhatsThisHel New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
pID
Methods
Name Visual Basic 2005 Equivalent
AddItem Add
AddRange
Insert
Clear Clear
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
RemoveItem Remove
SetFocus Focus
ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
GotFocus Enter
LostFocus Leave
OLECompleteDra New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
g
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag
Validate Validating
Upgrade Notes
During upgrade, if the Style property of a Visual Basic 6.0 Listbox is set to 1 – Checkbox, it is upgraded to the
CheckedListBox control; otherwise, it is upgraded to the ListBox control.
See Also
Reference
ListBox Control Overview (Windows Forms)
ListBox Control Overview (Windows Forms)
CheckedListBox Control Overview (Windows Forms)
Visual Basic Concepts
VB
' Visual Basic 2005
For Each selectedItem As ListViewItem In ListView1.SelectedItems
MsgBox(selectedItem.Text)
Next
Arrange Alignment
BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
ColumnsHeader Columns
s
Container Parent
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HWnd Handle
Icons LargeImageList
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
ListItems Items
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMode
Picture BackgroundImage
PictureAlignme BackgroundImageTiled
nt
SelectedItem SelectedItems
SmallIcons SmallImageList
Sorted Sorting
SortOrder
SortKey ListViewItemSorter
TextBackground BackColor
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
WhatsThisHelpI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D
Methods
Name Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
FindItem FindItemWithText
GetFirstVisibl TopItem
e
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Refresh RedrawItems
SetFocus Focus
ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his
StartLabelEdi BeginEdit
t
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
GotFocus Enter
LostFocus Leave
OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag
Validate Validating
Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any ListView controls are upgraded to Windows Forms
ListView controls. Where properties, methods, and events have no equivalent or have differences in behavior, upgrade notes
or warnings are added to your code.
See Also
Other Resources
ListView Control (Windows Forms)
Visual Basic Concepts
BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.
ClipMode SkipLiterals
ClipText Text
Note
The Visual Basic 6.0 ClipText property excludes literals; in Visual Basic 2005 literals are included unless Ski
pLiterals is set to true.
Container Parent
DataBinding New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataChanged
DataField
DataFormat
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline
ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.
Format New implementation. Use formatting functions such as FormatNumber Function (Visual Basic) or
FormatDateTime Function (Visual Basic).
FormattedTex Text
t
Note
The Visual Basic 6.0 ClipText property excludes literals; in Visual Basic 2005 literals are included unless Ski
pLiterals is set to true.
HelpContextI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMod
e
PromptInclud TextMaskFormat
e
SelLength SelectionLength
SelStart SelectionStart
SelText SelectedText
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
WhatsThisHel New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
pID
Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
SetFocus Focus
ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his
DblClick DoubleClick
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
GotFocus Enter
LostFocus Leave
OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag
Validate Validating
ValidationError MaskInputRejected
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any MaskEdBox controls are upgraded to Windows
Forms MaskedTextBox controls, and properties, methods and events are upgraded to their equivalents. Where there may be
differences in behavior, upgrade comments are inserted into the code.
See Also
Tasks
Walkthrough: Working with the MaskedTextBox Control
MaskedTextBox Control Sample
How to: Bind Data to the MaskedTextBox Control
Other Resources
MaskedTextBox Control (Windows Forms)
Visual Basic Concepts
VB
' Visual Basic 2005
Private Sub MDIForm1_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load
Dim i As Integer = 0
For i = 0 To 4
Dim F As New FormChild
F.Text = "Form " & CStr(i + 1)
F.Show()
Next
End Sub
VB
' Visual Basic 2005
Private Sub CascadeToolStripMenuItem_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles CascadeToolStripMenuItem.Click
Me.LayoutMdi(MdiLayout.Cascade)
End Sub
VB
' Visual Basic 2005
Private Sub TileVerticleToolStripMenuItem_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles TileVerticalToolStripMenuItem.Click
Me.LayoutMdi(MdiLayout.TileVertical)
End Sub
VB
' Visual Basic 2005
Private Sub TileHorizontalToolStripMenuItem_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles TileHorizontalToolStripMenuItem.Click
Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub
AutoShowChildren property New implementation. For more information, see MDI form Show behavior has changed.
BackColor property New implementation. The background for an MDI form will always be the default (Control).
Picture property New implementation. MDI forms in Visual Basic 2005 cannot directly display pictures.
Upgrade Notes
When upgrading a MDI application from Visual Basic 6.0 to Visual Basic 2005, any MDIForm objects are upgraded to regular
forms and their IsMdiContainer property is set to true.
In Visual Basic 2005, the AutoShowChildren property no longer exists. To emulate the Visual Basic 6.0 behavior, a line of code
is added during upgrade to show each child form if AutoShowChildren is set to true in the original application.
See Also
Concepts
MDI for Visual Basic 6.0 Users
Form Object for Visual Basic 6.0 Users
Forms Tasks for Visual Basic 6.0 Users
Other Resources
Multiple-Document Interface (MDI) Applications
Visual Basic Concepts
VB
' Visual Basic 2005
' You must first add a ContextMenuStrip component to the form at design
' time and add Cut, Copy, and Paste menu items named
' CutContextMenuItem, CopyContextMenuItem, and PasteContextMenuItem.
Private Sub CutToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles CutToolStripMenuItem.Click
MsgBox("Cut")
End Sub
Private Sub CopyToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles CopyToolStripMenuItem.Click
MsgBox("Copy")
End Sub
Private Sub PasteToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles PasteToolStripMenuItem.Click
MsgBox("Paste")
End Sub
VB
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As _
System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
AddHandler CopyContextMenuItem.Click, _
AddressOf CopyToolStripMenuItem_Click
AddHandler PasteContextMenuItem.Click, _
AddressOf PasteToolStripMenuItem_Click
End If
End Sub
HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
Index New implementation. See the Index property of the ToolStripItemCollection class.
NegotiatePosition No equivalent. This property was only used for OLE linking and embedding which is no longer supported.
WindowList MdiWindowListItem
Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
PopupMenu New implementation. Use a ContextMenuStrip component.
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any calls to the PopupMenu method are not upgraded;
you must create context menus to replace these.
See Also
Reference
MenuStrip Control Overview (Windows Forms)
Concepts
Menu Handling for Visual Basic 6.0 Users
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
If RadioButton1.Checked = True Then
RadioButton2.Checked = True
Else
RadioButton1.Checked = True
End If
VB
' Visual Basic 2005
' The CheckChanged event fires each time the RadioButton's Checked
' value changes to either True or False.
Private Sub RadioButton1_CheckedChanged(ByVal sender As Object, ByVal _
e As System.EventArgs) Handles RadioButton1.CheckedChanged, _
RadioButton2.CheckedChanged
' Only execute if the Checked value is True.
If sender.Checked = True Then
MsgBox(sender.Name & " was clicked")
End If
End Sub
Appearance FlatStyle
BackColor BackColor
Note
For a list of constants, see Color Handling for Visual Basic 6.0 Users.
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.
Caption Text
Container Parent
DisabledPict New implementation. For more information, see Style Property for Visual Basic 6.0 Users.
ure
DownPicture
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethr
ough
FontUnderlin
e
ForeColor ForeColor
Note
For a list of constants, see Color Handling for Visual Basic 6.0 Users.
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.
HelpContextI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
MaskColor New implementation. For more information, see MaskColor for Visual Basic 6.0 Users
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointe Cursor
r
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDropMod New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
e
Picture Image
RightToLeft: RightToLeft
True Yes enumeration value
False No enumeration value
Style Appearance
Note
There are differences in how the Graphical style is handled in Visual Basic 2005. For more information, see
Style Property for Visual Basic 6.0 Users.
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
UseMaskColo New implementation. For more information, see MaskColor for Visual Basic 6.0 Users.
r
Value Checked
WhatsThisHe New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
lpID
Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
SetFocus Focus
ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his
DblClick DoubleClick
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
GotFocus Enter
LostFocus Leave
OLEComplete New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Drag
OLEDragDrop
OLEDragOver
OLEGiveFeed
back
OLESetData
OLEStartDrag
Validate Validating
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any OptionButton controls are upgraded to Windows
Forms RadioButton controls, and properties, methods and events are upgraded to their equivalent. Where there may be
differences in behavior, upgrade comments are inserted into the code.
See Also
Reference
RadioButton Control Overview (Windows Forms)
Visual Basic Concepts
In Visual Basic 2005, the AutoSize property is replaced by the SizeMode property; in addition to the Normal and AutoSize
modes, options are also available to center, stretch, or zoom the picture.
Graphics Properties and Methods
In Visual Basic 6.0, various graphics properties and methods can be used to draw lines, shapes, and text on top of a PictureBox
control.
In Visual Basic 2005, controls no longer have graphics properties or methods; you can still draw on top of a PictureBox
control using a T:System.Drawing.Graphics object. For more information, see Graphics for Visual Basic 6.0 Users.
Other Differences
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag-and-drop functionality, Help support, and more. For more information, see
Windows Forms Concepts for Visual Basic 6.0 Users.
Code Changes for the PictureBox Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Displaying a Picture
The following code demonstrates how to display a picture in a PictureBox control at run time.
VB
' Visual Basic 2005
PictureBox1.Image = System.Drawing.Bitmap.FromFile( _
My.Application.Info.DirectoryPath & "\somepicture.jpg")
VB
' Visual Basic 2005
If Not (PictureBox1.Image Is Nothing) Then
PictureBox1.Image.Dispose()
PictureBox1.Image = Nothing
End If
VB
' Visual Basic 2005
Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e _
As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
Dim radius As Integer = 20
Dim diameter As Integer = radius * 2
Dim x As Integer = (PictureBox1.Width / 2) - radius
Dim y As Integer = (PictureBox1.Height / 2) - radius
e.Graphics.DrawEllipse(Pens.Red, x, y, diameter, diameter)
End Sub
AutoRedraw New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
AutoSize SizeMode
BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
BorderStyle BorderStyle
Note
In Visual Basic 6.0, the default is Fixed Single; in Visual Basic 2005 the default is None.
ClipControls New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Container Parent
CurrentX New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
CurrentY
DataChanged New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataField
DataFormat
DataMember
DataSource
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
DrawMode New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
DrawStyle
DrawWidth
FillColor
FillStyle
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline
ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
HasDC New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
HDC
Height Height, Size
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HWnd Handle
Image New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Note
In Visual Basic 2005, the Image property is not a graphics property. It is the equivalent of the Visual Basic 6
.0 Picture property.
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
LinkItem No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkMode
LinkTimeOut
LinkTopic
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMode
Parent FindForm
Picture Image
ScaleHeight New implementation. For more information, see Coordinate System for Visual Basic 6.0 Users.
ScaleLeft
ScaleMode
ScaleTop
ScaleWidth
ToolTipText ToolTip component
For more information, see ToolTip Support for Visual Basic 6.0 Users.
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
WhatsThisHelp New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
ID
Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Circle New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Cls
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Line New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
LinkExecute No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkPoke
LinkRequest
LinkSend
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
PaintPicture New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Point
Print
PSet
Scale New implementation. For more information, see Coordinate System for Visual Basic 6.0 Users.
ScaleX
ScaleY
SetFocus Focus
ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his
TextHeight New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
TextWidth
DblClick DoubleClick
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
GotFocus Enter
KeyDown New implementation. The Visual Basic 2005 PictureBox control is not a container control and does not receive
keystrokes.
KeyPress
KeyUp
LinkClose No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkError
LinkNotify
LinkOpen
LostFocus Leave
OLEComplet New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
eDrag
OLEDragDro
p
OLEDragOve
r
OLEGiveFee
dback
OLESetData
OLEStartDra
g
Validate Validating
Upgrade Notes
During upgrade, PictureBox controls that contain controls are upgraded to Panel controls. For Visual Basic 6.0 PictureBox
controls that were upgraded to Panel controls, images assigned to the Picture property are mapped to the
BackgroundPicture property of the Panel control.
See Also
Reference
PictureBox Control Overview (Windows Forms)
Visual Basic Concepts
Page Property
In Visual Basic 6.0, the Page property returns a count of pages that have been printed since your application started or since
the last time the EndDoc statement was used on the Printer object. This property is often used to add a page number to each
page during printing.
In Visual Basic 2005, page numbers are not tracked; however, you can easily keep a count by setting a variable in the
BeginPrint event and incrementing it in the PrintPage event.
Port Property
In Visual Basic 6.0, the Port property returns the name of the port through which a document is sent to a printer.
In Visual Basic 2005, the Port property no longer exists; the PrintDialog and PrintPreviewDialog controls automatically
manage port information.
RightToLeft Property
In Visual Basic 6.0, the RightToLeft property determines how the Printer object will format output on a bi-directional
platform, such as Arabic Windows 95 or Hebrew Windows 95.
In Visual Basic 2005, the RightToLeft property is no longer necessary; the direction of printing is controlled by the localization
settings in later versions of Windows.
TrackDefault Property
In Visual Basic 6.0, the TrackDefault property determines whether a Printer object always points to the same printer, or
whether it changes the printer it points to if you change the default printer setting in the operating system's Control Panel.
Changing the TrackDefault property setting while a print job is in progress causes printing to halt immediately.
In Visual Basic 2005, the TrackDefault property no longer exists; the IsDefaultPrinter property of the PrinterSettings class
can be used to determine if a printer is the default, but printing is no longer halted if the default printer changes.
Zoom Property
In Visual Basic 6.0, the Zoom property determines the percentage by which printed output is to be scaled up or down. For
example, consider a letter-sized page printed with Zoom set to 50. This page contains as much data as a page of the size 17 by
22 inches because the printed text and graphics on the letter-sized page are scaled to one-half their original height and width.
In Visual Basic 2005, the Zoom property no longer exists; if a printer has zoom capabilities, settings are automatically exposed
in the Print dialog box. You can also use graphics methods to scale the output prior to assigning it to a PrintDocument
component.
Graphics Properties and Methods
In Visual Basic 6.0, various graphics properties and methods can be used to draw lines, shapes, and text on a Printer object.
In Visual Basic 2005, most objects no longer have their own graphics properties or methods; you can still draw lines, shapes,
and text by creating and using a Graphics object. For more information, see Graphics for Visual Basic 6.0 Users.
Code Changes for the Printer Object
Due to the considerable differences in printing models between Visual Basic 6.0 and Visual Basic 2005, a comparison of the
coding techniques is of little value. For an example of printing in Visual Basic 2005, see Printing Sample.
Printer Object Property and Method Equivalencies
The following tables list Visual Basic 6.0 properties and methods, along with their Visual Basic 2005 equivalents. Those
properties and methods that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map to the
System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Bas Visual Basic 2005 Equivalent
ic 6.0
ColorMod New implementation. The SupportsColor property of the PrinterSettings class can be used to determine the color c
e apabilities of a printer
CurrentX New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
CurrentY
DrawMod New implementation. For details, see Graphics for Visual Basic 6.0 Users.
e
DrawStyle
DrawWidt
h
DriverNa New implementation. No longer needed; printer drivers are managed by Windows.
me
FillColor New implementation. For details, see Graphics for Visual Basic 6.0 Users.
FillStyle
Font New implementation. For details, see Font Handling for Visual Basic 6.0 Users.
FontBold
FontCoun
t
FontItalic
FontNam
e
Fonts
FontSize
FontStrike
Thru
FontTrans
parent
FontUnde
rline
ForeColor New implementation. For details, see Color Handling for Visual Basic 6.0 Users.
hDC No longer necessary. An instance of a PrintDocument component is the equivalent of a device context.
Page New implementation. The current page number is not tracked; however, you can easily do this by setting a variable
in the BeginPrint event and incrementing it in the PrintPage event.
Port No longer necessary. The PrintPreviewDialog control automatically sets port information.
RightToLe No longer necessary. The direction of printing is controlled by the localization settings in Windows.
ft
ScaleHeig New implementation. For details, see Coordinate System for Visual Basic 6.0 Users.
ht
ScaleLeft
ScaleMod
e
ScaleTop
ScaleWidt
h
TrackDefa No direct equivalent. The IsDefaultPrinter property of the PrinterSettings class can be used to determine if a print
ult er is the default.
TwipsPer No longer necessary. Measurements in Visual Basic 2005 are always in pixels.
PixelX
TwipsPer
PixelY
Zoom No longer necessary. If the printer has zoom capabilities, settings are automatically exposed in the Print dialog bo
x.
Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Circle New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
EndDoc Print
KillDoc Cancel
Line New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
NewPage HasMorePages
PaintPicture New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
PSet
Scale New implementation. For details, see Coordinate System for Visual Basic 6.0 Users.
ScaleX
ScaleY
TextHeight New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
TextWidth
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any instances of the Printer object are not upgraded, and
an upgrade error is issued. You need to remove the code for the Printer object and re-implement printing using a
PrintDocument component.
See Also
Tasks
Printing Sample
Reference
PageSettings Class
PrinterSettings Class
Concepts
Printing Changes for Visual Basic 6.0 Users
Graphics for Visual Basic 6.0 Users
Other Resources
Windows Forms Print Support
Visual Basic Concepts
VB
' Visual Basic 2005
Dim i As Integer
Dim pkInstalledPrinters As String
For i = 0 To System.Drawing.Printing.PrinterSettings. _
InstalledPrinters.Count - 1
pkInstalledPrinters = System.Drawing.Printing.PrinterSettings. _
InstalledPrinters.Item(i)
ListBox1.Items.Add(pkInstalledPrinters)
Next
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any instances of the Printers collection are not upgraded
and an upgrade error is issued. You will need to remove the code for the Printers collection and modify your code so that it
uses a PrintDialog component.
See Also
Reference
PrintDialog Component Overview (Windows Forms)
PrinterSettings Class
Concepts
Printing Changes for Visual Basic 6.0 Users
Other Resources
Windows Forms Print Support
Visual Basic Concepts
Container Parent
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Height Height
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
Max Maximum
Min Minimum
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePoin Cursor
ter
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDropM New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
ode
Parent FindForm
Scrolling Style
Top Top
Note Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
Value Value
Note
In Visual Basic 6.0, when the Value is changed, the Change event is raised. In Visual Basic 2005, the Change e
vent is not raised; use the ValueChanged event instead.
WhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HelpID
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
ShowWhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag
Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any ProgressBar controls are upgraded to Windows Forms
ProgressBar controls. Where properties, methods, and events have no equivalent or have differences in behavior, upgrade
notes or warnings are added to your code.
See Also
Tasks
How to: Set the Value Displayed by the Windows Forms ProgressBar Control
Other Resources
ProgressBar Control (Windows Forms)
Visual Basic Concepts
VB
' Visual Basic 2005
' Make sure that HideSelection is set to False.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
Dim endChars() As Char = New Char() {".", "!", "?"}
Dim intEnd As Integer
intEnd = RichTextBox1.Find(endChars, RichTextBox1.SelectionStart)
RichTextBox1.SelectionLength = intEnd - RichTextBox1.SelectionStart
End Sub
AutoVerbMenu New implementation. For more information, see AutoVerbMenu property was not upgraded.
BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.
Container Parent
DataBindings New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataChanged
DataField
DataFormat
DataMember
DataSource
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline
ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.
HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMode
SelAlignment SelectionAlignment
SelBold SelectionFont
SelBullet SelectionBullet
SelCharOffset SelectionCharOffset
SelColor SelectionColor
SelFontName SelectionFont
SelFontSize SelectionFont
SelHangingInd SelectionHangingIndent
ent
SelIndent SelectionIndent
SelItalic SelectionFont
SelLength SelectionLength
SelProtected SelectionProtected
SelRightIndent SelectionRightIndent
SelRTF SelectedRtf
SelStart SelectionStart
SelStrikethru SelectionFont
SelTabCount SelectionTabs.Length
SelTabs SelectionTabs
SelText SelectedText
SelUnderline SelectionFont
TextRTF Rtf
ToolTipText ToolTip component
For more information, see ToolTip Support for Visual Basic 6.0 Users.
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
WhatsThisHelp New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
ID
Methods
Visual Basic 6. Visual Basic 2005 Equivalent
0
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
GetLineFromC GetLineFromCharIndex
har
LinkExecute No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkPoke
LinkRequest
LinkSend
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
SelPrint New implementation. For more information, see SelPrint property was not upgraded.
SetFocus Focus
ShowWhatsTh New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
is
Span No direct equivalent. Use the Find method with a characterSet argument.
Upto No direct equivalent. Use the Find method with a characterSet argument.
ZOrder BringToFront or SendToBack function
Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
Change TextChanged
DblClick DoubleClick
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
GotFocus Enter
LostFocus Leave
OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag
SelChange SelectionChanged
Validate Validating
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any RichTextBox controls are upgraded to Windows
Forms RichTextBox controls, and properties, methods and events are upgraded to their equivalents. Where there may be
differences in behavior, upgrade comments are inserted into the code.
See Also
Reference
RichTextBox Control Overview (Windows Forms)
Other Resources
RichTextBox Control (Windows Forms)
Visual Basic Concepts
ActiveControl Property
In Visual Basic 6.0, the ActiveControl property of the Screen object is used to determine the control that has focus. The
ActiveControl property can be used in a global capacity, such as in Screen.ActiveControl, where the active control on the
currently selected form is returned. If a specific form is referenced, for example, Form2.ActiveControl, ActiveControl specifies
the control that will have the focus if the referenced form is active.
In Visual Basic 2005, there is no longer a global ActiveControl property; each instance of a form has its own ActiveControl
property. When referencing a specific form, this property works just as it did in Visual Basic 6.0. To determine the active control
on the currently selected form, you must first iterate through the OpenForms collection and check the ContainsFocus
property to determine which form is active.
ActiveForm Property
In Visual Basic 6.0, the ActiveForm property of the Screen object is used to determine which form currently has the focus. If
an MDI parent form has the focus, ActiveForm returns the MDI child form that last had the focus.
In Visual Basic 2005, there is no longer a global ActiveForm property. To determine the active form, you must iterate through
the OpenForms collection and find the form with its ContainsFocus property set to True.
Visual Basic 2005 MDI parent forms (any forms with IsMDIContainer set to True) have an ActiveMDIChild property that can
be used to return the active child form without using the OpenForms collection.
MousePointer Property
In Visual Basic 6.0, the MousePointer property of the Screen object is used to change the appearance of the cursor; once set it
applies to all forms in the application.
In Visual Basic 2005, there is no longer a global MousePointer property; each form has a Cursor property that can be used to
change the appearance of the cursor for that form only.
TwipsPerPixel Properties
In Visual Basic 6.0, the TwipsPerPixelX and TwipsPerPixelY properties of the Screen object are used to convert screen
measurements from a logical twip (the standard unit of measurement in Visual Basic 6.0) to pixels.
In Visual Basic 2005, pixels are the standard unit of measurement; there is no longer any need for conversion.
Code Changes for the Screen Object
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Determining the Active Control
The following code demonstrates copying the text from the currently selected control on the currently selected form to the
Clipboard.
VB
' Visual Basic 2005
Dim i As Integer
For i = 0 To My.Application.OpenForms.Count - 1
If My.Application.OpenForms.Item(i).ContainsFocus Then
If TypeOf (My.Application.OpenForms.Item(i).ActiveControl) _
Is TextBox Then
My.Computer.Clipboard.SetText(My.Application.OpenForms. _
Item(i).ActiveControl.Text)
End If
End If
Next
VB
' Visual Basic 2005
Dim i As Integer
For i = 0 To My.Application.OpenForms.Count - 1
If My.Application.OpenForms.Item(i).ContainsFocus Then
My.Application.OpenForms.Item(i).Text = _
"This is the selected form"
End If
Next
VB
' Visual Basic 2005
Me.ActiveMdiChild.Text = "This is the selected child form"
FontCount New implementation. The behavior for enumerating fonts is different. For more information, see
Font Handling for Visual Basic 6.0 Users.
Fonts
Height My.Computer.Screen.Bounds.Height
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePoint System.Windows.Forms.Cursor
er
TwipsPerPix New implementation. In Visual Basic 2005, coordinates are in pixels; twips are not used as a unit of measuremen
elX t.
TwipsPerPix
elY
Width My.Computer.Screen.Bounds.Width
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any Screen object properties are upgraded to their
Visual Basic 2005 equivalent. Where there may be differences in behavior, upgrade comments are inserted into the code.
See Also
Reference
My.Application.OpenForms Property
My.Computer.Screen Property
Concepts
App Object for Visual Basic 6.0 Users
Font Handling for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
' Using a Label control
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
Dim Shape1 As New System.Windows.Forms.Label
' Show a solid red rectangle 14 pixels from the top left.
Shape1.Location = New System.Drawing.Point(14, 14)
Shape1.Size = New System.Drawing.Size(200, 100)
Shape1.BorderStyle = BorderStyle.None
Shape1.BackColor = System.Drawing.Color.Red
Shape1.Text = ""
Controls.Add(Shape1)
End Sub
VB
' Visual Basic 2005
' Using Graphics methods
Private Sub Form2_Paint(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a solid blue rectangle below the red rectangle.
e.Graphics.FillRectangle(Brushes.Blue, 14, 120, 200, 100)
End Sub
VB
' Visual Basic 2005
Private Sub Form3_Paint(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a 70 pixel diameter red circle.
e.Graphics.DrawEllipse(Pens.Red, 0, 0, 70, 70)
End Sub
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any Shape controls are replaced with Windows Forms
Label controls, with the BorderStyle property set to FixedSingle, and the BackColor, Width, and Height properties set to
match the original control.
Note
The Label controls may be added to the form in a different order than the original Shape controls. For overlapping shapes, it
may be necessary to call the BringToFront or SendToBack function to achieve the same visual layout.
Shape controls with the Shape property set to 2-Oval or 3-Circle cannot be upgraded and are replaced with a Label control
as a placeholder. You can replace the Shape control using the graphics functions built into the .NET Framework. For more
information, see Graphics for Visual Basic 6.0 Users.
See Also
Concepts
Graphics for Visual Basic 6.0 Users
Visual Basic Concepts
Container Parent
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Font Font
FontBold Note
FontItalic
Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStriket
hrough
FontUnderl
ine
Height Height
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePoin Cursor
ter
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDropM New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
ode
Panels ToolStripItemCollection
Parent FindForm
Value Value
Note
In Visual Basic 6.0, when the Value property is changed, the Change event is raised. In Visual Basic 2005, the C
hange event is not raised; use the ValueChanged event instead.
WhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HelpID
Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
ShowWhatsThi New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
s
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag
PanelClick Click
PanelDblClick DoubleClick
Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any StatusBar controls are upgraded to Windows Forms
StatusBar controls. Where properties, methods, and events have no equivalent or have differences in behavior, upgrade notes
or warnings are added to your code.
See Also
Tasks
StatusStrip Control Sample
Reference
StatusStrip
Visual Basic Concepts
VB
' Visual Basic 2005
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
TextBox1.Text = "Two of the peak human experiences are "
TextBox1.Text = TextBox1.Text & "good food and classical music."
End Sub
Private Sub Form1_Click(ByVal sender As Object, ByVal e As _
System.EventArgs) Handles Me.Click
Dim Search As String
Dim Where As String
' Get search string from user.
Search = InputBox("Enter text to be found:")
' Find string in text.
Where = InStr(TextBox1.Text, Search)
If Where Then
TextBox1.Focus()
TextBox1.SelectionStart = Where - 1
TextBox1.SelectionLength = Len(Search)
Else
MsgBox("String not found.")
End If
End Sub
VB
' Visual Basic 2005
Private Sub Form1_Load2(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
TextBox1.MaxLength = 5
End Sub
Private Sub SetText()
' Truncate the string to equal MaxLength.
TextBox1.Text = Strings.Left("Hello World", TextBox1.MaxLength)
End Sub
BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.
Container Parent
DataChanged New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataField
DataFormat
DataMember
DataSource
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline
ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.
HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
LinkItem New implementation. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkMode
LinkTimeOut
LinkTopic
Locked ReadOnly
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMode
SelLength SelectionLength
SelStart SelectionStart
SelText SelectedText
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
WhatsThisHelp New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
ID
Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
LinkExecute New implementation. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkPoke
LinkRequest
LinkSend
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
SetFocus Focus
ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his
DblClick DoubleClick
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
GotFocus Enter
LinkClose New implementation. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkError
LinkNotify
LinkOpen
LostFocus Leave
OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag
Validate Validating
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any TextBox controls are upgraded to Windows Forms
TextBox controls, and properties, methods and events are upgraded to their equivalents. Where there may be differences in
behavior, upgrade comments are inserted into the code.
See Also
Reference
TextBox Control Overview (Windows Forms)
Visual Basic Concepts
Interval Property
In Visual Basic 6.0, you can disable a Timer control by setting the Interval property to 0.
In Visual Basic 2005, the lower range for the Interval property is 1. If you set the interval to 0, it throws a run-time exception.
The Visual Basic 2005 Timer component uses the Enabled property to allow you to disable or enable it.
Code Changes for the Timer Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Starting and Stopping a Timer Control
The following code demonstrates how to enable and disable a Timer control at run time.
VB
' Visual Basic 2005
Public Sub TimerOn(ByRef Interval As Short)
If Interval > 0 Then
' Start the timer.
Timer1.Enabled = True
Else
' Stop the timer
Timer1.Enabled = False
End If
End Sub
Parent propert New implementation. The Timer is a component and cannot have a parent.
y
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any Timer controls are upgraded to Windows Forms
Timer components. If code is found that sets the Interval property to 0, an upgrade warning is added to your code.
See Also
Reference
Timer Component Overview (Windows Forms)
Visual Basic Concepts
AllowCusto New implementation. You must provide your own dialog box.
mize
Buttons ToolStripItemCollection
Container Parent
Controls ToolStripItemCollection
DataBindin New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
gs
DisabledIm New implementation. Use the Image property of the ToolStripButton object.
ageList
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Height Height
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
HelpContex New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
tID
HelpFile
HotImageLi New implementation. Use the Image property of the ToolStripButton object.
st
HWnd Handle
ImageList New implementation. Use the Image property of the ToolStripButton object.
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePoint Cursor
er
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDropMo New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
de
Parent FindForm
ShowTips ShowItemToolTips
Value Value
Note
In Visual Basic 6.0, when the Value is changed, the Change event is raised. In Visual Basic 2005, the Change e
vent is not raised; use the ValueChanged event instead.
WhatsThisH New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
elpID
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his
DblClick DoubleClick
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag
Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any ToolBar controls are upgraded to Windows Forms
ToolStrip controls. Where properties, methods, and events have no equivalent or have differences in behavior, upgrade notes
or warnings will be added to your code.
See Also
Reference
ToolStrip Control Overview (Windows Forms)
Other Resources
ToolStrip Control (Windows Forms)
Visual Basic Concepts
VB
' Visual Basic 2005
Private Sub TreeView1_AfterSelect(ByVal sender As Object, ByVal e As _
System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
TreeView1.SelectedNode.Expand()
End Sub
VB
' Visual Basic 2005
Dim nodX As TreeNode = New TreeNode("New Node")
TreeView1.SelectedNode.Nodes.Add(nodX)
TreeView Control Property, Method, and Event Equivalencies
The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map
to the System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic 6. Visual Basic 2005 Equivalent
0
Appearance New implementation. For more information, see
Appearance and BorderStyle Properties for Visual Basic 6.0 Users.
BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
Container Parent
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
HelpContextI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D
HWnd Handle
Indentation Indent
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
LineStyle ShowRootLines
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMode
Scroll Scrollable
Style New implementation property. 0 or Standard maps to the CheckedListBox control, 1 or Checkbox maps to t
he CheckedListBox control.
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
WhatsThisHel New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
pID
Methods
Name Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
SetFocus Focus
ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his
StartLabelEdi BeginEdit
t
DblClick DoubleClick
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
Expand AfterExpand
GotFocus Enter
LostFocus Leave
NodeCheck AfterCheck
NodeClick NodeMouseClick
OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag
Validate Validating
Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any TreeView controls are upgraded to Windows Forms
TreeView controls. Where properties, methods, and events have no equivalent or have differences in behavior, upgrade notes
or warnings are added to your code.
See Also
Tasks
How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)
How to: Iterate Through All Nodes of a Windows Forms TreeView Control
Other Resources
TreeView Control (Windows Forms)
Visual Basic Reference
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Height Height
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
HelpConte New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
xtID
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
LargeChan LargeChange
ge
Note
The default value in Visual Basic 6.0 is 1; in Visual Basic 2005 the default value is 10.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
Max Maximum
Note
The default value in Visual Basic 6.0 is 32767; in Visual Basic 2005, the default value is 100.
Min Minimum
Note
In Visual Basic 6.0, Min can be set to a value greater than Max; in Visual Basic 2005, this is not allowed.
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePoin Cursor
ter
For a list of constants, see MousePointer for Visual Basic 6.0 Users.
Parent FindForm
RightToLef RightToLeft
t:
Yes enumeration value
True
No enumeration value
False
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
Value Value
Note
In Visual Basic 6.0, when the Value is changed, the Change event is raised. In Visual Basic 2005, the Change e
vent is not raised; use the ValueChanged event instead.
WhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HelpID
Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
SetFocus Focus
ShowWhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
GotFocus Enter
LostFocus Leave
Scroll Scroll
Note
The behavior of the Change and Scroll events have changed in Visual Basic 2005. For more information, see
Code was changed from an event to a procedure.
Validate Validating
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any code in the Scroll event handler for the HScrollBar or
VScrollBar control is changed to a procedure due to a difference in the sequence of events. For more information, see
Code was changed from an event to a procedure.
See Also
Reference
HScrollBar and VScrollBar Controls Overview (Windows Forms)
Visual Basic Concepts
Application New implementation. This was a property of the Internet Explorer object.
Busy IsBusy
Container Parent
Document Document
Note
In Visual Basic 6.0, the Document property returns a string containing the name of an HTML document; in
Visual Basic 2005, it returns the HTML document itself.
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
FullName New implementation. This was a property of the Internet Explorer object.
HelpContextI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D
HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
LocationName New implementation. This was a property of the Internet Explorer object.
LocationURL
MenuBar New implementation. This was a property of the Internet Explorer object.
Offline IsOffline
Path New implementation. This was a property of the Internet Explorer object.
RegisterAsBro New implementation. This was a property of the Internet Explorer object.
wser
RegisterAsDro AllowWebBrowserDrop
pTarget
Resizable New implementation. This was a property of the Internet Explorer object.
Silent ScriptErrorsSuppressed
StatusBar New implementation. This was a property of the Internet Explorer object.
StatusText
TheaterMode New implementation. This was a property of the Internet Explorer object.
ToolBar New implementation. This was a property of the Internet Explorer object.
ToolTipText ToolTip component.
For more information, see ToolTip Support for Visual Basic 6.0 Users.
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
TopLevelCont New implementation. This was a property of the Internet Explorer object.
ainer
Type DocumentType
WhatsThisHel New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
pID
Methods
Visual Ba Visual Basic 2005 Equivalent
sic 6.0
ClientTo PointToClient
Window
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
ExecWB New implementation. This was a method of the Internet Explorer object.
GetPrope New implementation. This was a method of the Internet Explorer object.
rty
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
Navigate New implementation. This was a method of the Internet Explorer object.
2
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
PutPrope New implementation. This was a method of the Internet Explorer object.
rty
QuerySta New implementation. This was a method of the Internet Explorer object.
tusWB
Quit New implementation. This was a method of the Internet Explorer object.
Refresh Refresh
Refresh2 Note
The Visual Basic 6.0 Refresh2 method took a parameter specifying the refresh level; the Visual Basic 2005 Refres
h method has an optional parameter that can be used to specify the refresh level.
SetFocus Focus
ShowBro New implementation. This was a method of the Internet Explorer object.
wserBar
ShowWh New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
atsThis
ClientToHostWindow New implementation. This was an event of the Internet Explorer object.
CommandStateChanged CanGoBackChanged
CanGoForwardChanged
DblClick DoubleClick
DocumentComplete DocumentCompleted
DownloadBegin
DownloadComplete
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
GotFocus Enter
LostFocus Leave
NavigateComplete Navigated
NavigateComplete2
NavigateError New implementation. This was an event of the Internet Explorer object.
NewWindow NewWindow
NewWindow2
NewWindow3
OnFullScreen New implementation. This was an event of the Internet Explorer object.
OnMenuBar
OnQuit
OnStatusBar
OnTheaterMode
OnToolBar
OnVisible
PrintTemplateInstantiation New implementation. This was an event of the Internet Explorer object.
PrintTemplateTearDown
PrivacyImpactedStateChange
ProgressChange ProgressChanged
PropertyChange New implementation. This was an event of the Internet Explorer object.
SetSecureLockIcon EncryptionLevelChanged
StatusTextChange StatusTextChanged
TitleChange DocumentTitleChanged
UpdatePageStatus New implementation. This was an event of the Internet Explorer object.
Validate Validating
WindowClosing New implementation. This was an event of the Internet Explorer object.
WindowSetHeight
WindowSetLeft
WindowSetResizable
WindowSetTop
WindowSetWidth
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any WebBrowser controls are upgraded to Windows
Forms WebBrowser controls, and properties, methods and events are upgraded to their equivalents. Where there may be
differences in behavior, upgrade comments are inserted into the code.
See Also
Tasks
How to: Use the WebBrowser Control in the .NET Compact Framework
Reference
WebBrowser Control Overview
Other Resources
WebBrowser Control (Windows Forms)
Visual Basic Concepts
The Visual Basic 6.0 CommandButton, ListBox, and ComboBox controls support only the Appearance property.
The Visual Basic 2005 Button control has a FlatStyle property that is equivalent to the Appearance property. The ListBox
control can be made to appear flat by setting the BorderStyle property to FixedSingle. The ComboBox control never actually
supported a flat appearance in Visual Basic 6.0, so there is no equivalent.
Note
Visual Basic 6.0 forms also have a BorderStyle property that supports a different set of values. This is replaced by the
FormBorderStyle property in Visual Basic 2005.
VB
' Visual Basic 2005
' Give a TextBox a flat look with a single border.
TextBox1.BorderStyle = BorderStyle.None
' Give a TextBox a three-dimensional appearance.
TextBox2.BorderStyle = BorderStyle.Fixed3D
' Give a Button a flat look
Button1.FlatStyle = FlatStyle.Flat
' Give a ListBox a flat look
ListBox1.BorderStyle = BorderStyle.FixedSingle
Appearance = 1 – 3D Fixed3D
BorderStyle = 1 – Fixed Single
Upgrade Notes
When upgrading a Visual Basic 6.0 application using the Upgrade wizard, Frame controls can be upgraded to either Visual
Basic 2005 GroupBox or Panel controls. Appearance and BorderStyle mappings apply only to those Frame controls that are
upgraded to Panel controls; there is no BorderStyle property for GroupBox controls. For more information, see
Frame Control for Visual Basic 6.0 Users.
When upgrading ComboBox, CommandButton, and ListBox controls, the Appearance property is not mapped. If the
Appearance property is set in code, an upgrade warning will be added.
See Also
Concepts
ComboBox Control for Visual Basic 6.0 Users
CommandButton Control for Visual Basic 6.0 Users
Frame Control for Visual Basic 6.0 Users
Label Control for Visual Basic 6.0 Users
PictureBox Control for Visual Basic 6.0 Users
TextBox Control for Visual Basic 6.0 Users
User Controls for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
Private Sub Form1_Load()
' Raises the TextChanged event.
ComboBox1.Items.Add("A")
End Sub
Private Sub Form1_Click(ByVal sender As System.Object, ByVal _
e As System.EventArgs)
' Uses the SetItemString method from the VB6 compatibility library;
' there is no equivalent method in Visual Basic 2005.
' Raises the TextChanged event.
Microsoft.VisualBasic.Compatibility.VB6. _
SetItemString(ComboBox1, ComboBox1.Items.Count, "B")
End Sub
What to do next
Set a breakpoint in the TextChanged event procedure and then run your code to determine where it is raised. Modify
your code as necessary.
See Also
Concepts
ComboBox Control for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
' Measurements are in pixels.
Me.Size = New System.Drawing.Size(640, 480)
Moving a Control
The following example shows how to move a control at run time.
VB
' Visual Basic 2005
' Move and retain original size.
Button2.SetBounds(20, 10, 0, 0, BoundsSpecified.X Or BoundsSpecified.Y)
' Move and resize to 120 by 80 pixels.
Button1.SetBounds(0, 0, 120, 80)
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, the Height and Width properties of forms and controls
are automatically converted to pixels.
If the original application used the ScaleMode property, the upgrade tool assumes that the design-time setting for the
ScaleMode property was twips; if this is not the case, the conversion will be incorrect and must be fixed. For more
information, see ScaleMode is not supported.
See Also
Concepts
Form Object for Visual Basic 6.0 Users
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Control Property, Method, and Event Changes for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic .NET
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
MsgBox("The form is loading")
End Sub
Note
A common use of the Initialize event is to show a "splash" form to display information while the form is loading. Visual Basi
c 2005 applications have a SplashScreen property that can be used to automatically display a form during application startu
p. For more information, see How to: Specify a Splash Screen for an Application (Visual Basic).
Terminate Event
In Visual Basic 6.0, the Terminate event is used to execute code after a form is unloaded.
In Visual Basic 2005, the Terminate event is no longer supported. Termination code must be executed inside the Dispose
method, before the call to MyBase.Dispose().
Note
The Dispose method is called automatically for the main form in an application; you need to call it explicitly for any other for
m.
VB
' Visual Basic .NET
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
MsgBox("The form was terminated")
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
Unload Event
In Visual Basic 6.0, the Unload event has a Cancel argument; in Visual Basic 2005, it is replaced by the Closed event, which
does not have a Cancel argument. If you need to cancel during unloading, use the Closing event instead.
Mouse Events for MDI Forms
In Visual Basic 6.0, MDI Forms support mouse events. In Visual Basic 2005, because an MDI Form has no client area to receive
mouse events, the Click, MouseDown, MouseMove, and MouseUp events are no longer supported for MDI Forms..
See Also
Reference
Form Constructor
Form.Closing Event
Concepts
Form Object for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
Text1.MaxLength = 5
Text1.Text = "Longer than five"
MsgBox(Text1.Text) ' Displays "Longer than five".
What to do next
Review the design of your application to determine if the intended behavior was to always limit the text in the text box to
the length set in the MaxLength property.
If this was the intended behavior, find each occurrence of code that sets the Text property, and add code to
truncate the string, similar to the following example.
VB
' Old code
Text1.Text = SomeString
Text1.Text = SomeString
If it was not the intended behavior, leave the code alone. The user will still be limited by the MaxLength setting,
but you can programmatically assign strings that are longer than the MaxLength setting.
See Also
Concepts
TextBox Control for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
Private Sub TextBox1_MouseEnter(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles TextBox1.MouseEnter
TextBox1.Cursor = System.Windows.Forms.Cursors.WaitCursor
End Sub
VB
' Visual Basic 2005
Private Sub TextBox2_MouseEnter(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles TextBox2.MouseEnter
TextBox2.Cursor = New System.Windows.Forms.Cursor _
("C:\mypath\mycursor.cur")
End Sub
1 – vbArrow Arrow
2 – vbCrossHair Cross
3 – vbIBeam IBeam
5 – vbSizePointer SizeAll
6 – vbSizeNESW SizeNESW
7 – vbSizeNS SizeNS
8 – vbSizeNWSE SizeNWSE
9 – vbSizeWE SizeWE
10 – vbUpArrow UpArrow
11 – vbHourGlass WaitCursor
12 – vbNoDrop No
13 – vbArrowHourGlass AppStarting
14 – vbArrowQuestion Help
15 – vbSizeAll SizeAll
99 – vbCustom No equivalent — for more information, see Cannot set a custom MousePointer
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, the MousePointer property is replaced by the Cursor
property. Code that uses MousePointer constants is modified to use Visual Basic 2005 Cursors enumerations.
If the Visual Basic 6.0 application uses a custom MousePointer, the design-time setting or custom MousePointer code will
not be upgraded and a warning will be issued.
In addition, if the Visual Basic 6.0 application sets the MousePointer to the vbIconPointer constant at either design time or
run time, it will be replaced by the default cursor during upgrade.
See Also
Reference
Cannot set a custom MousePointer
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Control Property, Method, and Event Changes for Visual Basic 6.0 Users
Visual Basic Concepts
TopIndex Property and Scroll Event for Visual Basic 6.0 Users
Visual Basic 2005 no longer supports the TopIndex property for a ComboBox control or the Scroll event for ListBox or
ComboBox controls.
Conceptual Differences
TopIndex Property
In Visual Basic 6.0, the TopIndex property is used to return or set a value that specifies which item in a ComboBox or ListBox
control displayed in the topmost position. This property is commonly used to scroll the list without selecting an item.
In Visual Basic 2005, the ComboBox control no longer supports the TopIndex property. In most cases this should not present
a problem as setting the TopIndex property has no visible effect, unless the Style property is set to 1 - SimpleCombo. In this
case, you can emulate the ComboBox's SimpleCombo behavior by using a ListBox control and a TextBox control, as the
ListBox control still supports the TopIndex property.
Scroll Event
The Scroll event in Visual Basic 6.0 is used in conjunction with the TopIndex property to perform actions when the list is
scrolled. Visual Basic 2005 does not support the Scroll event; however, in most cases the SelectedIndexChanged event should
be a suitable replacement.
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any code that references the TopIndex property for a
ComboBox control or any code in the Scroll event procedure for a ComboBox or ListBox control is not upgraded. The
Upgrade wizard inserts a warning comment in the code; the code must be removed for the application to compile.
See Also
Reference
SelectedIndexChanged
SelectedIndexChanged
Concepts
ComboBox Control for Visual Basic 6.0 Users
ListBox Control for Visual Basic 6.0 Users
Visual Basic Concepts
Color Constants
In Visual Basic 6.0, constants were provided for system colors that could be used to map a color to the user's system
preferences. In Visual Basic 2005, the system colors are of type SystemColors.
BackColor and ForeColor Properties
In Visual Basic 6.0, the BackColor and ForeColor properties of a control had to be explicitly set at design time or at run time;
colors could not be inherited. In Visual Basic 2005, unless a color is explicitly set at design time or at run time, it will inherit the
color setting of its parent. For more information, see Color Behavior for Visual Basic 6.0 Users.
Palette and PaletteMode Properties
In Visual Basic 6.0, the Palette and PaletteMode properties of a form were used to control the set of colors to be used when
displaying images on a 256-color display. Visual Basic 2005 does not support the Palette or PaletteMode properties. For
more information, see Palettes for Visual Basic 6.0 Users.
MaskColor Property
The Visual Basic 6.0 MaskColor property no longer exists for the CheckBox, Button, and RadioButton controls. You can emulate
the MaskColor property by using the graphics methods. For more information, see MaskColor for Visual Basic 6.0 Users.
Code Changes for Color Handling
The following examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Setting a Color to a System Color
The following code sets the BackColor of a form to match the user-selected color for the active title bar.
' Visual Basic 6.0
Me.BackColor = vbActiveTitleBar
VB
' Visual Basic 2005
Me.BackColor = System.Drawing.SystemColors.ActiveCaption
VB
' Visual Basic 2005
TextBox1.BackColor = System.Drawing.ColorTranslator.FromOle(&HC0FFC0)
Constant Equivalencies
The following tables list Visual Basic 6.0 constants and their Visual Basic 2005 equivalents.
Color Constant Equivalents
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbBlack Black
vbRed Red
vbGreen Lime
vbYellow Yellow
vbBlue Blue
vbMagenta Magenta
vbCyan Cyan
vbWhite White
System Color Constant Equivalents
Visual Basic 6.0 Visual Basic 2005 Equivalent
vb3DDKShadow ControlDarkDark
vb3DFace Control
vb3DHighlight ControlLightLight
vb3DLight ControlLight
vb3DShadow ControlDark
vbActiveBorder ActiveBorder
vbActiveTitleBar ActiveCaption
vbActiveTitleBarText ActiveCaptionText
vbApplicationWorkspace AppWorkspace
vbButtonFace Control
vbButtonShadow ControlDark
vbButtonText ControlText
vbDesktop Desktop
vbGrayText GrayText
vbHighlight Highlight
vbHighlightText HighlightText
vbInactiveBorder InactiveBorder
vbInactiveCaptionText InactiveCaptionText
vbInactiveTitleBar InactiveCaption
vbInactiveTitleBarText InactiveCaptionText
vbInfoBackground Info
vbInfoText InfoText
vbMenuBar Menu
vbMenuText MenuText
vbScrollBars ScrollBar
vbTitleBarText ActiveCaptionText
vbWindowBackground Window
vbWindowFrame WindowFrame
vbWindowText WindowText
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005 using the upgrade wizard, colors are converted using the
FromOle method.
After upgrade you should search for any code that explicitly sets the BackColor or ForeColor property at run time. If it is being
set for a parent, explicitly set the color of the child controls at design time, otherwise the child controls will inherit the colors
from the parent.
Any code that used the Palette, PaletteMode, or MaskColor properties will need to be rewritten in Visual Basic 2005.
See Also
Concepts
Color Behavior for Visual Basic 6.0 Users
Palettes for Visual Basic 6.0 Users
MaskColor for Visual Basic 6.0 Users
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Visual Basic Concepts
After running the above code, Command1's BackColor is still the default (gray), and Command2's BackColor is black.
The following example shows the behavior in Visual Basic 2005. In Visual Basic 2005, CommandButton controls are replaced
by Button controls.
VB
' Visual Basic 2005
' Command1's BackColor is left at its default (gray).
' Command2's BackColor is explicitly set.
Command2.BackColor = System.Drawing.Color.Black
' Explicitly set the BackColor of the form.
Me.BackColor = System.Drawing.Color.Red
After running the above code, Command1's BackColor is red and Command2's BackColor is black. Because the Command1's
BackColor was not explicitly set, red is inherited from the form.
Note
This applies for any parent, not just for forms. If the Button was contained in a Panel control within the form, changing the
color of either the panel or the form would change the color of the Button.
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, the upgrade wizard has no way to determine if colors will
be inherited. After upgrading, search for any code that explicitly sets the BackColor or ForeColor property at run time. If it is
set for a parent, explicitly set the color of the child controls at design time.
See Also
Reference
Color Handling for Visual Basic 6.0 Users
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
' Assumes a picture has been assigned to the BackgroundImage property.
Dim g As New System.Drawing.Bitmap(Button1.BackgroundImage)
g.MakeTransparent(System.Drawing.Color.White)
Button1.BackgroundImage = g
Upgrade Notes
When upgrading an application from Visual Basic 6.0 to Visual Basic 2005, the upgrade wizard does not upgrade code that
uses the MaskColor property. Upgrade warnings will be inserted into your code. You will need to modify the code before
running the application.
See Also
Reference
Color Handling for Visual Basic 6.0 Users
MakeTransparent
Concepts
CheckBox Control for Visual Basic 6.0 Users
CommandButton Control for Visual Basic 6.0 Users
OptionButton Control for Visual Basic 6.0 Users
Visual Basic Concepts
Upgrade Notes
When upgrading a Visual Basic 6.0 application to Visual Basic 2005, any code that references the Palette or PaletteMode
property is not upgraded. The upgrade wizard inserts a warning in your code; you will need to delete the code that references
these properties.
See Also
Reference
Color Handling for Visual Basic 6.0 Users
Concepts
Form Object for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
Private Sub TextBoxes_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged, _
TextBox2.TextChanged, TextBox3.TextChanged
Select Case DirectCast(sender, TextBox).Name
Case TextBox1.Name
MsgBox("The text in the first TextBox has changed")
Case TextBox2.Name
MsgBox("The text in the second TextBox has changed")
Case TextBox3.Name
MsgBox("The text in the third TextBox has changed")
End Select
End Sub
Note
The event behavior is slightly different in Visual Basic 2005. The TextChanged event is raised when each control is initialized
(for example in the Form_Load event) as well as when the text is changed at run time. In Visual Basic 6.0, the Change event w
as only raised when the text was changed.
Because nested controls are not included in the ControlCollection collection, the HasChildren method is used to determine if
each control contains other controls, if so the ClearText function is called recursively.
' Visual Basic 6.0
Private Sub ClearText()
For i = 0 To Text1().UBound
Text1(i).Text = ""
Next
End Sub
VB
' Visual Basic 2005
Private Sub ClearText(ByVal container As Control)
Dim ctrl As Control
For Each ctrl In container.Controls
If TypeOf (ctrl) Is TextBox Then
ctrl.Text = ""
End If
If ctrl.HasChildren Then
ClearText(ctrl)
End If
Next
End Sub
VB
' Visual Basic 2005
' Declare a new TextBox.
Dim TextBox2 As New TextBox
' Set the location below the first TextBox
TextBox2.Left = TextBox1.Left
TextBox2.Top = TextBox1.Top + 30
' Add the TextBox to the form's Controls collection.
Me.Controls.Add(TextBox2)
AddHandler TextBox2.TextChanged, AddressOf TextChangedHandler
Upgrade Notes
When an application created with Visual Basic 6.0 is upgraded to Visual Basic 2005, any control arrays are upgraded to special
control-specific control array classes. These classes are contained in the Microsoft.VisualBasic.Compatibility.VB6
namespace and are used by the upgrade tools to emulate Visual Basic 6.0 control array behavior.
Although it is possible to use these control array classes in new Visual Basic 2005 development, we recommend that you use
the .NET Framework event model and functions instead.
See Also
Concepts
Events and Event Handling for Visual Basic 6.0 Users
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load
' Dropping must be enabled before the dragging occurs.
TextBox2.AllowDrop = True
End Sub
Private Sub TextBox1_MouseDown(ByVal sender As Object, ByVal e _
As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseDown
Upgrade Notes
Drag-and-drop code cannot automatically be upgraded to Visual Basic 2005; it must be rewritten using the new model. Any
drag-and-drop code is marked with upgrade warnings during the upgrade process.
See Also
Other Resources
Drag-and-Drop Operations and Clipboard Support
Visual Basic Concepts
Methods LinkExecute
LinkPoke
LinkRequest
LinkSend
Events LinkClose
LinkError
LinkExecute
LinkNotify
LinkOpen
VB
' Visual Basic 2005
' Create a new Font object Name and Size are required.
Dim f As New System.Drawing.Font("Arial", 10)
' Assign the font to the control
Label1.Font = f
' To set additional properties, you must create a new Font object.
Label1.Font = New System.Drawing.Font(Label1.Font, FontStyle.Bold Or FontStyle.Italic)
VB
' Visual Basic 2005
Dim ff As FontFamily
For Each ff In System.Drawing.FontFamily.Families
listBox1.Items.Add(ff.Name)
Next
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any font-handling code is modified to use the new Font
object.
Font inheritance in Visual Basic 2005 can cause unintended changes in the appearance of your application. You should check
your converted application for any code that explicitly sets a font at the form or container level and, if necessary, change the
font for any child controls that should not inherit that font.
During upgrade, raster fonts are converted to the default OpenType font, Microsoft Sans Serif. Formatting such as Bold or Italic
is not preserved. For more information, see Only OpenType and TrueType fonts are supported.
If your application contains code that enumerates fonts, raster fonts will not be enumerated in the upgraded application, and
font families are enumerated rather than individual character-set versions.
See Also
Reference
Font Class
FontFamily.Families Property
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Visual Basic Concepts
Determine the modifier Use the parameters provided by Compare the form class's ModifierKeys method against the modifier
key (ALT, SHIFT, CTRL) the mouse event handler. key value, found in the Keys enumeration. For more information, see
pressed during keyboar How to: Determine Which Modifier Key Was Pressed
d and mouse events.
Align or size controls b Click each control to align or siz Click each control to align or size. The first control selected is used to
ased on the location an e. The last control selected is us determine the location and size of all controls selected. For more info
d size of a single contro ed to determine the location an rmation, see How to: Align Multiple Controls on Windows Forms.
l. d size of all controls selected.
Change the name of a f Change the name specified in th Click the form's class file in Solution Explorer, and then change the
orm. e Name property of the form in Filename property in the Properties window.
the Properties window.
Change the run-time di Use the Form Layout window t With the form selected in the Windows Forms Designer, set the
splay position of a form o position the form, or set its St StartPosition property in the Properties window.
. artup property in the Propertie
s window.
Display a form as a dial In code, use the Show method a In code, use the ShowDialog method of the form. For more informati
og box. nd specify that the form be displ on, see How to: Display Dialog Boxes for Windows Forms.
ayed modally using the vbMod
al value.
Group or layer controls Layer the controls within the Fr Place the controls within a GroupBox control. Moving the group box
on a form. ame control. To move the contr moves the controls as well.
ols as a group, select them all.
Iterate through the cont Use a control array. Use the Controls Collection. For more information, see
rols on a form. Collections in Visual Basic.
See Also
Reference
Windows Forms Overview
Concepts
Form Object for Visual Basic 6.0 Users
Control Arrays for Visual Basic 6.0 Users
Other Resources
Windows Forms Concepts for Visual Basic 6.0 Users
Visual Basic Concepts
VB
' Visual Basic 2005
Private Sub Form1_Paint(ByVal sender As Object, ByVal e _
As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a solid black line 25 pixels from the top of the form.
e.Graphics.DrawLine(Pens.Black, 0, 25, Me.Width, 25)
End Sub
VB
' Visual Basic 2005
Private Sub Form1_Paint1(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a dotted black line 25 pixels from the top of the form.
Dim LPen As New System.Drawing.Pen(System.Drawing.Color.Black)
LPen.DashStyle = Drawing2D.DashStyle.Dot
e.Graphics.DrawLine(LPen, 0, 25, Me.Width, 25)
End Sub
VB
' Visual Basic 2005
Private Sub Form1_Paint2(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a line with a thickness of 1 pixel.
Dim TPen As New System.Drawing.Pen(System.Drawing.Color.Black, 1)
e.Graphics.DrawLine(TPen, 0, 25, Me.Width, 25)
' Draw a line with a thickness of 5 pixels.
TPen.Width = 5
e.Graphics.DrawLine(TPen, 0, 50, Me.Width, 50)
' Draw a line with a thickness of 10 pixels.
TPen.Width = 10
e.Graphics.DrawLine(TPen, 0, 75, Me.Width, 75)
End Sub
Drawing a Circle
The following code demonstrates drawing a circle on a form at run time. In the Visual Basic 6.0 example, the Circle method is
used; it takes the X and Y coordinates of the center point, the radius, and, optionally, a color, as arguments. The Visual Basic
2005 example uses the DrawEllipse method, which takes a Pen object, the X and Y coordinates of the upper-left corner of the
bounding rectangle, and the width and height as arguments.
Note
In Visual Basic 6.0, the default unit of measurement is twips; in Visual Basic 2005, it is pixels.
VB
' Visual Basic 2005
Private Sub Form1_Paint3(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
VB
' Visual Basic 2005
Private Sub Form1_Paint4(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
VB
' Visual Basic 2005
Private Sub Form1_Paint5(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
VB
' Visual Basic 2005
Private Sub Form1_Paint6(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
VB
' Visual Basic 2005
Private Sub Form1_Paint7(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
VB
' Visual Basic 2005
Private Sub Form1_Paint8(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
VB
' Visual Basic 2005
Private Sub Form1_Paint9(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
CurrentX property The x parameter of various graphics methods. For example, DrawRectangle(pen, x, y, width, hei
ght)
CurrentY property The y parameter of various graphics methods. For example, DrawRectangle (pen, x, y, width,
height)
HasDC property New implementation. Device contexts are no longer necessary with GDI+.
HDC property New implementation. Device contexts are no longer necessary with GDI+.
Upgrade Notes
When an application is upgraded from Visual Basic 6.0 to Visual Basic 2005, graphics methods are not upgraded, and warnings
are inserted into the code. Due to the considerable differences between GDI and GDI+, any existing graphics code will need to
be rewritten.
See Also
Tasks
Custom Drawing User Control Sample
Other Resources
Graphics Overview (Windows Forms)
Getting Started with Graphics Programming
About GDI+ Managed Code
Using Managed Graphics Classes
Visual Basic Concepts
VB
' Visual Basic 2005
' Assumes a HelpProvider component has been added to the form.
If RadioButton1.Checked = True Then
HelpProvider1.HelpNamespace = My.Application.Info.DirectoryPath & _
"\EnglishHelp.chm"
Else
HelpProvider1.HelpNamespace = My.Application.Info.DirectoryPath & _
"\FrenchHelp.chm"
End If
Displaying a ToolTip
The following demonstrates code to display a ToolTip.
' Visual Basic 6.0
Private Sub Text1_Change()
Text1.ToolTipText = "The text has changed"
End Sub
VB
' Visual Basic 2005
' Assumes a ToolTip component has been added to the form.
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
ToolTip1.SetToolTip(TextBox1, "The text has changed")
End Sub
ToolTipText property SetToolTip method. For more information, see ToolTip Support for Visual Basic 6.0 Users.
Upgrade Notes
When a Visual Basic 6.0 project is upgraded using the upgrade wizard in Visual Basic 2005, any Help-related properties or code
will not be upgraded. You need to reimplement Help support for your application after upgrading. If your Help file was written
using HTML Help, you can reuse the Help file; if it was written using Windows Help it will need to be rewritten.
See Also
Tasks
How to: Provide Help in a Windows Application
How to: Display Pop-up Help
Concepts
ToolTip Support for Visual Basic 6.0 Users
Other Resources
Integrating User Help in Windows Forms
Visual Basic Concepts
VB
' Visual Basic 2005
ToolTip1.SetToolTip(Button1, "Save changes")
VB
' Visual Basic 2005
' Hide a single ToolTip.
ToolTip1.SetToolTip(Button1, "")
' Hide all ToolTips.
ToolTip1.Active = False
Upgrade Notes
When a Visual Basic 6.0 is upgraded to Visual Basic 2005, any references to the ToolTipText property at either design time or
run time are not upgraded, and comments are inserted into your code. A ToolTip component named ToolTip1 is added to
your form; you will need to hook up your ToolTips by either setting the ToolTip on ToolTip1 property at design time or
calling the SetToolTip method at run time.
If the Visual Basic 6.0 application uses Windows API calls to customize ToolTips, you should modify your code to take
advantage of the customization features of the ToolTip component.
See Also
Reference
ToolTip Component Overview (Windows Forms)
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Visual Basic Concepts
VB
'Visual Basic 2005
Label1.Text = My.Application.Info.Version.ToString()
Major My.Application.AppInfo.Version.Major
Minor My.Application.AppInfo.Version.Minor
Revision My.Application.AppInfo.Version.Revision
Note
In Visual Basic 6.0, Revision is the fourth part of the version number; in Visual Basic 2005, it is the third par
t.
Upgrade Notes
When an application is upgraded from Visual Basic 6.0, only the Major and Minor properties are upgraded; Visual Basic 2005
assigns new values for the Revision and Build properties.
See Also
Concepts
App Object for Visual Basic 6.0 Users
Visual Basic Concepts
How to: Add Visual Basic 6.0 File System Controls to Your
Application
We recommend that you use the OpenFileDialog and SaveFileDialog components to provide access to the file system;
however, if you find it necessary to create your own file dialog boxes, Visual Basic 2005 provides DirListBox, DriveListBox,
and FileListBox controls as part of the Microsoft Visual Basic Compatibility Runtime library.
You can add a DirListBox, DriveListBox, or FileListBox to a Windows Application project using the following procedures.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
See Also
Reference
OpenFileDialog Component Overview (Windows Forms)
SaveFileDialog Component Overview (Windows Forms)
Concepts
DirListBox Control for Visual Basic 6.0 Users
DriveListBox Control for Visual Basic 6.0 Users
FileListBox Control for Visual Basic 6.0 Users
Visual Basic Concepts
See Also
Concepts
Debugging Your Visual Basic Application
Integrated Development Environment for Visual Basic 6.0 Users
Other Resources
Help for Visual Basic 6.0 Users
Visual Basic Concepts
Visual Basic 2005 provides two different strategies for deploying Windows-based applications: publishing an application using
ClickOnce technologies, or deploying it by means of traditional Setup using Windows Installer technologies
With ClickOnce deployment, you publish the application to a centralized location (usually a Web server or file share), and the
user installs or runs the application from that location. ClickOnce applications can be self-updating—when you publish an
update to the application, end users can automatically download the update— ensuring that everyone is using the same
version. For more information, see ClickOnce Deployment.
With Windows Installer deployment, you use a Setup and Deployment project to package the application in a Setup.exe file and
distribute that file to users, who run the Setup.exe file to install the application. For more information, see
Windows Installer Deployment.
Note
Visual Basic Express Edition only supports ClickOnce deployment.
In This Section
Align Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Align constants and their Visual Basic 2005 equivalents.
Alignment Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Alignment constants and their Visual Basic 2005 equivalents.
Arrange Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Arrange constants and their Visual Basic 2005 equivalents.
BorderStyle Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 BorderStyle constants and their Visual Basic 2005 equivalents.
CallType Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 CallType constants and their Visual Basic 2005 equivalents.
CheckBox Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 CheckBox constants and their Visual Basic 2005 equivalents.
Color Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Color constants and their Visual Basic 2005 equivalents.
CompareMethod Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 CompareMethod constants and their Visual Basic 2005 equivalents.
Date Format Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 DateFormat constants and their Visual Basic 2005 equivalents.
DayOfWeek Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 DayOfWeek constants and their Visual Basic 2005 equivalents.
File Attribute Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 FileAttribute constants and their Visual Basic 2005 equivalents.
IMEMode Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 IMEMode constants and their Visual Basic 2005 equivalents.
Key Code Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Key Code constants and their Visual Basic 2005 equivalents.
Mouse Pointer Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Mouse Pointer constants and their Visual Basic 2005 equivalents.
MsgBox Result Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 MsgBox Result constants and their Visual Basic 2005 equivalents.
MsgBox Style Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 MsgBox Style constants and their Visual Basic 2005 equivalents.
MultiSelect Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 MultiSelect constants and their Visual Basic 2005 equivalents.
OLEDropEffect Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 OLEDropEffect constants and their Visual Basic 2005 equivalents.
ScrollBar Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 ScrollBar constants and their Visual Basic 2005 equivalents.
StartUpPosition Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 StartUpPosition constants and their Visual Basic 2005 equivalents.
StrConv Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 StrConv constants and their Visual Basic 2005 equivalents.
Style Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Style constants and their Visual Basic 2005 equivalents.
System Color Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 System Color constants and their Visual Basic 2005 equivalents.
TriState Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 TriState constants and their Visual Basic 2005 equivalents.
Variant Type Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Variant Type constants and their Visual Basic 2005 equivalents.
VarType Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 VarType constants and their Visual Basic 2005 equivalents.
VBA Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Visual Basic for Applications constants and their Visual Basic 2005 equivalents.
WeekOfYear Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 WeekOfYear constants and their Visual Basic 2005 equivalents.
WindowState Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 WindowState constants and their Visual Basic 2005 equivalents.
WindowStyle Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Window Style constants and their Visual Basic 2005 equivalents.
Related Sections
Constants and Enumerations in Visual Basic
Introduces Visual Basic 2005 enumerations.
Windows Forms Controls for Visual Basic 6.0 Users
Provides links to topics describing the differences between Visual Basic 6.0 and Windows Forms controls and objects.
Language Changes for Visual Basic 6.0 Users
Describes changes to the Visual Basic language.
Visual Basic Reference
vbGet CallType.Get
vbSet CallType.Set
vbLet CallType.Let
See Also
Reference
CallByName Function
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbRed Red
vbGreen Lime
vbYellow Yellow
vbBlue Blue
vbMagenta Magenta
vbCyan Cyan
vbWhite White
See Also
Reference
Color Handling for Visual Basic 6.0 Users
System Color Constants for Visual Basic 6.0 Users
Concepts
Color Behavior for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations (Visual Basic)
Visual Basic Reference
vbTextCompare CompareMethod.Text
vbDatabaseCompare No equivalent
See Also
Reference
CompareMethod Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbLongDate DateFormat.LongDate
vbShortDate DateFormat.ShortDate
vbLongTime DateFormat.LongTime
vbShortTime DateFormat.ShortTime
See Also
Reference
DateFormat Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbSunday FirstDayOfWeek.Sunday
vbMonday FirstDayOfWeek.Monday
vbTuesday FirstDayOfWeek.Tuesday
vbWednesday FirstDayOfWeek.Wednesday
vbThursday FirstDayOfWeek.Thursday
vbFriday FirstDayOfWeek.Friday
vbSaturday FirstDayOfWeek.Saturday
See Also
Reference
FirstDayOfWeek Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbReadOnly FileAttribute.ReadOnly
vbHidden FileAttribute.Hidden
vbSystem FileAttribute.System
vbVolume FileAttribute.Volume
vbDirectory FileAttribute.Directory
vbArchive FileAttribute.Archive
vbAlias No equivalent
See Also
Reference
FileAttribute Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbIMEModeOn (1) On
vbIMEOn (1) On
See Also
Concepts
Form Object for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbKeyUp (38) Up
VbKeyB (66) B
VbKeyC (67) C
VbKeyD (68) D
VbKeyE (69) E
VbKeyF (70) F
VbKeyG (71) G
VbKeyH (72) H
VbKeyI (73) I
VbKeyJ (74) J
VbKeyK (75) K
VbKeyL( 76) L
vbKeyM (77) M
VbKeyN (78) N
VbKeyO (79) O
VbKeyP( 80) P
VbKeyQ (81) Q
VbKeyR (82) R
VbKeyS (83) S
VbKeyT (84) T
VbKeyU (85) U
VbKeyV (86) V
VbKeyW (87) W
VbKeyX (88) X
VbKeyY (89) Y
VbKeyZ (90) Z
Numeric Key Constants
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbKey0 (48) D0
vbKey1 (49) D1
vbKey2 (50) D2
vbKey3 (51) D3
vbKey4 (52) D4
vbKey5 (53) D5
vbKey6 (54) D6
vbKey7 (55) D7
vbKey8 (56) D8
vbKey9 (57) D9
Numeric Keypad Key Constants
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbKeyNumpad0 (96) NumPad0
vbKeyF2 (113) F2
vbKeyF3 (114) F3
vbKeyF4 (115) F4
vbKeyF5 (116) F5
vbKeyF6 (117) F6
vbKeyF7 (118) F7
vbKeyF8 (119) F8
vbKeyF9 (120) F9
VbNoDrop (12) No
VbCustom (99) Cannot set a custom MousePointer No equivalent. For details, see Cannot set a custom MousePointer
See Also
Concepts
MousePointer for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbCancel MsgBoxResult.Cancel
vbAbort MsgBoxResult.Abort
vbRetry MsgBoxResult.Retry
vbIgnore MsgBoxResult.Ignore
vbYes MsgBoxResult.Yes
vbNo MsgBoxResult.No
See Also
Reference
MsgBoxResult Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbOKCancel MsgBoxStyle.OKCancel
vbAbortRetryIgnore MsgBoxStyle.AbortRetryIgnore
vbYesNoCancel MsgBoxStyle.YesNoCancel
vbYesNo MsgBoxStyle.YesNo
vbRetryCancel MsgBoxStyle.RetryCancel
vbCritical MsgBoxStyle.Critical
vbQuestion MsgBoxStyle.Question
vbExclamation MsgBoxStyle.Exclamation
vbInformation MsgBoxStyle.Information
vbDefaultButton1 MsgBoxStyle.DefaultButton1
vbDefaultButton2 MsgBoxStyle.DefaultButton2
vbDefaultButton3 MsgBoxStyle.DefaultButton3
vbDefaultButton4 No equivalent
vbApplicationModal MsgBoxStyle.ApplicationModal
vbSystemModal MsgBoxStyle.SystemModal
vbMsgBoxHelpButton MsgBoxStyle.MsgBoxHelp
vbMsgBoxRight MsgBoxStyle.MsgBoxRight
vbMsgBoxRtlReading MsgBoxStyle.MsgBoxRtlReading
vbMsgBoxSetForeground MsgBoxStyle.MsgBoxSetForeground
See Also
Reference
MsgBoxStyle Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbLowerCase VbStrConv.LowerCase
vbProperCase VbStrConv.ProperCase
vbWide VbStrConv.Wide
vbNarrow VbStrConv.Narrow
vbKatakana VbStrConv.Katakana
vbHiragana VbStrConv.Hiragana
vbUnicode No equivalent constant. You can achieve the same functionality by using the Convert method.
vbFromUnicode No equivalent
See Also
Reference
VbStrConv Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
See Also
Concepts
ComboBox Control for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vb3DFace Control
vb3DHighlight ControlLightLight
vb3DLight ControlLight
vb3DShadow ControlDark
vbActiveBorder ActiveBorder
vbActiveTitleBar ActiveCaption
vbActiveTitleBarText ActiveCaptionText
vbApplicationWorkspace AppWorkspace
vbButtonFace Control
vbButtonShadow ControlDark
vbButtonText ControlText
vbDesktop Desktop
vbGrayText GrayText
vbHighlight Highlight
vbHighlightText HighlightText
vbInactiveBorder InactiveBorder
vbInactiveCaptionText InactiveCaptionText
vbInactiveTitleBar InactiveCaption
vbInactiveTitleBarText InactiveCaptionText
vbInfoBackground Info
vbInfoText InfoText
vbMenuBar Menu
vbMenuText MenuText
vbScrollBars Scrollbar
vbTitleBarText ActiveCaptionText
vbWindowBackground Window
vbWindowFrame WindowFrame
vbWindowText WindowText
See Also
Reference
Color Handling for Visual Basic 6.0 Users
Color Constants for Visual Basic 6.0 Users
Concepts
Color Behavior for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbFalse TriState.False
vbUseDefault TriState.UseDefault
See Also
Reference
TriState Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbVNull VariantType.Null
vbVInteger VariantType.Short
vbVLong VariantType.Integer
vbVSingle VariantType.Single
vbVDouble VariantType.Double
vbVCurrency VariantType.Decimal
vbVDate VariantType.Date
vbVString VariantType.String
See Also
Reference
VariantType Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations (Visual Basic)
Visual Basic Reference
vbNull VariantType.Null
vbInteger VariantType.Short
vbLong VariantType.Integer
vbSingle VariantType.Single
vbDouble VariantType.Double
vbCurrency VariantType.Decimal
vbDate VariantType.Date
vbString VariantType.String
vbObject VariantType.Object
vbError VariantType.Error
vbBoolean VariantType.Boolean
vbVariant VariantType.Variant
vbDataObject VariantType.DataObject
vbDecimal VariantType.Decimal
vbByte VariantType.Byte
vbUserDefinedType VariantType.UserDefinedType
vbArray VariantType.Array
See Also
Reference
VariantType Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbCr ControlChars.Cr
vbCrLf ControlChars.CrLf
vbFormFeed ControlChars.FormFeed
vbLf ControlChars.Lf
vbNewLine ControlChars.NewLine
vbNullChar ControlChars.NullChar
vbObjectError vbObjectError
vbTab ControlChars.Tab
See Also
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
VbFirstJan1 FirstWeekOfYear.Jan1
vbFirstFourDays FirstWeekOfYear.FirstFourDays
vbFirstFullWeek FirstWeekOfYear.FirstFullWeek
See Also
Reference
FirstWeekOfYear Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference
vbNormalFocus AppWinStyle.NormalFocus
vbMinimizedFocus AppWinStyle.MinimizedFocus
vbMaximizedFocus AppWinStyle.MaximizedFocus
vbNormalNoFocus AppWinStyle.NormalNoFocus
vbMinimizedNoFocus AppWinStyle.MinimizedNoFocus
See Also
Reference
AppWinStyle Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Concepts
See Also
Concepts
Introduction to the .NET Framework Class Library in Visual Studio
Visual Basic Concepts
Support for Act You can now upgrade many Visual Basic 6.0 ActiveX controls to their Visual Basic 2005 equivalents. Support is
iveX control up included for these controls: WebBrowser, ToolBar, ImageList, TreeView, ListView, RichTextBox, ProgressBar,
grades StatusBar, CommonDialog, and MaskedTextBox.
Enhancements You will find a number of enhancements to code upgrades in Visual Basic 2005, including:
to code upgrad
es Upgrade code that uses string-based-keys in forms control collections.
Upgrade code that changes the key value in the KeyPress event.
Other enhancements let you:
Upgrade the Visual Basic 6.0 App object to the new My.Application object.
Upgrade the UnloadMode parameter of QueryUnload event to the ClosingReason argument of the For
mClosing event.
Upgrade forms to use the new Partial Type format.
Upgrade Visual Basic 6.0 default instances to use support for default instances provided in Visual Basic 2
005.
Upgrade the Forms collection to the Visual Basic 2005 System.Windows.Forms collection.
Upgrade Visual Basic 6.0 Clipboard object to the new My.Computer.Clipboard object.
Upgrade the LoadResString, LoadResData, and LoadResPicture methods to the new My.Resources
object.
See Also
Concepts
What's New in the Visual Basic Language
Visual Basic Concepts
In most cases you will want to upgrade your Visual Basic 6.0 applications to Visual Basic 2005 so that you can take
advantage of the benefits of the .NET Framework as you continue development. There are, however, situations where you
may wish to continue development in Visual Basic 6.0 rather than upgrading. Some of the factors in deciding to upgrade
an application include features that aren't supported in Visual Basic 2005, and the amount of rework needed due to
incompatibility and architectural considerations.
Unsupported Features
The following features from Visual Basic 6.0 are no longer supported in Visual Basic 2005. For more information, see
Preparing a Visual Basic 6.0 Application for Upgrading.
OLE Container Control There is no equivalent in Visual Basic 2005. Applications that depend on this control should be
left in Visual Basic 6.0.
Dynamic Data Exchange (DDE) DDE methods are no longer supported. Applications that depend on DDE should either
be revised to use another method of inter-application communication or left in Visual Basic 6.0.
DAO or RDO Data Binding Data binding to a DAO or RDO data source isn't supported in Visual Basic 2005; the Data
control and the RemoteData control have no equivalent. DAO and RDO can only be accessed using code. Applications
that rely on DAO or RDO data binding should either be updated to use ADO or left in Visual Basic 6.0.
Visual Basic 5.0 Controls Visual Basic 6.0 included the Visual Basic 5.0 versions of the Windows Common controls and
the Data-Bound Grid control. These controls are incompatible with Visual Basic 2005. Applications that rely on these
controls should either be updated to use the 6.0 versions or left in Visual Basic 6.0.
DHTML Applications There is no equivalent in Visual Basic 2005. However, DHTML applications can interoperate with
Visual Basic 2005 technologies.
ActiveX Documents There is no equivalent in Visual Basic 2005. However, DHTML applications can interoperate with
Visual Basic 2005 technologies. ActiveX documents should either be rewritten as user controls or left in Visual Basic 6.0.
Property Pages There is no equivalent in Visual Basic 2005. If your application depends heavily on property pages, it
should be left in Visual Basic 6.0.
Determining the Amount of Rework Required
Due to the many differences between Visual Basic 6.0 and Visual Basic 2005, most applications will require some rework for
items that can't be mapped directly or are otherwise incompatible. The amount of rework required depends on a number of
factors, including the type of application, features, and the language constructs used.
The easiest way to determine the amount of rework required is to run the Upgrade Wizard and view the list of issues in the
Upgrade Report. When an application is upgraded a new copy is created; the original application is left intact. If, after viewing
the report, you decide not to upgrade, you can simply delete the new project and continue development in Visual Basic 6.0.
The following are additional considerations that may factor into your upgrade decision.
Single-tier Database Applications Because data binding to DAO isn't supported, simple applications using controls
bound directly to a local database (such as one created with Microsoft Access) may require a significant amount of
rework.
Visual Basic Add-ins Because Visual Basic 2005 uses the Visual Studio integrated development environment, the object
model for extensibility is significantly different than that of Visual Basic 6.0. Add-ins will require a considerable amount of
rework.
Games Applications relying on specific performance characteristics of Visual Basic 6.0, such as arcade games, will
require rework because Visual Basic 2005 has different performance characteristics.
Graphics There is no support for the graphics methods of forms or for the shape and line controls. Applications that use
these features extensively to draw on forms will require considerable rework.
Drag-and-Drop Functionality The models for drag-and-drop functionality are significantly different; any code
performing drag-and-drop actions will need to be rewritten.
Variants When an application is upgraded, the Variant data type is converted to Object. If an application is heavily
dependent on variants, this conversion can introduce some subtle differences in the application's behavior. For example,
in Visual Basic 6.0 the expression IsObject(Variant) evaluates to false; in Visual Basic 2005 it changes to
IsObject(Object), which evaluates to true.
Windows APIs Due to language changes, many calls to Windows APIs will need to be revised or replaced with .NET
Framework functions.
See Also
Concepts
Preparing a Visual Basic 6.0 Application for Upgrading
Why Upgrading Is Necessary
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts
Dim o As Object
Set o = Me.Label1
o.Caption = "SomeText"
In Visual Basic 2005, the Caption property of a label control is replaced by the Text property. When your code is upgraded, all
instances of the Caption property are changed to Text, but because a late-bound object is typeless, Visual Basic cannot detect
what type of object it is, or if any properties should be translated. In such cases, you will need to change the code yourself after
upgrading.
If you rewrite the code using early-bound objects, it will be upgraded automatically:
Dim o As Label
Set o = Me.Label1
o.Text = "SomeText"
Where possible, you should declare variables of the appropriate object type rather than simply declaring them as the Object
data type.
In the cases where you do use Object and Variant variables in your Visual Basic 6.0 code, we recommend you use explicit
conversions when you assign the variables, perform operations on the variables, or pass the variables to a function. For
example, the intention of the '+' operation in the following code is unclear:
The above example may result in a run-time error in Visual Basic 2005. Rewriting the final line to use explicit conversions
ensures the code will work:
Visual Basic 2005 supports overloading functions based on parameter type. For example, the Environ function now has two
forms:
Visual Basic 2005 determines which function to call based on the parameter type. If you pass an integer to Environ(), the
integer version is called; if you pass a string, then the string version is called. Code that passes a Variant or Object data type
to an overloaded function may cause a compiler error or run-time error. Using an explicit conversion, as in the following
example, will mean your code will work as intended after it is upgraded to Visual Basic 2005:
Dim a As String
Dim v As Variant
v = "Path"
'GOOD: explicit conversion
a = Environ(CStr(v))
Using explicit conversions of late-bound objects is good coding practice. It makes the intention of the code easy to determine,
and makes it easier for you to upgrade your project to Visual Basic 2005.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts
The .NET Framework provides the ToOADate and FromOADate functions to convert between doubles and dates. However,
when your project is upgraded to Visual Basic 2005, it is difficult to determine the intention of code that uses doubles to store
dates. To avoid unnecessary modifications to your code in Visual Basic 2005, always use the Date data type to store dates.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts
MsgBox Form1.Text1.Text
MsgBox Form1.Text1
The default property is resolved when the code is compiled. In addition, you can also use default properties with late-bound
objects, as in the following example:
In the late-bound example, the default property is resolved at run time, and the MsgBox displays the value of the default
property of the TextBox as Text1.
Visual Basic 2005 does not support parameterless default properties, and consequently does not allow this programming
shortcut. When your project is upgraded, Visual Basic 2005 resolves the parameterless default properties, but late-bound
usages that rely on run-time resolution cannot be automatically resolved. In these cases, you will have to change the code
yourself. An additional complication is that many libraries implement default properties using a property called _Default.
_Default acts as a proxy, passing calls to the real default property. So, when your project is upgraded, some default properties
will be resolved to _Default. The code will still work as usual, but it will be less understandable than code written explicitly
using the actual property. For these reasons, try to avoid using parameterless default properties in your Visual Basic 6.0 code.
Instead of writing:
use:
While parameterless default properties are not supported in Visual Basic 2005, default properties with parameters are
supported. To understand the difference between the two types, consider that parameterized default properties always have an
index. An example is the default property of ADO recordset: the Fields collection. The code:
Dim rs As ADODB.Recordset
rs("CompanyName") = "SomeCompany"
rs!CompanyName = "SomeCompany"
In this case, the Fields property is parameterized, and so the usage is valid in Visual Basic 2005; however, the default property
of the Fields property, Value, is parameterless, so the correct usage in Visual Basic 2005 is:
Dim rs As ADODB.Recordset
rs("CompanyName").Value = "SomeCompany"
rs!CompanyName.Value = "SomeCompany"
This example and most other default properties are resolved for you when the project is upgraded, so resolving them in Visual
Basic 6.0 is simply a good programming practice. However, you should avoid using default properties with the Object and
Variant data types, as these cannot be resolved and you will have to fix the code yourself in the upgraded project.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts
Dim V
V = 1 + Null
V = Null + Right$("SomeText", 1)
V = Right("SomeText", 0)
Null propagation is not supported in Visual Basic 2005. The statement 1+Null will generate a type mismatch in Visual Basic
2005. Additionally, where Visual Basic 6.0 had two versions of the Left function — Left$ returning a string, Left returning a
variant which could be Null — Visual Basic 2005 only has one version, Left, which always returns a string.
In order to be compatible with both Visual Basic 6.0 and Visual Basic 2005, you should always write code to test for Null
instead of relying on Null propagation. Furthermore, in Visual Basic 2005, the following functions will no longer return Null:
Chr, Command, CurDir, Date, Environ, Error, Hex, LCase, LTrim, Oct, Right, RTrim, Space, Str, Time, Trim, UCase
Null propagation is commonly used in database applications, where you need to check if a database field contains Null. In
these cases you should check results using the function IsNull() and perform the appropriate action.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts
A side effect is that the Option Base statement is removed from the language.
When your project is upgraded to Visual Basic 2005, any option base statements are removed from your code. If the array is
zero-bound, it is left unchanged. However, if an array is non-zero–bound, then the lower bound is removed and a warning is
inserted into the code, as in the following example:
changes to:
In many cases, the upgraded code will work as it did before. However, if your application logic relies on the lower bound being
1, then you will need to make some modifications. Dim, ReDim, and LBound statements are marked with warnings to help
you review the changes.
For this reason, you should use zero-bound arrays in your Visual Basic 6.0 code, avoid using ReDim as an array declaration,
and avoid using Option Base 1.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts
rather than:
However, fixed-length strings do cause a problem when used in structures. The problem arises because the fixed-length string
class is not automatically created when the structure is created. Likewise, fixed-size arrays are not created when the structure is
created.
When your code is upgraded, user-defined types with fixed-length strings or arrays will be converted to structures and marked
with a comment telling you to initialize the fixed-length string or array before referencing the structure in code. However, you
can shield yourself from this modification by changing your Visual Basic 6.0 user-defined types to use strings instead of fixed-
length strings, and uninitialized arrays instead of fixed-size arrays. For example:
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts
GoSu GoSub and Return statements are not supported in Visual Basic 2005. In most cases you can replace these with functi
b/Ret ons and procedures.
urn
Optio The Option Base statement was used to specify the default lower bound of an array as either 0 or 1. This statement ha
n Bas s been removed from the language since Visual Basic 2005 natively only supports arrays with a zero lower bound. Non
e 0|1 -zero lower bound arrays are supported through the Compatibility library.
VarPt VarPtr, VarPtrArray, VarPtrStringArray, ObjPtr and StrPtr are undocumented functions used to get the underlying
r, Obj memory address of variables. These functions are not supported in Visual Basic 2005.
Ptr, St
rPtr
LSet In Visual Basic 6.0, the LSet statement can be used to assign a variable of one user-defined type to another variable of
a different user-defined type. This functionality is not supported in Visual Basic 2005.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts
changes to:
In addition to numeric data type upgrades, Visual Basic 6.0 has a fixed-length string data type which is not supported in Visual
Basic 2005, and which is upgraded to a fixed-length string wrapper class. In many cases in Visual Basic 6.0 you can perform the
same action using a normal string. For example:
can be better written using a normal string explicitly set to length 25 instead of a fixed-length string:
In some cases, Visual Basic 2005 better handles passing strings to APIs, since you can optionally declare how you want strings
to be passed using the ANSI and UNICODE keywords.
There are three cases where you may need to make some changes. The first is passing user-defined types that contain fixed-
length strings or byte arrays to APIs. In Visual Basic 2005 you may need to change your code, adding the MarshallAs attribute
(from the System.Runtime.InteropServices namespace) to each fixed-length string or byte array in the user-defined type. The
second case is using the As Any variable type in a Declare statement. This is not supported in Visual Basic 2005. Variables of
type As Any were often used to pass a variable that was either a string or Null; you can replace this Visual Basic 6.0 usage by
declaring two forms of the API, one with longs, one with strings. For example, the GetPrivateProfileString API has a
parameter lpKeyName of type As Any:
You can remove the "As Any" by replacing the Declare with two versions, one that accepts a long, and one that accepts a
string:
When you wish to pass the value Null to the API, you use the GetPrivateProfileStringNullKey version. Doing it this way
means that the function upgrades to Visual Basic 2005.
The final area where you may need to make some changes is if you are using APIs that perform thread creation, derive from
Windows classes, perform message queue hooking, and so on. Some of these functions will cause a run-time error in Visual
Basic 2005. Many of these APIs have equivalents in Visual Basic 2005 or the .NET Framework. You will have to fix these on a
case-by-case basis.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
5. On the third page of the wizard, enter the location where the new project will be created.
Note
Each Visual Basic 2005 project must be in its own folder. If you specify a folder that contains files, you will be prompted
to choose a different folder.
6. On the fourth page of the wizard, click Next to begin the upgrade process. When the process is complete, the new
project will appear in Solution Explorer.
7. In Solution Explorer, double-click the _UpgradeReport.htm node to open the upgrade report.
8. Review the upgrade report. Any errors must be fixed before you can run the application. Any warnings should be
examined to make sure that they do not affect application behavior.
Tip
For an explanation of any error or warning, click on the description to display a Help topic.
9. On the Debug menu, choose Start. Run the application and make sure that there are no errors and that the behavior is
the same as it was in Visual Basic 6.0.
Note
The Upgrade Wizard cannot catch all possible incompatibilities; it is possible that you will encounter additional errors w
hen you run the application. For a list of known issues, see
Troubleshooting Applications Upgraded from Visual Basic 6.0.
See Also
Tasks
How to: View the Upgrade Report
Concepts
Preparing a Visual Basic 6.0 Application for Upgrading
WebClasses for Visual Basic 6.0 Users
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Reference
For best performance, upgrade code in modules rather than in Form modules. If you need to upgrade a form, use the
Upgrade Wizard.
If you paste code that contains Unicode characters, a dialog will appear asking if you want to remove them. If you choose
OK, the code will be parsed and any Unicode characters will be removed.
See Also
Tasks
How to: Upgrade Visual Basic 6.0 Code with the Upgrade Visual Basic 6 Code Dialog Box
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts
How to: Upgrade Visual Basic 6.0 Code with the Upgrade Visual
Basic 6 Code Dialog Box
The Upgrade Visual Basic 6 Code dialog box is a tool that converts Visual Basic 6.0 code to equivalent Visual Basic 2005
code. Unlike the Visual Basic Upgrade Wizard, which upgrades an entire application, the Upgrade Visual Basic 6 Code dialog
box is available at design time to convert small amounts of code as you are developing your Visual Basic 2005 application.
The Upgrade Visual Basic 6 Code dialog box is useful in two ways:
You can make use of existing Visual Basic 6.0 code by pasting it into the tool.
You can type in code using Visual Basic 6.0 syntax in order to learn the Visual Basic 2005 equivalent.
After running the tool, Visual Basic 2005 code is inserted into the Code Editor at the current cursor location. If there are any
problems with the conversion, comments are inserted with clickable links to Help pages that explain the problem and any
possible workarounds.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
4. If your code references a COM component, select the References tab and click Add Reference, then select the reference
in the Add Reference dialog box.
5. Click Upgrade to convert the code and insert it into the Code Editor.
Any COM references will be added to the References node for your project in Solution Explorer, and a project-level
Imports statement will be added for the Microsoft.VisualBasic.Compatibility namespace.
See Also
Reference
Upgrade Visual Basic 6 Code Dialog Box
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts
Note
The dialog boxes and menu commands you see might differ from those described in Help, depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
6. To display the DownPicture image at run time, add the following code to the CheckedChanged event for the CheckBox
control.
VB
If CheckBox1.Checked = True Then
' Assign the second image (DownPicture) to the Image property.
CheckBox1.Image = ImageList1.Images(1)
Else
' Assign the first image (Picture) to the Image property.
CheckBox1.Image = ImageList1.Images(0)
End If
7. To display the DisabledPicture image at run time, add the following code to the EnabledChanged event for the
CheckBox control.
VB
If CheckBox1.Enabled = False Then
' Assign the third image (DisabledPicture) to the Image property.
CheckBox1.Image = ImageList1.Images(2)
ElseIf CheckBox1.Checked = True Then
' Assign the second image (DownPicture) to the Image property
CheckBox1.Image = ImageList1.Images(1)
Else
' Assign the first image (Picture)to the Image property
CheckBox1.Image = ImageList1.Images(0)
End If
The application should now behave exactly as it did in Visual Basic 6.0.
See Also
Concepts
Style Property for Visual Basic 6.0 Users
CheckBox Control for Visual Basic 6.0 Users
CommandButton Control for Visual Basic 6.0 Users
OptionButton Control for Visual Basic 6.0 Users
OptionButton Control for Visual Basic 6.0 Users
User Controls for Visual Basic 6.0 Users
Visual Basic Concepts
If you have never created an ASP.NET Web Site Application before upgrading your first Visual Basic 6.0 WebClass project, you
will need to set the project's StartUp object. You do so by right-clicking the .aspx file and selecting Set As Start Page from the
shortcut menu before running the upgraded project.
See Also
Concepts
WebClasses for Visual Basic 6.0 Users
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts
See Also
Concepts
Visual Basic Upgrade Wizard
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts
The upgrade report can be viewed in the Visual Basic 2005 integrated development environment (IDE) or in any Web browser.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
3. Open the resulting project in Visual Basic 2005. Review the code — notes are inserted into the code during upgrade to
alert you to any potential problems. Any errors must be fixed before you can run the application. Any warnings should be
examined to make sure that they do not affect application behavior.
Tip
For an explanation of any error or warning, click on the description to display Help.
4. On the Debug menu, choose Start. Run the application and make sure that there are no errors and that the behavior is
the same as it was in Visual Basic 6.0.
Note
The Vbupgrade tool cannot catch all possible incompatibilities; it is possible that you will encounter additional errors w
hen you run the application. For a list of known issues, see
Troubleshooting Applications Upgraded from Visual Basic 6.0.
See Also
Tasks
How to: View the Upgrade Report
Reference
Vbupgrade Command-Line Syntax
Concepts
Preparing a Visual Basic 6.0 Application for Upgrading
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Reference
Arguments
inputname
Required.
Specifies the path and file name of the Visual Basic 6.0 project to be upgraded.
/out outputname
Specifies the path for the folder where the Visual Basic 2005 project will be created. The default path is \OutDir.
/verbose
Displays all output to the Command Prompt window during upgrade.
/nolog
Does not create a log file during upgrade.
/logfile logfilename
Specifies the path and file name for the log file created during upgrade. If the path and file name are not specified, a log file is
created in the same folder as the Visual Basic 2005 project. The default file name is ProjectFileName.log, where
ProjectFileName is the name of the project file.
/?
Displays a list of command-line options.
Remarks
Paths or file names that contain spaces must be surrounded by quotation marks.
See Also
Tasks
How to: Upgrade a Project from the Command Line
Reference
Upgrade Wizard
Visual Basic Concepts
To fix this problem, find any code that assigns a string to the fixed-length string and add code to check the length of the string
and truncate it if necessary:
VB
' Before
MyString = "1234567"
MyStruct.FixedString5 = MyString
' After
MyString = "1234567"
If Len(MyString) > 5 Then
MyString = Microsoft.VisualBasic.Left(MyString, 5)
End If
MyStruct.FixedString5 = MyString
Result:
If Err.Number = 9 Then
' Do something.
Else
' Do something else.
End If
Before upgrading, Err.Number will always return 9 (Subscript out of range) and execute the first part of the If statement. After
upgrading, it will return 91 (Object variable or With block not set) and execute the Else clause. This is because in Visual Basic
2005, an array must be initialized before it can be referenced; in Visual Basic 6.0, arrays are initialized when declared.
If you depend on the return values from Err.Number in your code, you should carefully test the results and modify your code
as necessary.
See Also
Concepts
Working with Both Visual Basic 6.0 and the Current Version of Visual Basic
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts
Working with Both Visual Basic 6.0 and the Current Version of
Visual Basic
Both Visual Basic 2005 and Visual Basic 6.0, as well as applications created in either language, can be installed on the same
computer and run at the same time.
Components written in Visual Basic 2005 can interoperate with COM components written in earlier versions of Visual Basic
and other languages. For example, you can drag an ActiveX control written in Visual Basic 6.0 onto a Visual Basic 2005
Windows Form, use a Visual Basic 6.0 COM object from a Visual Basic 2005 class library, or add a reference to a Visual Basic
2005 library to a Visual Basic 6.0 executable.
Components compiled with Visual Basic 2005 have subtle run-time differences compared to components compiled with Visual
Basic 6.0. Because Visual Basic 2005 objects are released through garbage collection, when objects are explicitly destroyed,
there may be a lag before they are actually removed from memory. There are additional differences, such as data type and
other language changes. The combined result of these differences is that Visual Basic 2005 applications will have similar but
not identical run-time behavior to Visual Basic 6.0 applications.
In addition, Visual Basic 2005 makes binary compatibility between Visual Basic 2005 components and those in Visual Basic 6.0
unnecessary. Components now have a more robust versioning and deployment system, files can be deployed by simply
copying to a directory, and upgrading to a new version of a component is as simple as replacing the old file with a new file. All
you have to do is ensure classes and methods are compatible with the previous versions.
See Also
Concepts
Why Upgrading Is Necessary
Preparing a Visual Basic 6.0 Application for Upgrading
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts
8. Add an Image control to the form, and set the Name property to sourceImage and the Visible property to False.
9. Set the Picture property of the Image control to any bitmap image. You can use one of the pictures in your My Pictures
folder.
10. Add a Timer control to the form. Set the Enabled property to False and the Interval property to 25.
11. Double-click the form to open the Code Editor, and enter the following code.
Option Explicit
Private LeftPos As Double
12. Press F5 to run the application. Click the buttons to observe the behavior, and step through the code to see how it works.
13. On the File menu, choose Save Project As.
14. In the Save File As dialog box, save the form as PicForm.frm and save the project as Drawing.vbp.
2. Expand the PicForm.vb section by clicking on the plus sign in the New Filename column. This displays a detailed list of
upgrade issues for the form.
Notice that the issues apply to three different locations: the ClearPictureBox_Click procedure, the Timer1_Timer
procedure, and the form layout. You can click on the Description link to display a Help topic explaining each issue. The
layout issues in this case do not require any action; checking the Help reveals that they are for two properties of the
Visual Basic 6.0 PictureBox control that do not map to equivalent Visual Basic 2005 properties.
To fix the ClearPictureBox_Click error
1. In Solution Explorer, select PicForm.vb. On the View menu, choose Code.
2. In the Code Editor, select the ClearPictureBox_Click procedure.
Tip
There is an UPGRADE_ISSUE comment added to the procedure. If you scroll to the end of the comment, you can click o
n the link that displays the associated Help topic. All issues (except for layout issues) are added as code comments duri
ng an upgrade, including UPGRADE_NOTE comments explaining what happened during the upgrade; these do not app
ear in the Upgrade Report.
The only error in the original procedure is the Picture1.Cls() method call. In Visual Basic 2005, the intrinsic controls do
not provide direct access to their drawing surfaces with methods (as in Visual Basic 6.0). All graphics operations are
handled with a special object of type Graphics. You can access a control's drawing surface by calling the
CreateGraphics() method to get an instance of a Graphics object.
4. Delete or comment out the original line, Picture1.Cls().
As with the previous procedure, the errors here begin with the lack of a Graphics object.
3. Find the first UPGRADE_ISSUE, the Picture1.Print method. Add the following code:
VB
g.DrawString("VB .NET ROCKS!", Me.Font, New SolidBrush( _
Color.Yellow), 0, 0)
The DrawString method of the Graphics object replaces the Visual Basic 6.0 Print method. Where the Print method
took a single Text argument, DrawString also takes arguments specifying the Font, a Brush object that specifies a
Color object, and the starting coordinates for drawing the text.
4. Delete or comment out the original line, Picture1.Print("Visual Basic ROCKS!").
5. Find the next UPGRADE_ISSUE, Picture1.Cls(). Replace the code with the following:
VB
g.Clear(Picture1.BackColor)
In this case, the DrawImage method of the Graphics class replaces the PaintPicture method.
7. Delete or comment out the original line, Picture1.PaintPicture(sourceImage, LeftPos *
VB6.PixelsToTwipsX(Picture1.Width), 0).
The Dispose method is necessary to free up the memory resources associated with the Graphics object.
g.FillRectangle(New SolidBrush(Me.BackColor), _
New Rectangle(left, 0, 6, imageHeight))
In place of the Clear method, use the FillRectangle method, using the background color to obscure any remaining
pixels to the right of the current image being drawn. To do this, you first need to calculate the left-most coordinate of the
rectangle, which is accomplished by the first three lines of code.
2. On the Debug menu, choose Start.
3. Click the ShowImage button.
You will notice that the image no longer flickers as it moves.
There is still one additional problem that should be fixed. You may have noticed that the message displayed in the PictureBox
control is in a smaller font than the original version. This is because the Font property of the PictureBox control in the Visual
Basic 6.0 application was set to Arial Bold 16 at design time. There is no Font property for the Visual Basic 2005 PictureBox
control; instead, the form's default font (Me.Font) is used. You can remedy this by declaring a new Font object.
To fix the font
1. In the Timer1_Tick procedure, add the following declaration:
VB
Dim f As System.Drawing.Font = New System.Drawing.Font("Arial", _
16, FontStyle.Bold)
Upgrade Wizard
Use the Upgrade Wizard to upgrade Visual Basic 6.0 projects to Visual Basic 2005. The wizard creates a new project, copies
each file from the original project into the new project and modifies it as necessary, and generates a report detailing what was
done and what you need to do to finish the upgrade.
To access the Upgrade Wizard, open any Visual Basic 6.0 project file (.vbp) in Visual Basic 2005.
User Interface Element List
The following options are available in the Upgrade Wizard.
What type of project would you like this to be upgraded to?
If the Visual Basic 6.0 project is an ActiveX EXE or ActiveX Document EXE project, you can upgrade it to either an .exe or a .dll
file. For all other project types, the correct option is already selected and cannot be changed.
Where do you want your new project created?
Specifies the location of the new project. By default, the project is placed in a directory directly beneath the Visual Basic 6.0
project. The new project is named ProjectName.NET, where ProjectName is the name of the project being upgraded.
See Also
Concepts
Visual Basic Upgrade Wizard
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Reference
FontChangeBold Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.
FontChangeGdiCharSe Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.
t
FontChangeItalic Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.
FontChangeName Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.
FontChangeSize Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.
FontChangeStrikeout Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.
FontChangeUnderline Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.
GetCancel Duplicates the functionality of the Cancel property of a Visual Basic 6.0 CommandButton.
GetDefault Duplicates the functionality of the Default property of a Visual Basic 6.0 CommandButton.
GetItemData Duplicates the functionality of the ItemData property of a Visual Basic 6.0 ListBox or ComboBox.
GetItemString Duplicates the functionality of retrieving a value from a list in a Visual Basic 6.0 ListBox or ComboB
ox.
SetCancel Duplicates the functionality of the Cancel property of a Visual Basic 6.0 CommandButton.
SetDefault Duplicates the functionality of the Default property of a Visual Basic 6.0 CommandButton.
SetItemData Duplicates the functionality of the ItemData property of a Visual Basic 6.0 ListBox or ComboBox.
SetItemString Duplicates the functionality of setting a value in a list in a Visual Basic 6.0 ListBox or ComboBox.
SetResourceBaseNam Used with LoadRes functions when a resource file uses a non-standard naming convention.
e
ShowForm Duplicates the functionality of the Show method of a Visual Basic 6.0 form.
TabLayout Used when converting Debug.Print statements that contain the Tab or Spc keywords.
ToPixelsX Used for coordinate conversion.
ValidateControls Duplicates the functionality of the ValidateControls method of a Visual Basic 6.0 form.
WhatsThisMode Duplicates the functionality of the WhatsThisMode method of a Visual Basic 6.0 form.
CheckedListBoxArray Emulates a Visual Basic 6.0 control array of ListBox controls with the Style property set to Checked.
PanelArray Emulates a Visual Basic 6.0 control array of PictureBox controls that contain child controls.
Command Window No
Dynamic Help window No Does not appear when you press F1.
Server Explorer/Database Explorer No Displays data connections and available system servi
ces.
Start Page Yes Appears the first time you start the IDE. You can cust
omize it.
In addition, the following elements have certain behaviors enabled when you select Visual Basic Development Settings.
Dialog Boxes
Feature Behavior
New Project Dialog Box When other platforms are installed on the computer, the IDE enables the combo box that all
ows you to specify the targeted platform.
Options Dialog Box (Visual Studio) Visual Basic enables simplified Options pages. Click the Show All Settings check box to se
e the full list of options.
Keyboard
Feature Behavior
Visual Basic 6.0 Default Shortcut Keys Supports typical Visual Basic 6 keyboard mapping.
Miscellaneous IDE Elements
Feature Behavior
Tool tips Appear for all menu items and toolbar buttons when the mouse hovers above th
em.
Visual Basic IntelliSense Code Snippets Includes a library of code snippets that are ready to be inserted in your application.
Visual Basic-Specific IntelliSense Provides all of the IntelliSense features with some productivity enhancements for
Visual Basic developers.
See Also
Tasks
How to: Customize Dynamic Help
How to: Change Select Settings
How to: Specify Settings for a Team
Reference
Import and Export Settings, Environment, Options Dialog Box
Other Resources
Import and Export Settings Wizard
Visual Basic: Samples
See Also
Tasks
How to: Insert Snippets Into Your Code (Visual Basic)
Reference
Creating and Using IntelliSense Code Snippets
Concepts
Visual Basic IntelliSense Code Snippets
Security Considerations in Using Snippets
Best Practices for Using IntelliSense Code Snippets
Visual Basic: Samples
Troubleshooting Snippets
Problems with IntelliSense code snippets are typically caused by two problems: a corrupt snippet file or bad content in the
snippet file.
Common Problems
The Snippet Cannot Be Dragged from Windows Explorer to a Visual Studio Source File
The XML in the snippet file may be corrupt. The XML Editor in Visual Studio can locate problems in the XML structure.
The snippet file may not conform to the snippet schema. The XML Editor in Visual Studio can locate problems in the
XML structure.
The Code Has Compiler Errors That Are Not Highlighted
You may be missing a project reference. Examine the documentation about the snippet. If the reference is not found on
the computer, you will need to install it. Inserting a snippet should add to the project any references needed. If the
snippet is missing the reference information, that can be reported to the snippet creator as an error.
A variable may be undefined. Undefined variables in a snippet should be highlighted. If not, that can be reported to the
snippet creator as an error.
See Also
Reference
Creating and Using IntelliSense Code Snippets
Visual Basic Language Concepts
Field Changes the declaration and usages of the field to the new name.
Local variab Changes the declaration and usages of the variable to the new name.
le
Method Changes the name of the method and all references to that method to the new name.
Namespace Changes the name of the namespace to the new name, in the declaration, all Imports statements, and all fully qu
alified names.
Property Changes the declaration and usages of the property to the new name.
Refactoring
To provide a more complete refactoring experience, Visual Basic has partnered with Developer Express Inc. to get the developer
refactoring support. See Refactor! (http://msdn.microsoft.com/vbasic/downloads/2005/tools/refactor/) on the MSDN Visual
Basic Developer Center for additional details and instructions on how to download this tool. Refactor! supports more than 15
individual refactoring features, including operations like Reorder Parameters, Extract Method, Encapsulate Field, and Create
Overload.
See Also
Tasks
How to: Rename an Identifier
Other Resources
Using the Visual Basic Editor
Visual Basic Language Concepts
Edit.Cut CTRL + X Removes the currently selected item to the system Clipboard.
SHIFT + DE
LETE
Edit.CycleCli CTRL + SHI Pastes an item from the Clipboard Ring tab of the Toolbox at the insertion point in the file and aut
pboardRing FT + V omatically selects the pasted item. You can review each item on the Clipboard by repeatedly pressing
the shortcut keys.
CTRL + SHI
FT + INSER
T
Edit.GotoNe F12 Moves the cursor to the next item, such as a task in the Task List window or a search match in the Fi
xtLocation nd Results window. Each time you press F12, you move to the next item in the list.
Edit.GotoPr SHIFT + F12 Moves the cursor to the previous item in the Task List window or Find Results window.
eviousLocat
ion
Edit.ListMe CTRL + J Lists members of the current class for statement completion when editing code.
mbers
Edit.Parame CTRL + SHI Displays a ToolTip that contains information for the current parameter based on the current languag
terInfo FT + I e.
Edit.QuickIn CTRL + I Displays the complete declaration for the identifier nearest the insertion point in a ToolTip.
fo
File.AddExis CTRL + D Displays the Add Existing Item dialog box, which allows you to add an existing file to the current pr
tingItem oject.
File.AddNe CTRL + SHI Displays the Add New Item dialog box, which allows you to add a new file to the current project.
wItem FT + A
File.Print CTRL + P Displays the Print dialog box where you can choose printer settings.
File.SaveAll CTRL + SHI Saves all documents in the current solution and any files in the external files project.
FT + S
Tools.GoTo CTRL + / Places the caret in the Find/Command box on the Standard toolbar.
CommandLi
ne
View.Navig CTRL + SHI Goes back to the previous document or window in the navigation history.
ateBackwar FT + F2
d
View.Navig CTRL + SHI Moves forward to the next document or window in the navigation history.
ateForward FT + -
View.WebN ALT + LEFT Displays the previous page in the viewing history. Available only in the integrated Web browser.
avigateBack ARROW
View.WebN ALT + RIGH Displays the next page in the viewing history. Available only in the integrated Web browser.
avigateForw T ARROW
ard
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Project Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Integrated Help Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
Help.Dynami CTRL + F1 Displays the Dynamic Help window, which displays different topics depending on what items
cHelp currently have focus in the product.
Help.F1Help F1 Displays a topic from Help that corresponds to the current user interface selected.
Help.Index CTRL + ALT + F Displays the Index window for the documentation contained in MSDN.
2
Help.Nexttop ALT + DOWN A Displays the next topic in the table of contents. Available only in the Help (Web) browser windo
ic RROW w.
Help.Previou ALT + UP ARRO Displays the previous topic in the table of contents. Available only in the Help (Web) browser w
stopic W indow.
Help.Search CTRL + ALT + F Displays the Search window, which allows you to search for words or phrases in the document
3 ation contained in MSDN.
Help.Window SHIFT + F1 Displays a topic from Help that corresponds to the current user interface selected.
Help
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Window Management Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
Build.Compile CTRL + F7 Creates an object file containing machine code, linker directives, sections, external references, and
function/data names for the selected file.
File.NewFile CTRL + SHIF Displays the New File dialog box where you can select a new file to add to the current project.
T+N
File.NewProje CTRL + N Displays the New Project dialog box where you can create projects and add them to the current s
ct olution.
File.OpenFile CTRL + SHIF Displays the Open File dialog box where you can select an existing file to open.
T+O
File.OpenProj CTRL + O Displays the Open Project dialog box where you can add existing projects to your solution.
ect
File.AddExistin CTRL + D Displays the Add Existing Item dialog box, which allows you to add an existing file to the current
gItem project.
File.AddNewIt CTRL + SHIF Displays the Add New Item dialog box, which allows you to add a new file to the current project.
em T+A
Edit.ClearA CTRL + K, Removes all unnamed bookmarks in the current document. Only available in HTML view of the HTML
llBookmar CTRL + L Designer.
ks
Edit.Compl CTRL + SP Displays Word Completion based on the current language. Only available in HTML view of the HTML
eteWord ACEBAR Designer.
Edit.MakeL CTRL + U Changes the selected text to lowercase characters. Available only in HTML view of the HTML Designe
owercase r.
Edit.MakeU CTRL + SH Changes the selected text to uppercase characters. Available only in HTML view of the HTML Designer
ppercase IFT + U .
Edit.NextB CTRL + K, Moves to the next bookmark in the document. Available only in HTML view of the HTML Designer.
ookmark CTRL + N
Edit.Word CTRL + DE Deletes the word to the right of the insertion point. Available only in HTML view of the HTML Designe
DeleteToEn LETE r.
d
CTRL + SH
IFT + BAC
KSPACE
Edit.Word CTRL + BA Deletes the word to the left of the insertion point. Available only in HTML view of the HTML Designer.
DeleteToSt CKSPACE
art
Format.Bol CTRL + B Toggles the selected text between bold and normal. Available only in Design view of the HTML Desig
d ner.
Format.De CTRL + SH Decreases the selected paragraph by one indent unit. Available only in Design view of the HTML Desi
creaseInde IFT + T gner.
nt
Format.Inc CTRL + T Indents the selected paragraph by one indent unit. Available only in Design view of the HTML Design
reaseInden er.
t
Format.Itali CTRL + I Toggles the selected text between italic and normal. Available only in Design view of the HTML Desig
c ner.
Format.Loc CTRL + SH Prevents an absolutely positioned element from being inadvertently moved. Available only in Design v
kElement IFT + K iew of the HTML Designer.
Format.Sh CTRL + G Toggles snap to grid. Available only in Design view of the HTML Designer.
owGrid
Format.Sn CTRL + SH Specifies that elements be aligned using an invisible grid. You can set grid spacing on the Display pan
aptoGrid IFT G e of HTML Designer options in the Options dialog box, and the grid will be changed the next time you o
pen a document. Available only in Design view of the HTML Designer.
Format.Un CTRL + U Toggles the selected text between underlined and normal. Available only in Design view of the HTML
derline Designer.
Format.Ins CTRL + SH Displays the Bookmark dialog box, which allows you to create a target for jumps within the current doc
ertBookma IFT + L ument. Available in Design view and HTML view of the HTML Designer.
rk
Format.Co CTRL + L When text is selected, displays the Hyperlink dialog box. Available in Design view and HTML view of th
nverttoHyp e HTML Designer.
erlink
Table.Inser CTRL + AL Adds one row above the current row in the table. Available only in Design view of the HTML Designer
tRowAbov T + UP AR .
e ROW
Table.Inser CTRL + AL Adds one row below the current row in the table. Available only in Design view of the HTML Designer
tRowBelow T + DOW .
N ARROW
Table.Inser CTRL + AL Adds one column to the left of the current column in the table. Available only in Design view of the HT
tColumnst T + LEFT A ML Designer.
otheLeft RROW
Table.Inser CTRL + AL Adds one column to the right of the current column in the table. Available only in Design view of the H
tColumnst T + RIGHT TML Designer.
otheRight ARROW
View.Detail CTRL + SH Displays signal icons for HTML elements that do not have a visual representation, such as comments, s
s IFT + Q cripts, and anchors for absolutely positioned elements. Available only in Design view of the HTML Des
igner.
View.Next CTRL + PA Switches from Design view to HTML view and vice versa. Available only in Design view of the HTML
View GE DOWN Designer.
View.Visibl CTRL + Q Displays a 1-pixel border around HTML elements that support a BORDER attribute such as tables, table
eBorders cells, and divisions, and has it set to zero. Available only in Design view of the HTML Designer.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
HTML Designer
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
Image.FlipHoriz CTRL + H Flips the image from right to left on the horizontal axis. Available only in the Image editor.
ontal
Image.FlipVertic SHIFT + ALT Flips the image from top to bottom on the vertical axis. Available only in the Image editor.
al +H
Image.NewImag INSERT Displays the New Icon Image Type dialog box, which allows you to select a new image type to
eType create. Available only in the Image editor.
Image.Rotate90 CTRL + SHI Rotates the image 90 degrees clockwise. Available only in the Image editor.
Degrees FT + H
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Image Editor
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
Debug.Auto CTRL Displays the Auto window to view the values of variables currently in the scope of the current line of exec
s + ALT ution within the current procedure.
+ V, A
Debug.Brea CTRL Temporarily stops execution of all processes in a debugging session. Available only in Run mode.
kAll + BRE
AK
Debug.Brea CTRL Displays the Breakpoints dialog box where you can add and modify breakpoints.
kpoints + ALT
+B
Debug.Call CTRL Displays the Call Stack window to display a list of all active procedures or stack frames for the current thr
Stack + L ead of execution. Available only in Run mode.
Debug.Imm CTRL Displays the Immediate window where you can evaluate expressions and execute individual commands.
ediate +G
Debug.Loca CTRL Displays the Locals window to view the variables and their values for each procedure in the current stack f
ls + ALT rame.
+ V, L
Debug.Me CTRL Displays the Memory 1 window, which allows you to view large buffers, strings, and other data that do no
mory1 + ALT t display well in the Watch or Variables window.
+ M, 1
Debug.Me CTRL Displays the Memory 2 window, which allows you to view large buffers, strings, and other data that do no
mory2 + ALT t display well in the Watch or Variables window.
+ M, 2
Debug.Me CTRL Displays the Memory 3 window, which allows you to view large buffers, strings, and other data that do no
mory3 + ALT t display well in the Watch or Variables window.
+ M, 3
Debug.Me CTRL Displays the Memory 4 window, which allows you to view large buffers, strings, and other data that do not
mory4 + ALT display well in the Watch or Variables window.
+ M, 4
Debug.Mod CTRL Displays the Modules window which allows you to view the .dll or .exe files used by the program.
ules + ALT
+U
Debug.Quic SHIFT Displays the Quick Watch dialog box with the current value of the selected expression. Available only in B
kWatch + F9 reak mode. Use this command to check the current value of a variable, property, or other expression for w
hich you have not defined a watch expression.
Debug.Regi CTRL Displays the Registers window, which displays content for debugging native code applications.
sters +ALT
+G
Debug.Rest SHIFT Terminates a debugging session, rebuilds, and then starts running the application from the beginning. Ava
art + F5 ilable in Break and Run modes.
Debug.Run CTRL Displays the Running Documents window that shows the set of documents that you are in the process o
ningDocum + ALT f debugging. Available in Run mode.
ents +N
Debug.Run CTRL In Break mode, resumes execution of your code from the current statement to the selected statement. The
ToCursor + F8 Current Line of Execution margin indicator appears in the Margin Indicator bar. In Design mode, starts
the debugger and executes your code to the cursor location.
Debug.Set CTRL Sets the execution point to the line of code you choose.
NextStatem + F9
ent
Debug.Start F5 Automatically attaches the debugger and runs the application from the startup form specified in the <Proj
ect> Properties dialog box. Changes to Continue if in Break mode.
Debug.Step F8 Executes code one statement at a time, following execution into function calls.
Into
Debug.Step CTRL Executes the remaining lines of a function in which the current execution point lies.
Out + SHIF
T + F8
Debug.Step SHIFT Executes the next line of code, but does not follow execution through any function calls.
Over + F8
Debug.This CTRL Displays the This window, which allows you to view the data members of the object associated with the cu
+ ALT rrent method.
+ V, T
Debug.Thre CTRL Displays the Threads window to view all of the threads for the current process and information about the
ads + ALT m.
+H
Debug.Tog CTRL Displays the disassembly information for the current source file. Available only in Break mode.
gleDisasse + F11
mbly
Tools.Debu CTRL Displays the Processes dialog box, which allows you to debug multiple programs at the same time in a sin
gProcesses + ALT gle solution.
+P
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Tool Window Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
Edit.FindNextSel CTRL + F3 Finds the next occurrence of the currently selected text in the document.
ected
Edit.FindPreviou CTRL + SHI Finds the previous occurrence of the currently selected text, or the word at the caret.
sSelected FT + F3
Edit.GoToFindC CTRL + SHI Places the caret in the Find/Command line on the Standard toolbar.
ombo FT + F
Edit.HiddenText ALT + F3, H Selects or clears the Search Hidden Text option for the Find dialog box.
Edit.Incremental CTRL + ALT Starts Incremental search. If Incremental search is started but you have not typed any characters,
Search +I recalls the previous pattern. If text has been found, searches for the next occurrence.
Edit.MatchCase ALT + F3, + Selects or clears the Match Case option for Find and Replace operations.
C
Edit.RegularExp ALT + F3, + Selects or clears the Regular expression option so that special characters can be used in Find a
ression R nd Replace operations.
Edit.ReverseIncr CTRL + SHI Changes the direction of Incremental search to begin at the bottom of the file and progress towa
ementalSearch FT + ALT + I rds the top.
Edit.Up ALT + F3, + Selects or clears the Search Up option for Find and Replace operations.
B
Edit.WholeWor ALT + F3, + Selects or clears the Match whole word option for Find and Replace operations.
d W
Edit.Wildcard ALT + F3, P Selects or clears the Wildcard option for Find and Replace operations.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Text Navigation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Text Selection Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Text Manipulation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
Database.StepInt CTRL + E Steps into debug mode for the currently active database object.
o
Query.Run CTRL + R Executes the query. Available only in Visual Database Tools.
View.Diagram CTRL + 1 Displays the Diagram pane of the Query designer. Available only in the Query and View desig
ners.
View.Grid CTRL + 2 Displays the Grid pane of the Query designer. Available only in the Query and View designers.
View.Results CTRL + 4 Displays the Results pane of the Query designer. Available only in the Query and View design
ers.
View.SQL CTRL + 3 Displays the SQL pane of the Query designer. Available only in the Query and View designers.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Global Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
View.ObjectBrowserBac ALT + - Moves back to the previously selected object in the selection history of the Obj
k ect Browser.
View.ObjectBrowserFor SHIFT + ALT + - Moves forward to the next object in the selection history of the Object Brows
ward er.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Tool Window Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Window Management Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
Edit.MoveControlDownG DOWN ARROW Moves the selected control down in increments of 8 on the design sur
rid face.
Edit.MoveControlLeft CTRL + LEFT ARROW Moves the control left in increments of 1 on the design surface.
Edit.MoveControlLeftGri LEFT ARROW Moves the control left in increments of 8 on the design surface.
d
Edit.MoveControlRight CTRL + RIGHT ARROW Moves the control to the right in increments of 1 on the design surfac
e.
Edit.MoveControlRightGr RIGHT ARROW Moves the control right in increments of 8 on the design surface.
id
Edit.MoveControlUp CTRL + UP ARROW Moves the control up in increments of 1 on the design surface.
Edit.SelectPreviousContr SHIFT + TAB Selects the previously selected control on the design surface.
ol
Edit.SizeControlDown CTRL + SHIFT + DOWN ARR Increases the height of the control in increments of 1 on the design su
OW rface.
Edit.SizeControlDownGri SHIFT + DOWN ARROW Increases the height of the control in increments of 8 on the design su
d rface.
Edit.SizeControlLeft CTRL + SHIFT + LEFT ARROW Reduces the width of the control in increments of 1 on the design surf
ace.
Edit.SizeControlLeftGrid SHIFT + LEFT ARROW Reduces the width of the control in increments of 8 on the design surf
ace.
Edit.SizeControlRight CTRL + SHIFT +RIGHT ARRO Increases the width of the control in increments of 1 on the design sur
W face.
Edit.SizeControlRightGri SHIFT + RIGHT ARROW Increases the width of the control in increments of 8 on the design sur
d face.
Edit.SizeControlUp CTRL + SHIFT + UP ARROW Decreases the height of the control in increments of 1 on the design s
urface.
Edit.SizeControlUpGrid SHIFT + UP ARROW Decreases the height of the control in increments of 8 on the design s
urface.
Format.BringToFront CTRL + J Moves the selected control to the top of the Z-order.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Global Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
Edit.DocumentEnd CTRL + END Moves the insertion point to the last line of the document.
Edit.DocumentStart CTRL + HOME Moves the insertion point to the first line of the document.
Edit.GotoBrace CTRL + ] Moves the insertion point to the next brace in the document.
Edit.GoToDeclaration CTRL + ALT + F12 Displays the definition of the selected symbol in the code.
Edit.GoToDefinition SHIFT + F2 Displays the declaration for the selected symbol in code.
Edit.LineDown DOWN ARROW Moves the insertion point down one line.
Edit.LineEnd END Moves the insertion point to the end of the line.
Edit.LineStart HOME Moves the insertion point to the beginning of the line.
Edit.ViewBottom CTRL + PAGE DOWN Moves to the bottom of the current document.
Edit.ViewTop CTRL + PAGE UP Moves to the top of the current window or document.
Edit.WordNext CTRL + RIGHT ARROW Moves the insertion point right one word.
Edit.WordPrevious CTRL + LEFT ARROW Moves the insertion point left one word.
View.ViewDesigner SHIFT + F7 Displays the selected item in Design view of the Editor.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Text Selection Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Text Manipulation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
Edit.CharLeftExtendColu SHIFT + ALT + LEFT ARROW Moves the cursor left one character, extending the column selection.
mn
Edit.CharRightExtend SHIFT + RIGHT ARROW Moves the cursor right one character, extending the selection.
Edit.CharRightExtendCol SHIFT + ALT + RIGHT ARRO Moves the cursor right one character, extending the column selection.
umn W
Edit.DocumentEndExtend CTRL + SHIFT + END Selects the text from the insertion point to the last line of the document
.
Edit.DocumentStartExten CTRL + SHIFT + HOME Selects the text from the insertion point to the first line of the documen
d t.
Edit.GotoBraceExtend CTRL + SHIFT + ] Moves the insertion point to the next brace, extending the selection.
Edit.LineDownExtend SHIFT + DOWN ARROW Extends text selection down one line, starting at the location of the inse
rtion point.
Edit.LineDownExtendCol SHIFT + ALT + DOWN ARRO Moves the cursor down one line, extending the column selection.
umn W
Edit.LineEndExtend SHIFT + END Selects text from the insertion point to the end of the current line.
Edit.LineEndExtendColu SHIFT + ALT + END Moves the insertion point to the end of the line, extending the column
mn selection.
Edit.LineStartExtend SHIFT + HOME Selects text from the insertion point to the start of the line.
Edit.LineUpExtend SHIFT + UP ARROW Selects text up line by line starting from the location of the insertion po
int.
Edit.LineUpExtendColum SHIFT + ALT + UP ARROW Moves the cursor up one line, extending the column selection.
n
Edit.SelectCurrentWord CTRL + W Selects the word containing the insertion point or the word to the right
of the insertion point.
Edit.SelectToLastGoBack CTRL + = Selects from the current location in the Editor back to the previous loca
tion in the Editor.
Edit.ViewBottomExtend CTRL + SHIFT +PAGE DOW Moves the cursor to the last line in view, extending the selection.
N
Edit.ViewTopExtend CTRL + SHIFT +PAGE UP Extends the selection to the top of the current window or document.
Edit.WordNextExtend CTRL + SHIFT + RIGHT ARR Extends the selection one word to the right.
OW
Edit.WordNextExtendCol CTRL + SHIFT + ALT + RIGH Moves the cursor right one word, extending the column selection.
umn T ARROW
Edit.WordPreviousExtend CTRL + SHIFT + LEFT ARRO Extends the selection one word to the left.
W
Edit.WordPreviousExtend CTRL + SHIFT + ALT + LEFT Moves the cursor left one word, extending the column selection.
Column ARROW
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Text Navigation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Text Manipulation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
Edit.CollapsetoDef CTRL + M, C Automatically determines logical boundaries for creating regions in code such as procedures,
inition TRL + O and then hides them.
Edit.CommentSele CTRL + K, CT Marks the current line of code as a comment, using the correct comment syntax for the progr
ction RL + C amming language.
Edit.DeleteHorizon CTRL + K, CT Collapses white space in the selection, or deletes white space adjacent to the cursor if there is
talWhiteSpace RL + \ no selection.
Edit.FormatDocu CTRL + K, CT Applies the indenting and space formatting for the language as specified on the Formatting p
ment RL + D ane of that language in the Text Editor section of the Options dialog box.
Edit.FormatSelecti CTRL + K, CT Correctly indents the selected lines of code based on the surrounding lines of code.
on RL + F
Edit.HideSelection CTRL + M, C Hides the selected text. A signal icon marks the location of the hidden text in the file.
TRL + H
Edit.InsertTab TAB Indents the line of text a specified number of spaces, such as five. Available only in the .NET Fr
amework Designer.
Edit.LineCut CTRL + Y Cuts all selected lines, or the current line if there is no selection, to the Clipboard.
Edit.LineDelete CTRL + SHIF Deletes all selected lines, or the current line if there is no selection.
T+Y
Edit.LineOpenAbo CTRL + ENT Inserts a blank line above the insertion point.
ve ER
Edit.LineOpenBelo CTRL + SHIF Inserts a blank line below the insertion point.
w T + ENTER
Edit.LineTranspos SHIFT + ALT Moves the line containing the insertion point below the next line.
e +T
Edit.OvertypeMod INSERT Types over any characters already in the document instead of inserting the characters. Availab
e le only in Text editors.
Edit.StopHidingCu CTRL + M, C Removes the outlining information for the currently selected region.
rrent TRL + U
Edit.StopOutlining CTRL + M, C Removes all outlining information from the entire document.
TRL + P
Edit.SwapAnchor CTRL + R, C Swaps the anchor and end points of the current selection.
TRL + P
Edit.TabLeft SHIFT + TAB Moves selected lines left one tab stop. Available only in the .NET Framework Designer.
Edit.ToggleAllOutli CTRL + M, C Toggles all previously marked hidden text sections between hidden and display states.
ning TRL + L
Edit.ToggleOutlini CTRL + M, C Toggles the currently selected hidden text section between the hidden and display state.
ngExpansion TRL + M
Edit.UncommentS CTRL + K, CT Removes the comment syntax from the current line of code.
election RL + U
Edit.WordTranspo CTRL + SHIF Transposes the words on either side of the insertion point.
se T+T
View.ShowRefere ALT + F12 Performs a case-sensitive, whole word symbol search and displays the results in the Find Sym
nces bol Results window.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Text Navigation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Text Selection Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
Window.ActivateDocumen ESC Closes a menu or dialog box, cancels an operation in progress, or places focus in t
tWindow he current document window.
Window.MoveToDropDow CTRL + F2 Moves the cursor to the drop-down bar while the Editor is in Code view.
nBar
Window.NextDocumentWi CTRL + F6 Cycles through the MDI child windows one window at a time.
ndow
CTRL + TAB
Window.NextSplitPane F6 Moves to the next pane of a split pane view of a single document.
Window.NextTab CTRL + PAGE D Moves to the next tab in the document or window.
OWN
Window.PreviousDocume CTRL + SHIFT + Moves to the previous document in the Editor or Designer.
ntWindow F6
CTRL + SHIFT +
TAB
Window.PreviousSplitPan SHIFT + F6 Moves to the previous pane of a document in split pane view.
e
Window.PreviousTab CTRL + PAGE U Moves to the previous tab in the document or window.
P
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Tool Window Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Global Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts
Tools.AddRemoveT CTRL + T Displays the Customize Toolbox dialog box, which allows you to add and remove items on the
oolboxItems Toolbox.
View.MacroExplore ALT + F8 Displays the Macro Explorer window which lists all available macros in the current solution.
r
View.CommandWi CTRL + A Displays the Command window, which allows you to type commands that manipulate the IDE.
ndow LT + A
View.DocumentOut CTRL + A Displays the Document Outline window to view the flat or hierarchical outline of the current d
line LT + T ocument.
View.Favorites CTRL + A Displays the Favorites window, which lists shortcuts to Web pages.
LT + F
View.ObjectBrowse F2 Displays the Object Browser to view the classes, properties, methods, events, and constants av
r ailable for packages, and the object libraries and procedures in your project.
View.Output CTRL + A Displays the Output window to view status messages at run time.
LT + O
View.PropertiesWi F4 Displays the Properties window, which lists the design-time properties and events for the curre
ndow ntly selected item.
View.PropertyPage SHIFT + F Displays the property pages for the item currently selected.
s 4
View.ServerExplore CTRL + A Displays Server Explorer, which allows you to view and manipulate database servers, event log
r LT + S s, message queues, Web services, and many other operating system services.
View.SolutionExplo CTRL + R Displays Solution Explorer, which lists the projects and files in the current solution.
rer
View.TaskList CTRL + A Displays the Task List window where you customize, categorize, and manage tasks, comments,
LT + K shortcuts, warnings and error messages.
View.Toolbox CTRL + A Displays the Toolbox, which contains controls and other items that can be included or used wit
LT + X h your code.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Reference
End Sub
See Also
Concepts
Event Handlers Overview (Windows Forms)
Other Resources
Handling and Raising Events
Visual Basic Language Concepts
Local Intranet The application code runs from a file share on the user's intranet.
Trusted Sites These are applications from sites defined as "Trusted" through Internet Explorer.
Untrusted Sites These are applications from sites defined as "Restricted" through Internet Explorer.
The assignment of the first three zones, My Computer, Local Intranet, and Internet, is based on where the code is located.
You can override the assignment by assigning specific sites to the Trusted Sites or Untrusted Sites groups in the Internet
Explorer.
Each of these zones has specific access permissions set by a system administrator. The security level for a zone may be set to
full trust, medium trust, low trust, or no trust. The trust levels define the resources that are accessible to the application. The
zone, together with other security evidence, such as the publisher, strong name, Web site, and URL of the code, determines the
permissions that are granted to the code at run time. (For more information about security evidence, see Evidence.) You have
no control over the security settings on the user's computer, yet your application must work within the settings it encounters
as it runs. This may mean that your application will be denied access to particular resources. For example, your application may
need to write data to a file, yet the user's system will deny write access at run time by raising an exception.
Your job is to develop your application to handle this situation. This does not necessarily mean that you will make your
application find another way to write the data. It does mean that your application needs to anticipate that it may not be able to
write the data and then respond to such a possibility. You may want to use more exception handling
(How to: Test Code with a Try…Catch Block in Visual Basic) or some of the objects in the System.Security.Permissions
namespace to make your code more robust. A brief description of these methods is included in a later section of this article,
"Developing for Partial-Trust Environments."
The security levels for zones are set using the Administration Tools installed when the .NET Framework is installed. To learn
more about the setting security levels for zones on a computer, see Administration Tools.
Full Trust
Developers often work in a full-trust environment. They keep their source code on their hard drives, and they test their
applications from their development computers. In this full-trust environment, any code the developer compiles is allowed to
run on the local computer. Security exceptions do not surface, because the local computer is defined to be a full-trust
environment by default.
Partial Trust
Partial trust describes any zone that is not a full trust zone. When an application is deployed, it may move into a new zone,
perhaps one that does not grant full trust to the application. The two most common scenarios that run code in partial trust are:
Running code that is downloaded from the Internet.
Running code that resides on a network share (intranet).
Some examples of resources that might be denied in a partial-trust zone are:
File I/O operations, including reading, writing, creating, deleting, or printing files.
System components, such as registry values and environment variables.
Server components, including directory services, registry, event logs, performance counters, and message queues.
What is not allowed in partial trust? That is not easy to determine. Each class and each method of each class in the .NET
Framework has a security attribute that defines the level of trust needed to run that method, and that attribute may not be
accessible at run time because of just these security features. The zone level is not a simple mapping of trust level to attributes,
but is a collection of particular permissions given to particular classes and methods. Your application will not be able to simply
query for the trust level and then be able to predict which resources are not available. You can determine whether or not your
application is running in full trust. One method of doing so is described in the next section, "Developing for Partial Trust
Environments."
Developing for Partial-Trust Environments
This section presents a very brief look into how security concerns might affect the code you write. There is no single solution to
developing for the partial-trust environment. Your solution will depend on the application you are writing. Additionally,
because the trust level may change during execution of your application, you cannot simply test for the existing trust level and
then proceed.
Security Exception Code
The first step in developing for partial-trust zones is to write code that recognizes that security exceptions will surface. Consider
the following code:
This method runs without throwing an exception if the project and the project assembly are stored on the hard disk of your
computer, and if you are a member of the Administrators group on your computer. If you deploy this application to your
intranet, SecurityException may be thrown when the application attempts to save the bitmap object. If you do not have a
Try...Catch...Finally Statement (Visual Basic) block around this code, your application terminates with the exception. This is
probably not a satisfactory user experience. If you add exception-handling code, then your application can:
Warn the user that the application cannot complete all the tasks it needs to.
Clean up any existing objects, so that code that runs after the catch block does not fail.
You could modify the bitmap-saving code as shown below. The added code warns the user that that file was not saved because
of a security denial, and it separates security failures from other file I/O failures, such as incorrect file names. This method does
not create any security holes. The user will either modify security to trust your application, or the application will not run.
Classes, attributes, and enumerations from the System.Security.Permissions namespace support even more control over the
security tasks in your application. If you are writing libraries that may be called from other applications, you will want your
library to verify the permissions of the calling code. For example, you could simply add the following assembly-level attribute
at the top of your code file, or to the AssemblyInfo.vb or AssemblyInfo.cs file. For more information, see
Setting Assembly Attributes.
<Assembly: System.Security.Permissions.FileIOPermissionAttribute( _
System.Security.Permissions.SecurityAction.RequestMinimum, _
Write:="c:\PrettyPicture.bmp")>
The runtime verifies the permission when the assembly loads. If the runtime denies the permission requested, the assembly
fails to load and a security exception is thrown. If you add this attribute to a stand-alone application, the application might not
run. If this attribute appears in a class library, then the library may not load at run time. You would need to add a try/catch
block to the code that calls the class library.
You can also specifically ask for permissions from the runtime, shown below using the Demand method. The runtime may then
grant or deny the demand. The demand is denied by raising a security exception. You might rewrite the code like this to
explicitly demand permission to write the bitmap file:
Try
permission.Demand()
Catch ex As System.Security.SecurityException
' Let the user know the save won't work.
MessageBox.Show("Permission to save the file was denied, " & _
"and the bitmap was not saved.")
Catch ex As System.Exception
' React to other exceptions here.
MessageBox.Show("Other error.")
End Try
Try
b = New Bitmap(100, 100)
b.Save(filename)
Catch ex As System.Exception
MessageBox.Show("Unable to create and save the bitmap.")
End Try
End Sub
Testing
The second step in developing for partial-trust zones is testing in multiple environments, especially from your intranet and the
Internet. This will force the security exceptions to be thrown. One important test is to create a user account on your local
computer that does not have Administrator rights and try running your application with that account.
See Also
Concepts
Introduction to Code Access Security
Other Resources
Code Access Security
Security Namespaces in Visual Studio
Secure Coding Guidelines
Visual Basic Language Concepts
The Copy Project feature of Visual Studio includes the option to deploy an application with a configuration file (Web.config)
that is different from the configuration file used in development. It is likely that the development file has debugging enabled,
which if deployed, would allow users to examine the call stack when an exception is thrown. It is recommended that you deploy
with a separate configuration file that does not allow debugging.
For more information, see ClickOnce Deployment and Security and How to: Debug a Partial Trust Application.
See Also
Reference
The proxy settings on this computer are not configured correctly for Web discovery.
Concepts
Security and Visual Basic Development
Basic Security Practices for Web Applications (Visual Studio)
Security in Windows Forms Overview
Visual Basic Language Concepts
Playing Sounds
The My.Computer.Audio object provides methods for playing sounds.
In This Section
How to: Play Sounds and Wait For Completion in Visual Basic
Demonstrates how to play sounds from a sound file or application resource and wait for them to complete.
How to: Play Sounds in Visual Basic
Demonstrates how to play a sound from a sound file or application resource in the background.
How to: Play Looping Sounds in Visual Basic
Demonstrates how to play a sound from a sound file or application resource as a continuous loop.
How to: Stop Playing Sounds in the Background in Visual Basic
Demonstrates how to stop a sound playing in the background.
How to: Play System Sounds in Visual Basic
Demonstrates how to play a system sound.
Reference
My.Computer.Audio Object
Describes the My.Computer.Audio object.
My.Computer.Audio.Play Method
Describes the Play method.
My.Computer.Audio.PlaySystemSound Method
Describes the PlaySystemSound method.
My.Computer.Audio.Stop Method
Describes the Stop method, which is used to stop a sound that is currently playing.
Visual Basic Language Concepts
How to: Play Sounds and Wait For Completion in Visual Basic
This example plays sounds from a sound file and an application resource using the My.Computer.Audio.Play method, and
waits for them to complete.
Background playing lets the application execute other code while the sound plays. The My.Computer.Audio.Play method
allows the application to play only one background sound at a time; when the application plays a new background sound, it
stops playing the previous background sound.
The My.Computer.Audio class provides methods and properties that can be used to play audio files.
Example
The My.Computer.Audio.Play method plays the specified sound and waits for it to complete.
Check that the file name references a .wav sound file on your system.
VB
Sub PlaySoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.WaitToComplete)
End Sub
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms
Applications > Sound. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
The My.Computer.Audio.Play method plays the specified sound and waits for it to complete.
Check that the application resources include a .wav sound file named Waterfall.
VB
Sub PlaySoundResource()
My.Computer.Audio.Play(My.Resources.Waterfall, _
AudioPlayMode.WaitToComplete)
End Sub
The My.Computer.Audio.Play method plays the specified sound in the background when PlayMode.Background is
specified.
Check that the application resources include a .wav sound file named Waterfall.
VB
Sub PlayBackgroundSoundResource()
My.Computer.Audio.Play(My.Resources.Waterfall, _
AudioPlayMode.Background)
End Sub
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms
Applications > Sound. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
The My.Computer.Audio.Play method plays the specified sound in the background when PlayMode.BackgroundLoop is
specified.
Check that the application resources include a .wav sound file named Waterfall.
VB
Sub PlayLoopingBackgroundSoundResource()
My.Computer.Audio.Play(My.Resources.Waterfall, _
AudioPlayMode.BackgroundLoop)
End Sub
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms
Applications > Sound. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This code example can run only within a Windows Forms or console application. For more information, see
My.Computer.Audio.Stop Method.
See Also
Tasks
How to: Play Sounds in Visual Basic
How to: Determine if a File Exists in Visual Basic
Reference
My.Computer.Audio.Stop Method
Other Resources
Playing Sounds
Visual Basic Language Concepts
See Also
Tasks
How to: Read from the Clipboard in Visual Basic
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
How to: Save an Audio Stream to the Clipboard in Visual Basic
How to: Write to the Clipboard in Visual Basic
Reference
My.Computer.Clipboard.Clear Method
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Forms Applications > Clipboard. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
To read an image from the Clipboard
Use the My.Computer.Clipboard.GetImage method to read an image from the Clipboard. The following code reads an
image from the Clipboard and assigns it to the Image property of Button1. There must be an image stored on the
Clipboard and a Button named Button1 for the example to run correctly.
VB
Button1.Image = My.Computer.Clipboard.GetImage()
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Forms Applications > Clipboard. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
See Also
Tasks
How to: Write to the Clipboard in Visual Basic
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object Members
My.Computer.Clipboard Object
Visual Basic Language Concepts
See Also
Tasks
How to: Read from the Clipboard in Visual Basic
How to: Write to the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsAudio Method
My.Computer.Clipboard.ContainsFileDropList Method
My.Computer.Clipboard.ContainsImage Method
My.Computer.Clipboard.ContainsText Method
My.Computer.Clipboard.ContainsData Method
Visual Basic Language Concepts
VB
My.Computer.Clipboard.SetData("specialFormat", dataChunk)
See Also
Tasks
How to: Read from the Clipboard in Visual Basic
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.SetText Method
My.Computer.Clipboard.SetData Method
My.Computer.Clipboard.SetDataObject Method
TextDataFormat
Visual Basic Language Concepts
See Also
Tasks
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard Object Members
My.Computer.Clipboard.ContainsImage Method
My.Computer.Clipboard.GetImage Method
Visual Basic Language Concepts
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.SetAudio Method
My.Computer.Clipboard.GetAudioStream Method
My.Computer.Clipboard.ContainsAudio Method
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Concepts
Determine the number of ticks that have occurred since the computer was started My.Computer.Clock.TickCount Property
See Also
Reference
My.Computer.Clock Object
My.Computer.Clock Object Members
System.DateTime
Concepts
Formatting Date and Time for a Specific Culture
Visual Basic Language Concepts
Determine the platform type of the computer on which the application is runn My.Computer.Info.OSPlatform Property
ing
Determine the operating system of the computer on which the application is r My.Computer.Info.OSFullName Property
unning
Determine what service packs have been installed on the computer on which t My.Computer.Info.OSVersion Property
he application is running
Determine the installed UICulture on the computer on which the application i My.Computer.Info.InstalledUICulture Property
s running.
See Also
Reference
My.Computer.Info Object
My.Computer.Info Object Members
Visual Basic Language Concepts
Start an application and send it keystrokes How to: Start an Application and Send it Keystrokes (Visual Basic)
See Also
Reference
My.Computer.Keyboard Object
System.Windows.Forms.Keys
Visual Basic Language Concepts
See Also
Reference
My.Computer.Keyboard Object
Concepts
Accessing the Keyboard
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms
Applications > Forms. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
A ArgumentException exception is raised if an application with the requested process identifier cannot be found.
Security
The call to the Shell function requires full trust (SecurityException class).
See Also
Reference
My.Computer.Keyboard.SendKeys Method
Shell Function
AppActivate Function
Visual Basic Language Concepts
Determine whether the left and right mouse buttons have been swapped My.Computer.Mouse.ButtonsSwapped Property
Set how much to scroll when the mouse wheel is rotated one notch. My.Computer.Mouse.WheelScrollLines Property
See Also
Reference
My.Computer.Mouse Object
My.Computer.Mouse Object Members
Visual Basic Language Concepts
VB
My.Computer.Network.UploadFile( _
"C:\My Documents\Order.txt", _
"http://www.cohowinery.com/upload.aspx")
VB
My.Computer.Network.UploadFile( _
"C:\My Documents\Order.txt", _
"http://www.cohowinery.com/upload.aspx", "anonymous", "")
Robust Programming
The following conditions may throw an exception:
The local file path is not valid (ArgumentException).
Authentication failed (SecurityException).
The connection timed out (TimeoutException).
See Also
Tasks
How to: Download a File in Visual Basic
How to: Determine if a Remote Computer is Available in Visual Basic
How to: Parse File Paths in Visual Basic
Reference
My.Computer.Network Object
My.Computer.Network Object Members
My.Computer.Network.UploadFile Method
Visual Basic Language Concepts
Security Note
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be
a Visual Basic source file. Verify all inputs before using the data in your application. The contents of the file may not be what i
s expected, and methods to read from the file may fail.
To download a file
Use the DownloadFile method to download the file, specifying the target file's location as a string or URI and specifying
the location at which to store the file. This example downloads the file WineList.txt from
http://www.cohowinery.com/downloads and saves it to C:\Documents and Settings\All Users\Documents:
VB
My.Computer.Network.DownloadFile _
("http://www.cohowinery.com/downloads/WineList.txt", _
"C:\Documents and Settings\All Users\Documents\WineList.txt")
VB
My.Computer.Network.DownloadFile _
("http://www.cohowinery.com/downloads/WineList.txt", _
"C:\Documents and Settings\All Users\Documents\WineList.txt", False, 500)
Security Note
The FTP protocol used by the DownLoadFile method sends information, including passwords, in plain text and should
not be used for transmitting sensitive information.
See Also
Tasks
How to: Upload a File in Visual Basic
How to: Parse File Paths in Visual Basic
Reference
My.Computer.Network Object
My.Computer.Network Object Members
My.Computer.Network.DownloadFile Method
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in
Connectivity and Networking. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
See Also
Tasks
How to: Determine if a Remote Computer is Available in Visual Basic
Reference
My.Computer.Network Object
My.Computer.Network.IsAvailable Property
Visual Basic Language Concepts
To ping a server
Determine whether the Ping method returns True. This example reports whether or not the server can be pinged, by
determining whether the Ping method returned True. Replace 198.01.01.01 with the IP address, URL, or computer
name of the server to ping
VB
If My.Computer.Network.Ping("198.01.01.01") Then
MsgBox("Server pinged successfully.")
Else
MsgBox("Ping request timed out.")
End If
VB
If My.Computer.Network.Ping("www.cohowinery.com", 1000) Then
MsgBox("Server pinged successfully.")
Else
MsgBox("Ping request timed out.")
End If
See Also
Tasks
How to: Check Connection Status in Visual Basic
Reference
My.Computer.Network Object
My.Computer.Network Object Members
My.Computer.Network.Ping Method
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Connectivity and
Networking. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
A project reference to System.Windows.Forms.dll.
Access to the members of the System.Windows.Forms namespace. Add an Imports statement if you are not fully
qualifying member names in your code. For more information, see Imports Statement.
That your form have a ListBox control named ListBox1.
Robust Programming
You do not have to use the ListBox control to display the available serial port names. Instead, you can use a ComboBox or
other control. If the application does not need a response from the user, you can use a TextBox control to display the
information.
Note
The port names returned by My.Computer.Ports.SerialPortNames may be incorrect when run on Windows 98. To prevent
application errors, use exception handling, such as the Try...Catch...Finally statement or the Using statement, when using th
e port names to open ports.
See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Send Strings to Serial Ports in Visual Basic
How to: Receive Strings From Serial Ports in Visual Basic
Reference
My.Computer.Ports Object
Visual Basic Language Concepts
3. Set the DtrEnable property to indicate that the computer is ready to accept an incoming transmission from the modem.
VB
com1.DtrEnable = True
4. Send the dial command and the phone number to the modem through the serial port by means of the Write method.
VB
com1.Write("ATDT 555-0100" & vbCrLf)
Example
VB
Sub DialModem()
' Dial a number via an attached modem on COM1.
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1", 9600)
com1.DtrEnable = True
com1.Write("ATDT 555-0100" & vbCrLf)
' Insert code to transfer data to and from the modem.
End Using
End Sub
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Connectivity and
Networking. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires a reference to the System namespace.
Robust Programming
This example assumes the modem is connected to COM1. We recommend that your code allow the user to select the desired
serial port from a list of available ports. For more information, see How to: Show Available Serial Ports in Visual Basic.
This example uses a Using block to make sure that the application closes the port even if it throws an exception. For more
information, see Using Statement (Visual Basic).
In this example, the application disconnects the serial port after it dials the modem. Realistically, you will want to transfer data
to and from the modem. For more information, see How to: Receive Strings From Serial Ports in Visual Basic.
See Also
Tasks
How to: Send Strings to Serial Ports in Visual Basic
How to: Receive Strings From Serial Ports in Visual Basic
How to: Show Available Serial Ports in Visual Basic
Reference
My.Computer.Ports Object
System.IO.Ports.SerialPort
Visual Basic Language Concepts
Robust Programming
This example assumes the computer is using COM1; for more flexibility, the code should allow the user to select the desired
serial port from a list of available ports. For more information, see How to: Show Available Serial Ports in Visual Basic.
This example uses a Using block to make sure that the application closes the port even if it throws an exception. For more
information, see Using Statement (Visual Basic).
See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Show Available Serial Ports in Visual Basic
Reference
My.Computer.Ports Object
System.IO.Ports.SerialPort
Visual Basic Language Concepts
2. Determine which serial port should provide the strings. This example assumes it is COM1.
3. Use the My.Computer.Ports.OpenSerialPort method to obtain a reference to the port. For more information, see
My.Computer.Ports.OpenSerialPort Method.
The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates
the serial port should appear within this block, or within a Try...Catch...Finally block.
VB
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1")
End Using
4. Create a Do loop for reading lines of text until no more lines are available.
VB
Do
Loop
5. Use the ReadLine method to read the next available line of text from the serial port.
VB
Dim Incoming As String = com1.ReadLine()
6. Use an If statement to determine if the ReadLine method returns Nothing (which means no more text is available). If it
does return Nothing, exit the Do loop.
VB
If Incoming Is Nothing Then
Exit Do
End If
7. Add an Else block to the If statement to handle the case if the string is actually read. The block appends the string from
the serial port to the return string.
VB
Else
returnStr &= Incoming & vbCrLf
8. Return the string.
VB
Return returnStr
Example
VB
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1")
Do
Dim Incoming As String = com1.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
End Using
Return returnStr
End Function
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Connectivity and
Networking. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example assumes the computer is using COM1.
Robust Programming
This example assumes the computer is using COM1. For more flexibility, the code should allow the user to select the desired
serial port from a list of available ports. For more information, see How to: Show Available Serial Ports in Visual Basic.
This example uses a Using block to make sure that the application closes the port even if it throws an exception. For more
information, see Using Statement (Visual Basic).
See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Send Strings to Serial Ports in Visual Basic
How to: Show Available Serial Ports in Visual Basic
Reference
My.Computer.Ports Object
System.IO.Ports.SerialPort
Visual Basic Language Concepts
Determine whether a value exists in a specific registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic
Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic
Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Delete a registry key How to: Delete a Registry Key in Visual Basic
See Also
Tasks
Walkthrough: Creating a Registry Key and Changing Its Values
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Concepts
Reading from and Writing to the Registry Using My
Security and the Registry
Visual Basic Language Concepts
How to: Create a Registry Key and Set Its Values in Visual Basic
The CreateSubKey method of the My.Computer.Registry object can be used to create a registry key.
Procedure
To create a registry key
Use the CreateSubKey method, specifying which hive to place the key under as well as the name of the key. The
parameter Subkey is not case-sensitive. This example creates the registry key MyTestKey under HKEY_CURRENT_USER.
VB
My.Computer.Registry.CurrentUser.CreateSubKey("MyTestKey")
2. Set the value with the SetValue method. This example sets the string value. "MyTestKeyValue" to "This is a test value".
VB
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\MyTestKey", _
"MyTestKeyValue", "This is a test value.")
Example
This example creates the registry key MyTestKey under HKEY_CURRENT_USER and then sets the string value MyTestKeyValue
to This is a test value.
VB
My.Computer.Registry.CurrentUser.CreateSubKey("MyTestKey")
' Change MyTestKeyValue to This is a test value.
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\MyTestKey", _
"MyTestKeyValue", "This is a test value.")
Robust Programming
Examine the registry structure to find a suitable location for your key. For example, you may want to open the
HKEY_CURRENT_USER\Software key of the current user, and create a key with your company's name. Then add the registry
values to your company's key.
When reading the registry from a Web application, the current user depends on the authentication and impersonation
implemented in the Web application.
It is more secure to write data to the user folder (CurrentUser) rather than to the local computer (LocalMachine).
When you create a registry value, you need to decide what to do if that value already exists. Another process, perhaps a
malicious one, may have already created the value and have access to it. When you put data in the registry value, the data is
available to the other process. To prevent this, use the GetValue method. It returns Nothing if the key does not already exist.
It is not secure to store secrets, such as passwords, in the registry as plain text, even if the registry key is protected by ACLs
(Access Control Lists).
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The user does not have permissions to create registry keys (SecurityException).
The key name exceeds the 255-character limit (ArgumentException).
The key is closed (IOException).
The registry key is read-only (UnauthorizedAccessException).
Security
To run this process, your assembly requires a privilege level granted by the RegistryPermission class. If you are running in a
partial-trust context, the process might throw an exception due to insufficient privileges. Similarly, the user must have the
correct ACLs for creating or writing to settings. For example, a local application that has the code access security permission
might not have operating system permission. For more information, see Code Access Security Basics.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Walkthrough: Creating a Registry Key and Changing Its Values
Reference
My.Computer.Registry Object
My.Computer.Registry.CurrentUser Property
CreateSubKey
Concepts
Common Registry Tasks
Code Access Security Basics
Visual Basic Language Concepts
Robust Programming
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The user does not have permissions to create registry keys (SecurityException).
The key name exceeds the 255-character limit (ArgumentException).
The key is closed (IOException).
The registry key is read-only (UnauthorizedAccessException).
Security
To run this process, your assembly requires a privilege level granted by the RegistryPermission class. If you are running in a
partial-trust context, the process might throw an exception due to insufficient privileges. Similarly, the user must have the
correct access control lists for creating or writing to settings. For example, a local application that has the code access security
permission might not have operating system permission. For more information, see Code Access Security Basics.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Walkthrough: Creating a Registry Key and Changing Its Values
Reference
My.Computer.Registry Object
My.Computer.Registry.CurrentUser Property
Concepts
Code Access Security Basics
Common Registry Tasks
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Operating System > Registry. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The registry holds top-level, or root, keys that are used to store data. For instance, the HKEY_LOCAL_MACHINE root key is used
for storing machine-level settings used by all users, while HKEY_CURRENT_USER is used for storing data specific to an
individual user.
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The user does not have permissions to read from registry keys (SecurityException).
The key name exceeds the 255-character limit (ArgumentException).
Security
To run this process, your assembly requires a privilege level granted by the RegistryPermission class. If you are running in a
partial-trust context, the process might throw an exception due to insufficient privileges. Similarly, the user must have the
correct ACLs for creating or writing to settings. For example, a local application that has the code access security permission
might not have operating system permission. For more information, see Code Access Security Basics.
See Also
Tasks
Walkthrough: Creating a Registry Key and Changing Its Values
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
RegistryHive
Concepts
Common Registry Tasks
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Operating System > Registry. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
User preference data should be written to the Microsoft.Win32.Registry.CurrentUser hive.
It is not secure to store secrets, such as passwords, in the registry as plain text, even if the registry key is protected by access
control lists (ACLs).
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The key name exceeds the 255-character limit (ArgumentException).
The specified hive is not valid (ArgumentException).
The key is closed (IOException).
The path is not valid (IOException).
The registry key is read-only (UnauthorizedAccessException).
Security
To run this process, your assembly requires a privilege level granted by the RegistryPermission class. If you are running in a
partial-trust context, the process might throw an exception due to insufficient privileges. Similarly, the user must have the
correct ACLs for creating or writing to settings. For example, a local application that has the code access security permission
might not have operating system permission. For more information, see Code Access Security Basics.
See Also
Tasks
How to: Read a Value from a Registry Key in Visual Basic
Walkthrough: Creating a Registry Key and Changing Its Values
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object Members
My.Computer.Registry.SetValue Method
Concepts
Common Registry Tasks
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Operating System > Registry. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The DeleteSubKey method returns an empty string if the key/value pair does not exist.
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The user does not have permissions to delete registry keys (SecurityException).
The key name exceeds the 255-character limit (ArgumentException).
The registry key is read-only (UnauthorizedAccessException).
Security
Registry calls fail if either sufficient run-time permissions are not granted (RegistryPermission) or if the user does not have the
correct access (as determined by the ACLs) for creating or writing to settings. For example, a local application that has the code
access security permission might not have operating system permission.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Walkthrough: Creating a Registry Key and Changing Its Values
Reference
DeleteSubKey
DeleteSubKey
RegistryKey
Concepts
Security and the Registry
Common Registry Tasks
Visual Basic Language Concepts
Delete a registry key How to: Delete a Registry Key in Visual Basic
Determine whether a value exists How to: Determine if a Value Exists in a Registry Key in Visual Basic
Read a value How to: Read a Value from a Registry Key in Visual Basic
CurrentUser Contains information about the current user preferences, such as environmental variables.
DynData Contains dynamic registry data, such as that used by Virtual Device Drivers.
LocalMachine Contains five subkeys (Hardware, SAM, Security, Software, and System) that hold the configuration data for t
he local computer.
The following code reads, increments, and then writes a string to HKEY_CURRENT_USER.
VB
Dim regVersion As Microsoft.Win32.RegistryKey
regVersion = Microsoft.Win32.Registry.CurrentUser.OpenSubKey( _
"SOFTWARE\\Microsoft\\TestApp\\1.0", True)
If regVersion Is Nothing Then
' Key doesn't exist; create it.
regVersion = Microsoft.Win32.Registry.CurrentUser.CreateSubKey( _
"SOFTWARE\\Microsoft\\TestApp\\1.0")
End If
Dim intVersion As Integer = 0
If (Not regVersion Is Nothing) Then
intVersion = regVersion.GetValue("Version", 0)
intVersion = intVersion + 1
regVersion.SetValue("Version", intVersion)
regVersion.Close()
End If
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
SystemException Class
ApplicationException Class
My.Computer.Registry Object
Concepts
Structured Exception Handling Overview for Visual Basic
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Concepts
4. Test your application by entering the name of an existing subkey into the showSubKey textbox. When the
ReadValueButton is clicked, the Value text box displays the value.
3. Test your application by entering a new value for a subkey in the Value text box and then confirming that the value has
been changed with the button named ReadValueButton.
3. Test your application by entering a new key name in the showSubKey text box and using the Registry Editor to confirm
that your key has been created.
3. Test your code by deleting a subkey and using the Registry Editor to confirm that the key was deleted.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Reading from and Writing to the Registry Using the Microsoft.Win32 Namespace
Visual Basic Language Concepts
Create Create
NoAccess No access
Read Read
Write Write
See Also
Tasks
Walkthrough: Creating a Registry Key and Changing Its Values
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
My.Computer.Registry Object Members
Concepts
Common Registry Tasks
Reading from and Writing to the Registry Using My
Visual Basic Language Concepts
SecurityException Make sure you have read and write permissions from RegistryPermissionAccess.
UnauthorizedAccessException Make sure the key was opened for writing if attempting to write to it.
See Also
Tasks
Walkthrough: Creating a Registry Key and Changing Its Values
Reference
My.Computer.Registry Object
Concepts
Common Registry Tasks
Reading from and Writing to the Registry Using My
Reading from and Writing to the Registry Using the Microsoft.Win32 Namespace
Security and the Registry
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Operating System > Processes. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
An Imports statement specifying the System.Diagnostics namespace. For more information, see Imports Statement.
A running instance of the Notepad (Notepad.exe) application.
Security
Because this example abruptly terminates processes, data loss could occur if it is used with some applications.
The Kill method requires full trust (SecurityException class).
See Also
Reference
Process
Other Resources
Accessing Other Processes
Visual Basic Language Concepts
Updating an Application
The My.Application.Deployment property can be used to check for available updates to the application. If the application
was deployed as a ClickOnce application, the example displays appropriate user interface text.
In This Section
This table shows tasks associated with the My.Application.Deployment property and points to topics showing how to
accomplish each task.
To See
Check for application updates How to: Check for ClickOnce Application Updates
See Also
Reference
My.Application.Deployment Property
My.Application Object
Visual Basic Language Concepts
Only applications that are deployed using ClickOnce can be updated using the My.Application.Deployment object. For more
information on deploying a ClickOnce application, see How to: Publish a ClickOnce Application.
See Also
Tasks
How to: Download ClickOnce Application Updates
Reference
My.Application.Deployment Property
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Application—
Compiling, Resources, and Settings. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Only applications that are deployed using ClickOnce can be updated using the My.Application.Deployment object. For more
information on deploying a ClickOnce application, see How to: Publish a ClickOnce Application.
See Also
Tasks
How to: Check for ClickOnce Application Updates
Reference
My.Application.Deployment Property
Visual Basic Language Concepts
Write exception information to the application's logs How to: Log Exceptions in Visual Basic
.
Write trace information to the application's logs whe How to: Log Messages When the Application Starts or Shuts Down
n the application starts and shuts down.
Configure My.Application.Log to write informatio How to: Write Event Information to a Text File
n to a text file.
Configure My.Application.Log to write informatio How to: Write to an Application Event Log
n to an event log.
Change where My.Application.Log writes informat Walkthrough: Changing Where My.Application.Log Writes Information
ion.
Determine where My.Application.Log writes infor Walkthrough: Determining Where My.Application.Log Writes Information
mation.
Create a custom log listener for My.Application.Lo Walkthrough: Creating Custom Log Listeners
g.
Filter the output of the My.Application.Log logs. Walkthrough: Filtering My.Application.Log Output
See Also
Tasks
Troubleshooting: Log Listeners
Reference
My.Application.Log Object
My.Log Object
Concepts
Working with Application Logs in Visual Basic
Logging and Tracing in the .NET Framework with Visual Basic
Visual Basic Language Concepts
Security
Make sure the data you write to the log does not include sensitive information such as user passwords. For more information,
see Working with Application Logs in Visual Basic.
See Also
Tasks
How to: Log Exceptions in Visual Basic
Walkthrough: Determining Where My.Application.Log Writes Information
Walkthrough: Changing Where My.Application.Log Writes Information
Walkthrough: Filtering My.Application.Log Output
Reference
My.Application.Log Object
My.Log Object
WriteEntry Method (My.Application.Log and My.Log)
WriteException Method (My.Application.Log and My.Log)
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Concepts
3. Put the code that could generate an exception in the Try block.
Uncomment the Dim and MsgBox lines to cause a NullReferenceException exception.
VB
' Code that might generate an exception goes here.
' For example:
' Dim x As Object
' MsgBox(x.ToString)
4. In the Catch block, use the My.Application.Log.WriteException method to write the exception information.
VB
My.Application.Log.WriteException(ex, _
TraceEventType.Error, _
"Exception in ExceptionLogTest " & _
"with argument " & fileName & ".")
Example
This example shows the complete code for logging a handled exception.
VB
Public Sub ExceptionLogTest(ByVal fileName As String)
Try
' Code that might generate an exception goes here.
' For example:
' Dim x As Object
' MsgBox(x.ToString)
Catch ex As Exception
My.Application.Log.WriteException(ex, _
TraceEventType.Error, _
"Exception in ExceptionLogTest " & _
"with argument " & fileName & ".")
End Try
End Sub
The next example shows the complete code for logging an unhandled exception. You can use the Project Designer to access
the application events in the Code Editor. For more information, see How to: Handle Application Events (Visual Basic).
VB
Private Sub MyApplication_UnhandledException( _
ByVal sender As Object, _
ByVal e As ApplicationServices.UnhandledExceptionEventArgs _
) Handles Me.UnhandledException
My.Application.Log.WriteException(e.Exception, _
TraceEventType.Critical, _
"Application shut down at " & _
My.Computer.Clock.GmtTime.ToString)
End Sub
See Also
Tasks
How to: Write Log Messages
Walkthrough: Determining Where My.Application.Log Writes Information
Walkthrough: Changing Where My.Application.Log Writes Information
Reference
My.Application.Log Object
My.Log Object
WriteEntry Method (My.Application.Log and My.Log)
WriteException Method (My.Application.Log and My.Log)
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Concepts
Example
You can use the Project Designer to access the application events in the Code Editor. For more information, see
How to: Handle Application Events (Visual Basic).
VB
Private Sub MyApplication_Startup( _
ByVal sender As Object, _
ByVal e As ApplicationServices.StartupEventArgs _
) Handles Me.Startup
My.Application.Log.WriteEntry("Application started at " & _
My.Computer.Clock.GmtTime.ToString)
End Sub
Private Sub MyApplication_Shutdown( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
) Handles Me.Shutdown
My.Application.Log.WriteEntry("Application shut down at " & _
My.Computer.Clock.GmtTime.ToString)
End Sub
See Also
Tasks
How to: Handle Application Events (Visual Basic)
Reference
My.Log Object
My.Application.Log Object
WriteEntry Method (My.Application.Log and My.Log)
WriteException Method (My.Application.Log and My.Log)
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Concepts
<add name="EventLog"/>
4. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.
5. Add this element to that <sharedListeners> section:
<add name="EventLog"
type="System.Diagnostics.EventLogTraceListener, System, Version=2.0.0.0, Culture=n
eutral, PublicKeyToken=b77a5c561934e089"
initializeData="APPLICATION_NAME"/>
4. Locate the <sharedListeners> section in the <system.diagnostics> section, nested under the top-level
<configuration> section.
<add name="FileLogListener"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
initializeData="FileLogListenerWriter"
location="Custom"
customlocation="c:\temp\" />
You can change the behavior of the log and the trace listeners by changing the application's configuration file. The following
diagram shows the correspondence between the parts of the log and the configuration file.
<configuration>
<system.diagnostics>
<sources>
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"
/>
</sharedListeners>
</system.diagnostics>
</configuration>
5. For many types of shared listeners, the listener's initialization data includes a description of where the listener directs the
data:
A Microsoft.VisualBasic.Logging.FileLogTraceListener listener writes to a file log, as described in the introduction.
A System.Diagnostics.EventLogTraceListener listener writes information to the computer event log specified by the
initializeData parameter. To view an event log, you can use Server Explorer or Windows Event Viewer. For
more information, see How to: Work with Event Logs in Server Explorer or How to: Launch Event Viewer.
The System.Diagnostics.DelimitedListTraceListener and System.Diagnostics.XmlWriterTraceListener listeners write
to the file specified in the initializeData parameter.
A System.Diagnostics.ConsoleTraceListener listener writes to the command-line console.
For information about where other types of log listeners write information, consult that type's documentation.
See Also
Tasks
How to: Log Exceptions in Visual Basic
How to: Write Log Messages
Walkthrough: Changing Where My.Application.Log Writes Information
How to: Work with Event Logs in Server Explorer
How to: Launch Event Viewer
Troubleshooting: Log Listeners
Reference
My.Application.Log Object
My.Log Object
DefaultTraceListener
EventLogTraceListener
DelimitedListTraceListener
XmlWriterTraceListener
ConsoleTraceListener
System.Diagnostics
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Concepts
4. Uncomment the log listeners that you want to receive Log messages.
5. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.
6. Add these elements to that <sharedListeners> section.
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
initializeData="FileLogWriter" />
<add name="EventLog"
type="System.Diagnostics.EventLogTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="sample application"/>
<add name="Delimited"
type="System.Diagnostics.DelimitedListTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="c:\temp\sampleDelimitedFile.txt"
delimiter=";;;"
traceOutputOptions="DateTime" />
<add name="XmlWriter"
type="System.Diagnostics.XmlWriterTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="c:\temp\sampleLogFile.xml" />
<add name="Console"
type="System.Diagnostics.ConsoleTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="true" />
7. The content of the app.config file should be similar to the following XML:
To reconfigure a listener
1. Locate the listener's <add> element from the <sharedListeners> section.
2. The type attribute gives the name of the listener type. This type must inherit from the TraceListener class. Use the
strongly named type name to ensure that the right type is used. For more information, see the "To reference a strongly
named type" section below.
Some types that you can use are:
A Microsoft.VisualBasic.Logging.FileLogTraceListener listener, which writes to a file log.
A System.Diagnostics.EventLogTraceListener listener, which writes information to the computer event log specified
by the initializeData parameter.
The System.Diagnostics.DelimitedListTraceListener and System.Diagnostics.XmlWriterTraceListener listeners, which
write to the file specified in the initializeData parameter.
A System.Diagnostics.ConsoleTraceListener listener, which writes to the command-line console.
For information about where other types of log listeners write information, consult that type's documentation.
3. When the application creates the log-listener object, it passes the initializeData attribute as the constructor parameter.
The meaning of the initializeData attribute depends on the trace listener.
4. After creating the log listener, the application sets the listener's properties. These properties are defined by the other
attributes in the <add> element. For more information on the properties for a particular listener, see the documentation
for that listener's type.
See Also
Tasks
How to: Write Event Information to a Text File
How to: Write to an Application Event Log
Reference
My.Application.Log Object
My.Log Object
TraceListener
Microsoft.VisualBasic.Logging.FileLogTraceListener
System.Diagnostics.EventLogTraceListener
Visual Basic Language Concepts
In the example above, the second call to the WriteEntry Method (My.Application.Log and My.Log) and the call to the
WriteException Method (My.Application.Log and My.Log) produces log output, while the first and last calls to the WriteEntry
method do not. This is because the severity levels of WriteEntry and WriteException are "Information" and "Error", both of
which are allowed by the My.Application.Log object's default log filtering. However, events with "Start" and "Stop" severity
levels are prevented from producing log output.
Filtering for All My.Application.Log Listeners
The My.Application.Log object uses a SourceSwitch named DefaultSwitch to control which messages it passes from the
WriteEntry and WriteException methods to the log listeners. You can configure DefaultSwitch in the application's
configuration file by setting its value to one of the SourceLevels enumeration values. By default, its value is "Information".
This table shows the severity level required for Log to write a message to the listeners, given a particular DefaultSwitch
setting.
DefaultSwitch Value Message severity required for output
Critical Critical
This table explains the log output shown in the previous example: with the default DefaultSwitch setting of "Information", only
the second call to the WriteEntry method and the call to the WriteException method produce log output.
To log only activity tracing events
1. Right-click app.config in the Solution Explorer and select Open.
-or-
If there is no app.config file:
a. On the Project menu, choose Add New Item.
b. From the Add New Item dialog box, choose Application Configuration File.
c. Click Add.
2. Locate the <switches> section, which is in the <system.diagnostics> section, which is in the top-level <configuration>
section.
3. Find the element that adds DefaultSwitch to the collection of switches. It should look similar to this element:
<add name="DefaultSwitch" value="Information" />
This example demonstrates how to configure filtering for a new debug listener and add it to the Log object. The default debug
listener should be removed from the Log object, so it is clear that the debug messages come from the new debug listener.
To log only activity-tracing events
1. Right-click app.config in the Solution Explorer and choose Open.
-or-
If there is no app.config file:
a. On the Project menu, choose Add New Item.
b. From the Add New Item dialog box, choose Application Configuration File.
c. Click Add.
2. Right-click app.config in Solution Explorer. Choose Open.
3. Locate the <listeners> section, in the <source> section with the name attribute "DefaultSource", which is under the
<sources> section. The <sources> section is under the <system.diagnostics> section, in the top-level <configuration>
section.
4. Add this element to the <listeners> section:
5. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.
6. Add this element to that <sharedListeners> section:
<add name="NewDefault"
type="System.Diagnostics.DefaultTraceListener,
System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089,
processorArchitecture=MSIL">
<filter type="System.Diagnostics.EventTypeFilter"
initializeData="Error" />
</add>
The EventTypeFilter filter takes one of the SourceLevels enumeration values as its initializeData attribute.
7. The content of the app.config file should be similar to the following XML:
The application writes less information to the application's debug output because of the more restrictive filtering.
Default Error 2 Error
5. The content of the app.config file should be similar to the following XML:
<Security.Permissions.HostProtection(Synchronization:=True)> _
Public Overloads Overrides Sub Write(ByVal message As String)
MsgBox("Write: " & message)
End Sub
<Security.Permissions.HostProtection(Synchronization:=True)> _
Public Overloads Overrides Sub WriteLine(ByVal message As String)
MsgBox("WriteLine: " & message)
End Sub
End Class
The Write and WriteLine methods, required by the base class, call MsgBox to display their input.
The HostProtectionAttribute attribute is applied to the Write and WriteLine methods so that their attributes match the
base class methods. The HostProtectionAttribute attribute allows the host that runs the code to determine that the
code exposes host-protection synchronization.
Note
The HostProtectionAttribute attribute is effective only on unmanaged applications that host the common language r
untime and that implement host protection, such as SQL Server.
To ensure that My.Application.Log uses your log listener, you should strongly name the assembly that contains your log
listener.
The next procedure provides some simple steps for creating a strongly named log-listener assembly. For more information,
see Creating and Using Strong-Named Assemblies.
To strongly name the log-listener assembly
1. Have a project selected in Solution Explorer. On the Project menu, choose Properties. For more information, see
Introduction to the Project Designer.
2. Click the Signing tab.
3. Select the Sign the assembly box.
4. Select <New> from the Choose a strong name key file drop-down list.
The Create Strong Name Key dialog box opens.
5. Provide a name for the key file in the Key file name box.
6. Enter a password in the Enter password and Confirm password boxes.
7. Click OK.
8. Rebuild the application.
Adding the Listener
Now that the assembly has a strong name, you need to determine the strong name of the listener so that My.Application.Log
uses your log listener.
The format of a strongly named type is as follows.
<type name>, <assembly name>, <version number>, <culture>, <strong name>
To determine the strong name of the listener
The following code shows how to determine the strongly named type name for SimpleListener.
VB
Public Sub DisplaySimpleListenerStrongName()
Dim t As Type = GetType(SimpleListener)
MsgBox(t.FullName & ", " & t.Assembly.FullName)
End Sub
4. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.
5. Add this element to that <sharedListeners> section:
2. Create a function that returns a string consisting of information for each of the log's listeners.
VB
Function GetListeners(ByVal listeners As TraceListenerCollection) As String
Dim ret As String = ""
For Each listener As TraceListener In listeners
ret &= listener.Name
Dim listenerType As Type = listener.GetType
If listenerType Is GetType(DefaultTraceListener) Then
Dim tmp As DefaultTraceListener = _
DirectCast(listener, DefaultTraceListener)
ret &= ": Writes to the debug output."
ElseIf listenerType Is GetType(Logging.FileLogTraceListener) Then
Dim tmp As Logging.FileLogTraceListener = _
DirectCast(listener, Logging.FileLogTraceListener)
ret &= ": Log filename: " & tmp.FullLogFileName
ElseIf listenerType Is GetType(EventLogTraceListener) Then
Dim tmp As EventLogTraceListener = _
DirectCast(listener, EventLogTraceListener)
ret &= ": Event log name: " & tmp.EventLog.Log
ElseIf listenerType Is GetType(XmlWriterTraceListener) Then
Dim tmp As Diagnostics.XmlWriterTraceListener = _
DirectCast(listener, XmlWriterTraceListener)
ret &= ": XML log"
ElseIf listenerType Is GetType(ConsoleTraceListener) Then
Dim tmp As ConsoleTraceListener = _
DirectCast(listener, ConsoleTraceListener)
ret &= ": Console log"
ElseIf listenerType Is GetType(DelimitedListTraceListener) Then
Dim tmp As DelimitedListTraceListener = _
DirectCast(listener, DelimitedListTraceListener)
ret &= ": Delimited log"
Else
ret &= ": Unhandeled log type: " & _
listenerType.ToString
End If
ret &= vbCrLf
Next
Return ret
End Function
3. Pass the collection of the log's trace listeners to the GetListeners function, and display the return value.
VB
Dim ListenerCollection As TraceListenerCollection
ListenerCollection = My.Application.Log.TraceSource.Listeners
Dim ListenersText As String = GetListeners(ListenerCollection)
MsgBox(ListenersText)
Determine the application's command-line arguments How to: Access Command-Line Arguments (Visual Basic)
Check if the application started with the string "/batch" as an arg How to: Enable a Batch Mode for Window Forms Applications
ument
Use the events provided by the Visual Basic Application model t How to: Run Code When the Application Starts or Ends
o run code when the application starts or ends
Download and install the latest version of a ClickOnce applicatio How to: Download ClickOnce Application Updates
n
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application Object
My.Application.Log Object
My.Application.Info Object
Concepts
Overview of the Visual Basic Application Model
Logging Information from the Application
Visual Basic Language Concepts
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is de
scribed in Help, depending on your active settings or edition. This Help page was written with General Development Settin
gs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
VB
End Sub
4. Iterate through the application's command-line arguments, and set the Cancel property of the e object to True if one of
the arguments is /batch.
When the Cancel property is set to True, the startup form does not start.
VB
For Each s As String In My.Application.CommandLineArgs
If s.ToLower = "/batch" Then
' Stop the start form from loading.
e.Cancel = True
End If
Next
5. If the Cancel property of the e object is set to True, call the main routine for windowless operation.
VB
If e.Cancel Then
' Call the main routine for windowless operation.
Dim c As New BatchApplication
c.Main()
End If
Example
VB
Private Sub MyApplication_Startup( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs _
) Handles Me.Startup
For Each s As String In My.Application.CommandLineArgs
If s.ToLower = "/batch" Then
' Stop the start form from loading.
e.Cancel = True
End If
Next
If e.Cancel Then
' Call the main routine for windowless operation.
Dim c As New BatchApplication
c.Main()
End If
End Sub
Class BatchApplication
Sub Main()
' Insert code to run without a graphical user interface.
End Sub
End Class
See Also
Tasks
How to: Access Command-Line Arguments (Visual Basic)
Reference
My.Application Object
My.Application.CommandLineArgs Property
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Concepts
See Also
Tasks
How to: Enable a Batch Mode for Window Forms Applications
Reference
My.Application.CommandLineArgs Property
Structure of a Visual Basic Program
Visual Basic Language Concepts
Get the user's domain name, if the application uses Wi How to: Determine the User's Domain
ndows authentication
See Also
Reference
My.User Object
Other Resources
Authentication and Authorization in the .NET Framework with Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Determine the User's Domain
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User.Name Property
Concepts
Accessing User Data
Visual Basic Language Concepts
See Also
Tasks
How to: Determine the User's Domain
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User.IsInRole Method
Concepts
Accessing User Data
Visual Basic Language Concepts
See Also
Tasks
How to: Determine a User's Login Name
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User.Name Property
Concepts
Accessing User Data
Visual Basic Language Concepts
Display the titles of all the application's open forms. How to: Access All Open Forms of an Application
Update the splash screen with status information as the application st My.Application.SplashScreen Property
arts.
See Also
Reference
My.Forms Object
My.Application.OpenForms Property
My.Application.SplashScreen Property
Visual Basic Language Concepts
See Also
Tasks
How to: Access All Open Forms of an Application
Reference
My.Forms Object
Concepts
Accessing Application Forms
Visual Basic Language Concepts
Try
For Each f As Form In My.Application.OpenForms
' Use a thread-safe method to get all form titles.
formTitles.Add(GetFormTitle(f))
Next
Catch ex As Exception
formTitles.Add("Error: " & ex.Message)
End Try
Form1.ListBox1.DataSource = formTitles
End Sub
See Also
Tasks
How to: Make Thread-Safe Calls to Windows Forms Controls
Reference
My.Application.OpenForms Property
Visual Basic Language Concepts
Call a Web service asynchronously and handle an event when it completes How to: Call a Web Service Asynchronously
See Also
Reference
My.WebServices Object
Visual Basic Language Concepts
http://www.xmethods.net/sd/2001/DemoTemperatureService.wsdl
For more information, see How to: Access an XML Web Service in Managed Code.
2. Add an event handler for the getTempCompleted event:
Note
You cannot use the Handles statement to associate an event handler with the My.WebServices object's events.
3. Add a field to track if the event handler has been added to the getTempCompleted event:
4. Add a method to add the event handler to the getTempCompleted event, if necessary, and to call the getTempAsynch
method:
See Also
Tasks
How to: Access an XML Web Service in Managed Code
Reference
My.WebServices Object
Concepts
Accessing Application Web Services
Visual Basic Language Concepts
Retrieve an icon resource How to: Retrieve Icon Resources in Visual Basic
Retrieve an image resource How to: Retrieve Image Resources in Visual Basic
Retrieve a string resource How to: Retrieve String Resources in Visual Basic
Retrieve a localized resource How to: Retrieve Localized Resources in Visual Basic
See Also
Reference
My.Resources Object
Other Resources
Managing Application Resources
Visual Basic Language Concepts
VB
Sub PlayFormGreeting()
My.Computer.Audio.Play(My.Resources.Form1Greeting, _
AudioPlayMode.Background)
End Sub
For this example to work, your application must have an audio resource named Form1Greeting in the application's resource
file. For more information, see How to: Add or Remove Resources.
The My.Computer.Audio.Play method is available only for Windows Forms applications. For more information, see
My.Computer.Audio.Play Method.
See Also
Tasks
How to: Retrieve String Resources in Visual Basic
How to: Retrieve Image Resources in Visual Basic
How to: Retrieve Icon Resources in Visual Basic
How to: Retrieve Localized Resources in Visual Basic
Reference
My.Resources Object
My.Computer.Audio.Play Method
Other Resources
Managing Application Resources
Visual Basic Language Concepts
For this example to work, your application must have an icon named Form1Icon in the application's resource file. For more
information, see How to: Add or Remove Resources.
See Also
Tasks
How to: Retrieve String Resources in Visual Basic
How to: Retrieve Image Resources in Visual Basic
How to: Retrieve Audio Resources in Visual Basic
How to: Retrieve Localized Resources in Visual Basic
Reference
My.Resources Object
Other Resources
Managing Application Resources
Visual Basic Language Concepts
For this example to work, your application must have an image resource named Form1Background in the application's resource
file. For more information, see How to: Add or Remove Resources.
See Also
Tasks
How to: Retrieve String Resources in Visual Basic
How to: Retrieve Icon Resources in Visual Basic
How to: Retrieve Audio Resources in Visual Basic
How to: Retrieve Localized Resources in Visual Basic
Reference
My.Resources Object
Other Resources
Managing Application Resources
Visual Basic Language Concepts
For this example to work, your application must have a string named Form1Title in the application's resource file. For more
information, see How to: Add or Remove Resources.
See Also
Tasks
How to: Retrieve Image Resources in Visual Basic
How to: Retrieve Icon Resources in Visual Basic
How to: Retrieve Audio Resources in Visual Basic
How to: Retrieve Localized Resources in Visual Basic
Reference
My.Resources Object
Other Resources
Managing Application Resources
Visual Basic Language Concepts
For this example to work, your application must have a string named Message in the application's resource file, and the
application should have the French-culture version of that resource file, Resources.fr-FR.resx. For more information, see
How to: Add or Remove Resources.
If the application does not have the French-culture version of that resource file, the My.Resource object retrieves the resource
from the default-culture resource file.
See Also
Tasks
How to: Retrieve String Resources in Visual Basic
Reference
My.Resources Object
Other Resources
Managing Application Resources
Visual Basic Language Concepts
Display application and user settings in a property grid How to: Create Property Grids for User Settings in Visual Basic
Save updated user setting values How to: Persist User Settings in Visual Basic
Determine the values of user settings How to: Read Application Settings in Visual Basic
See Also
Reference
My.Settings Object
Other Resources
Managing Application Settings
Visual Basic Language Concepts
How to: Create Property Grids for User Settings in Visual Basic
You can create a property grid for user settings by populating a PropertyGrid control with the user setting properties of the
My.Settings object.
Note
In order for this example to work, your application must have its user settings configured. For information on adding user set
tings, see How to: Add or Remove Application Settings.
The My.Settings object exposes each setting as a property. The property name is the same as the setting name, and the
property type is the same as the setting type. The setting's Scope determines if the property is read-only; the property for an
Application-scope setting is read-only, while the property for a User-scope setting is read-write. For more information, see
My.Settings Object.
Note
You cannot change or save the values of application-scope settings at run time. Application-scope settings can be changed o
nly when creating the application (through the Project Designer) or by editing the application's configuration file. For more
information, see Managing Application Settings.
This example uses a PropertyGrid control to access the user-setting properties of the My.Settings object. By default, the
PropertyGrid shows all the properties of the My.Settings object. However, the user-setting properties have the
UserScopedSettingAttribute attribute. This example sets the BrowsableAttributes property of the PropertyGrid to
UserScopedSettingAttribute to display only the user-setting properties.
To add a user setting property grid
1. Add the PropertyGrid control from the Toolbox to the design surface for your application, assumed here to be Form1.
Note
To show only the application-scope settings, use the ApplicationScopedSettingAttribute attribute instead of UserScope
dSettingAttribute.
Robust Programming
The application saves the user settings when the application shuts down. To save the settings immediately, call the
My.Settings.Save method. For more information, see How to: Persist User Settings in Visual Basic.
See Also
Tasks
How to: Read Application Settings in Visual Basic
How to: Change User Settings in Visual Basic
How to: Persist User Settings in Visual Basic
How to: Add or Remove Application Settings
Reference
My.Settings Object
Other Resources
Managing Application Settings
Visual Basic Language Concepts
Example
This example changes the value of the LastChanged user setting and saves that change by calling the My.Settings.Save
method.
VB
Sub ChangeAndPersistSettings()
My.Settings.LastChanged = Today
My.Settings.Save()
End Sub
For this example to work, your application must have a LastChanged user setting, of type Date. For more information, see
How to: Add or Remove Application Settings.
See Also
Tasks
How to: Read Application Settings in Visual Basic
How to: Change User Settings in Visual Basic
How to: Create Property Grids for User Settings in Visual Basic
How to: Add or Remove Application Settings
Reference
My.Settings Object
Other Resources
Managing Application Settings
Visual Basic Language Concepts
Example
This example changes the value of the Nickname user setting.
VB
Sub ChangeNickname(ByVal newNickname As String)
My.Settings.Nickname = newNickname
End Sub
For this example to work, your application must have a Nickname user setting, of type String. For more information, see
How to: Add or Remove Application Settings.
The application saves the user settings when the application shuts down. To save the settings immediately, call the
My.Settings.Save method. For more information, see How to: Persist User Settings in Visual Basic.
See Also
Tasks
How to: Read Application Settings in Visual Basic
How to: Persist User Settings in Visual Basic
How to: Create Property Grids for User Settings in Visual Basic
How to: Add or Remove Application Settings
Reference
My.Settings Object
Other Resources
Managing Application Settings
Visual Basic Language Concepts
For this example to work, your application must have a Nickname setting, of type String. For more information, see
How to: Add or Remove Application Settings.
See Also
Tasks
How to: Change User Settings in Visual Basic
How to: Persist User Settings in Visual Basic
How to: Create Property Grids for User Settings in Visual Basic
How to: Add or Remove Application Settings
Reference
My.Settings Object
Other Resources
Managing Application Settings
Visual Basic Language Concepts
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The file does not exist (FileNotFoundException).
The file is in use by another process or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
There is not enough memory to write the string to buffer (OutOfMemoryException).
The user lacks necessary permissions to view the path (SecurityException).
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a
Visual Basic source file.
Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to
read from the file may fail.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.ReadAllText Method
Concepts
File Encodings
Other Resources
Reading from Files in Visual Basic
Visual Basic Language Concepts
VB
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser _
("C:\TestFolder\test.txt")
2. Define the TextField type and delimiter. The following code defines the TextFieldType property as Delimited and the
delimiter as ",".
VB
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
3. Loop through the fields in the file. If any lines are corrupt, report an error and continue parsing. The following code loops
through the file, displaying each field in turn and reporting any fields that are formatted incorrectly.
VB
4. Close the While and Using blocks with End While and End Using.
VB
End While
End Using
Example
This example reads from the file test.txt.
VB
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using
Robust Programming
The following conditions may cause an exception:
A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line
causing the exception, while the TextFieldParser.ErrorLine Property is assigned the text contained in the line.
The specified file does not exist (FileNotFoundException).
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
The path is too long (PathTooLongException).
The user does not have sufficient permissions to access the file (UnauthorizedAccessException).
See Also
Tasks
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser Object
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Concepts
VB
Using Reader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser _
("C:\TestFolder\test.log")
2. Define the TextFieldType property as FixedWidth, defining the width and format. The following code defines the
columns of text; the first is 5 characters wide, the second 10, the third 11, and the fourth is of variable width.
VB
Reader.TextFieldType = _
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(5, 10, 11, -1)
3. Loop through the fields in the file. If any lines are corrupted, report an error and continue parsing.
VB
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As _
Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
4. Close the While and Using blocks with End While and End Using.
VB
End While
End Using
Example
This example reads from the file test.log.
VB
Using Reader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\TestFolder\test.log")
Reader.TextFieldType = _
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(5, 10, 11, -1)
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using
Robust Programming
The following conditions may cause an exception:
A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line
causing the exception, while the TextFieldParser.ErrorLine Property is assigned to the text contained in the line.
The specified file does not exist (FileNotFoundException).
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
The path is too long (PathTooLongException).
The user does not have sufficient permissions to access the file (UnauthorizedAccessException).
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser Object
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Concepts
How to: Read From Text Files with Multiple Formats in Visual
Basic
The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs. You can process a
file with multiple formats by using the PeekChars method to determine the format of each line as you parse through the file.
To parse a text file with multiple formats
1. Define the expected format and the format used when an error is reported.
VB
Dim StdFormat As Integer()= {5,10,11,-1}
Dim ErrorFormat As Integer() = {5,5,-1}
Robust Programming
The following conditions may cause an exception:
A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line
causing the exception, while the TextFieldParser.ErrorLine Property is assigned to the text contained in the line.
The specified file does not exist (FileNotFoundException).
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
The path is too long (PathTooLongException).
The user does not have sufficient permissions to access the file (UnauthorizedAccessException).
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
Reference
TextFieldParser Object
TextFieldParser.PeekChars Method
My.Computer.FileSystem.WriteAllText Method
TextFieldParser.EndOfData Property
TextFieldParser.TextFieldType Property
MalformedLineException
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Concepts
VB
My.Computer.FileSystem.ReadAllBytes _
("C:/Documents and Settings/selfportrait.jpg")
Robust Programming
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The file does not exist (FileNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
There is not enough memory to write the string to buffer (OutOfMemoryException).
The user lacks necessary permissions to view the path (SecurityException).
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a
Visual Basic source file.
Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to
read from the file may fail.
See Also
Tasks
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
My.Computer.FileSystem.ReadAllBytes Method
My.Computer.FileSystem.WriteAllBytes Method
Other Resources
Reading from Files in Visual Basic
Storing Data to and Reading From the Clipboard
Visual Basic Language Concepts
VB
Dim fileReader As System.IO.StreamReader
fileReader = _
My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)
Robust Programming
The file that is read must be a text file.
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a
Visual Basic source file.
Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to
read from the file may fail.
Security
To read from a file, your assembly requires a privilege level granted by the FileIOPermission class. If you are running in a
partial-trust context, the code might throw an exception due to insufficient privileges. For more information, see
Code Access Security Basics. The user also needs access to the file. For more information, see Access Control Lists (ACLs).
See Also
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.OpenTextFileWriter Method
My.Computer.FileSystem.OpenTextFileReader Method
OpenFileDialog
Other Resources
SaveFileDialog Component (Windows Forms)
Reading from Files in Visual Basic
Visual Basic Language Concepts
VB
My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", _
"This is new text to be added.",True)
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
File points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The disk is full, and the call to WriteAllText fails (IOException).
If you are running in a partial-trust context, the code might throw an exception due to insufficient privileges. For more
information, see Code Access Security Basics.
See Also
Tasks
How to: Read From Text Files in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.WriteAllText Method
Visual Basic Language Concepts
VB
Dim inputString As String = "This is a test string."
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", inputString, True)
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
File points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
See Also
Reference
My.Computer.FileSystem.WriteAllText Method
My.Computer.FileSystem Object
Other Resources
Writing to Files in Visual Basic
Visual Basic Language Concepts
Robust Programming
The following conditions may create an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; or it contains
invalid characters. (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
File points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
See Also
Tasks
How to: Write Text to Files in Visual Basic
Reference
My.Computer.FileSystem.WriteAllBytes Method
Visual Basic Language Concepts
Example
VB
Try
Dim filePath As String
filePath = System.IO.Path.Combine( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt")
My.Computer.FileSystem.WriteAllText(filePath, "some text", False)
Catch fileException As Exception
Throw fileException
End Try
Robust Programming
The following conditions may cause an exception:
The file exists and is read-only (IOException).
The disk is full (IOException).
The pathname is too long (PathTooLongException).
Security
This example creates a new file, if the file does not already exist. If an application needs to create a file, that application needs
Create access for the folder. If the file already exists, the application needs only Write access, a lesser privilege. Where
possible, it is more secure to create the file during deployment, and only grant Read access to a single file, rather than Create
access for a folder.
See Also
Tasks
How to: Read From Text Files in Visual Basic
Reference
My.Computer.FileSystem.OpenTextFileWriter Method
StreamWriter
Other Resources
Writing to Files in Visual Basic
Visual Basic Language Concepts
2. Use the CopyFile method to copy the files. This example copies the files to the directory named testdirectory.
VB
My.Computer.FileSystem.CopyFile(foundFile, "C:\testdirectory\" & foundFile)
Example
The following example, which presents the above snippets in complete form, copies all .rtf files in the specified directory to the
directory named testdirectory.
VB
For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
FileIO.SearchOption.SearchTopLevelOnly, "*.rtf")
Security
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The directory does not exist (DirectoryNotFoundException).
The directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException). The user lacks necessary permissions
(UnauthorizedAccessException).
See Also
Tasks
How to: Find Subdirectories with a Specific Pattern in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
How to: Get the Collection of Files in a Directory in Visual Basic
Reference
My.Computer.FileSystem.CopyFile Method
My.Computer.FileSystem.GetFiles Method
Visual Basic Language Concepts
Robust Programming
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The system could not retrieve the absolute path (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
The combined path points to an existing directory (IOException).
The destination file exists and overwrite is set to False (IOException).
The user does not have sufficient permissions to access the file (IOException).
A file in the target folder with the same name is in use (IOException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
ShowUI is set to True, onUserCancel is set to ThrowException, and the user has cancelled the operation
(OperationCanceledException).
ShowUI is set to True, onUserCancel is set to ThrowException, and an unspecified I/O error occurs
(OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user does not have required permission (UnauthorizedAccessException).
The user lacks necessary permissions to view the path (SecurityException).
See Also
Tasks
How to: Copy Files with a Specific Pattern to a Directory in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
How to: Copy a Directory to Another Directory in Visual Basic
How to: Rename a File in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.CopyFile Method
UICancelOption Enumeration
Visual Basic Language Concepts
Robust Programming
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The system could not retrieve the absolute path (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
The combined path points to an existing directory (IOException).
The destination file exists and overwrite is set to False (IOException).
The user does not have sufficient permissions to access the file (IOException).
A file in the target folder with the same name is in use (IOException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
ShowUI is set to True, onUserCancel is set to ThrowException, and the user has cancelled the operation
(OperationCanceledException).
ShowUI is set to True, onUserCancel is set to ThrowException, and an unspecified I/O error occurs
(OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user does not have required permission (UnauthorizedAccessException).
The user lacks necessary permissions to view the path (SecurityException).
See Also
Tasks
How to: Copy Files with a Specific Pattern to a Directory in Visual Basic
How to: Create a Copy of a File in the Same Directory in Visual Basic
How to: Copy a Directory to Another Directory in Visual Basic
How to: Rename a File in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.CopyFile Method
UICancelOption Enumeration
Visual Basic Language Concepts
To delete a text file and ask the user to confirm that the file should be deleted
Use the DeleteFile method to delete the file, setting showUI to AllDialogs. The following code demonstrates how to
delete the file named test.txt and allow the user to confirm that the file should be deleted.
VB
My.Computer.FileSystem.DeleteFile("C:\test.txt", _
FileIO.UIOption.AllDialogs, FileIO.RecycleOption.DeletePermanently, FileIO.UIC
ancelOption.DoNothing)
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The file is in use (IOException).
The user lacks necessary permissions to view the path (SecurityException).
The file does not exist (FileNotFoundException).
The user does not have permission to delete the file, or the file is read-only (UnauthorizedAccessException).
A partial-trust situation exists in which the user does not have sufficient permissions (SecurityException).
The user cancelled the operation and onUserCancel is set to Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException
(OperationCanceledException).
See Also
Tasks
How to: Get the Collection of Files in a Directory in Visual Basic
How to: Delete a Directory in Visual Basic
Reference
UICancelOption Enumeration
My.Computer.FileSystem Object
UIOption Enumeration
RecycleOption Enumeration
Visual Basic Language Concepts
My.Computer.FileSystem.DeleteFile(foundFile, _
FileIO.UIOption.AllDialogs, _
FileIO.RecycleOption.DeletePermanently)
Next
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The file is in use (IOException).
The user lacks necessary permissions to view the path (SecurityException).
The file does not exist (FileNotFoundException).
The user does not have permission to delete the file, or the file is read-only (UnauthorizedAccessException).
A partial-trust situation exists in which the user does not have sufficient permissions (SecurityException).
The user cancelled the operation and onUserCancel is set to Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException
(OperationCanceledException).
See Also
Tasks
How to: Delete a File in Visual Basic
How to: Delete a Directory in Visual Basic
How to: Rename a File in Visual Basic
How to: Determine the Absolute Path of a File in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.DeleteFile Method
RecycleOption Enumeration
UICancelOption Enumeration
Visual Basic Language Concepts
Listbox1.Items.Add(foundFile)
Next
Security
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Find Subdirectories with a Specific Pattern in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
How to: Get the Collection of Files in a Directory in Visual Basic
Reference
My.Computer.FileSystem.GetFiles Method
Visual Basic Language Concepts
VB
My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt", _
"C:\TestDir2\nexttest.txt", _
FileIO.UIOption.AllDialogs, _
FileIO.UICancelOption.ThrowException)
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
destinationFileName is Nothing or an empty string (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
The combined path points to an existing directory, the destination file exists and overwrite is set to False, a file in the
target directory with the same name is in use, or the user does not have sufficient permissions to access the file
(IOException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
showUI is set to True, onUserCancel is set to ThrowException, and either the user has cancelled the operation or an
unspecified I/O error occurs (OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have required permission (UnauthorizedAccessException).
See Also
Tasks
How to: Rename a File in Visual Basic
How to: Move a Collection of Files in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
How to: Parse File Paths in Visual Basic
How to: Move a Directory in Visual Basic
Reference
My.Computer.FileSystem.MoveFile Method
Visual Basic Language Concepts
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
The combined path points to an existing directory, the destination file exists and overwrite is set to False, a file in the
target directory with the same name is in use, or the user does not have sufficient permissions to access the file
(IOException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
showUI is set to True, onUserCancelOption is set to ThrowException, and either the user has cancelled the operation or
an unspecified I/O error occurs (OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have required permission (UnauthorizedAccessException).
See Also
Tasks
How to: Rename a File in Visual Basic
How to: Move a File in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
How to: Parse File Paths in Visual Basic
How to: Move a Directory in Visual Basic
How to: Move the Contents of a Directory in Visual Basic
Reference
My.Computer.FileSystem.MoveFile Method
My.Computer.FileSystem.GetFiles Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Concepts
VB
' Change "c:\test.txt" to the path and filename for the file that
' you want to rename.
My.Computer.FileSystem.RenameFile("C:\Test.txt", "SecondTest.txt")
This code example is also available as an IntelliSense code snippet. In the code snippet picker, the snippet is located in File
system - Processing Drives, Folders, and Files. For more information, see
How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
newName contains path information (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
newName is Nothing or an empty string (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
There is an existing file or directory with the name specified in newName (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have the required permission (UnauthorizedAccessException).
See Also
Tasks
How to: Move a File in Visual Basic
How to: Move a Collection of Files in Visual Basic
How to: Create a Copy of a File in the Same Directory in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
Reference
My.Computer.FileSystem.RenameFile Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Concepts
VB
My.Computer.FileSystem.RenameDirectory("C:MyDocuments\Test", _
"SecondTest")
This code example is also available as an IntelliSense code snippet. In the code snippet picker, the example is located in File
system - Processing Drives, Folders, and Files. For more information, see
How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The following conditions can cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
newName contains path information (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
newName is Nothing or an empty string (ArgumentNullException).
The source directory is not valid or does not exist (DirectoryNotFoundException).
There is an existing file or folder with the name specified in newName (IOException).
The folder is a root folder (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have required permission (UnauthorizedAccessException).
See Also
Tasks
How to: Copy a Directory to Another Directory in Visual Basic
How to: Parse File Paths in Visual Basic
How to: Move a Directory in Visual Basic
How to: Move the Contents of a Directory in Visual Basic
Reference
My.Computer.FileSystem.RenameDirectory Method
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in File system
- Processing Drives, Folders, and Files. For more information, see
How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The following conditions may cause an exception:
The new name specified for the directory contains a colon (:) or slash (\ or /) (ArgumentException).
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
destinationDirectoryName is Nothing or an empty string (ArgumentNullException)
The source directory does not exist (DirectoryNotFoundException).
The source directory is a root directory (IOException).
The combined path points to an existing file (IOException).
The source path and target path are the same (IOException).
ShowUI is set to UIOption.AllDialogs and the user cancels the operation, or one or more files in the directory cannot be
copied (OperationCanceledException).
The operation is cyclic (InvalidOperationException).
The path contains a colon (:) (NotSupportedException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
A destination file exists but cannot be accessed (UnauthorizedAccessException).
See Also
Tasks
How to: Find Subdirectories with a Specific Pattern in Visual Basic
How to: Get the Collection of Files in a Directory in Visual Basic
How to: Move a Directory in Visual Basic
How to: Move the Contents of a Directory in Visual Basic
Reference
My.Computer.FileSystem.CopyDirectory Method
Visual Basic Language Concepts
Robust Programming
The following conditions may cause an exception:
The directory name is malformed. For example, it contains illegal characters or is only white space (ArgumentException).
The parent directory of the directory to be created is read-only (IOException).
The directory name is Nothing (ArgumentNullException).
The directory name is too long (PathTooLongException).
The directory name is a colon ":" (NotSupportedException).
The user does not have permission to create the directory (UnauthorizedAccessException).
The user lacks permissions in a partial-trust situation (SecurityException).
See Also
Tasks
How to: Determine if a Directory Exists in Visual Basic
Reference
My.Computer.FileSystem.CreateDirectory Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Concepts
Robust Programming
The following conditions may cause an exception:
The path is a zero-length string, is malformed, contains only white space, or contains invalid characters (including
wildcard characters) (ArgumentException).
The path is a device path (starts with \\.\) (ArgumentException).
The path is Nothing (ArgumentNullException).
The directory does not exist or is a file (DirectoryNotFoundException).
The user does not have permission to delete the directory or subdirectory (IOException).
A file in the directory or subdirectory is in use (IOException).
A file or directory name contains a colon (:) (NotSupportedException).
OnUserCancel is set to ThrowException and the user cancels the operation (OperationCanceledException).
OnUserCancel is set to ThrowException and the directory cannot be deleted (OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
showUI is set to AllDialogs and the user does not have required permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Delete a File in Visual Basic
Reference
UICancelOption Enumeration
My.Computer.FileSystem.DeleteDirectory Method
RecycleOption Enumeration
UIOption Enumeration
DeleteDirectoryOption Enumeration
Visual Basic Language Concepts
VB
For Each foundDirectory As String In _
My.Computer.FileSystem.GetDirectories( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, True, _
"*Logs*")
ListBox1.Items.Add(foundDirectory)
Next
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
One or more of the specified wildcard characters is Nothing, an empty string, or contains only spaces
(ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Find Files with a Specific Pattern in Visual Basic
Reference
My.Computer.FileSystem.GetDirectories Method
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in File system
- Processing Drives, Folders, and Files. For more information, see
How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Find Files with a Specific Pattern in Visual Basic
How to: Find Subdirectories with a Specific Pattern in Visual Basic
Reference
My.Computer.FileSystem.GetFiles Method
Visual Basic Language Concepts
2. Use the Count property to determine the number of files in the collection. This example displays the result in a message
box.
VB
MsgBox("number of files is " & CStr(counter.Count))
Example
This example, which presents the above snippet in complete form, counts the number of files in TestDir and reports it in a
message box.
VB
Dim counter As _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
counter = My.Computer.FileSystem.GetFiles("C:\TestDir")
MsgBox("number of files is " & CStr(counter.Count))
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The directory does not exist or is a file (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Get the Collection of Files in a Directory in Visual Basic
How to: Find Files with a Specific Pattern in Visual Basic
Reference
My.Computer.FileSystem.GetFiles Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is Nothing (ArgumentNullException).
The source is invalid (DirectoryNotFoundException).
The source is a root directory (IOException).
The combined path points to an existing file (IOException).
The source path and the target path are the same (IOException).
The file already exists and overwrite is set to False (IOException).
A subdirectory of file cannot be copied (IOException).
The operation is cyclic (InvalidOperationException).
A file or directory name in the path contains a colon (:) (NotSupportedException).
onUserCancel is set to UICancelOption.ThrowException, and the user cancels the operation
(OperationCanceledException).
onUserCancel is set to UICancelOption.ThrowException, and the operation cannot be completed
(OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
onUserCancel is set to UICancelOption.ThrowException, and the user lacks necessary permissions (SecurityException).
The user does not have permission to modify the file (UnauthorizedAccessException).
See Also
Tasks
How to: Move the Contents of a Directory in Visual Basic
How to: Copy a Directory to Another Directory in Visual Basic
How to: Rename a Directory in Visual Basic
How to: Parse File Paths in Visual Basic
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Concepts
My.Computer.FileSystem.MoveFile(foundFile, "C:\StorageDir")
Next
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Rename a File in Visual Basic
How to: Move a File in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
How to: Parse File Paths in Visual Basic
How to: Move a Directory in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
How to: Move a Collection of Files in Visual Basic
Reference
My.Computer.FileSystem.MoveFile Method
My.Computer.FileSystem.GetFiles Method
Visual Basic Language Concepts
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
My.Computer.FileSystem.SpecialDirectories Object Members
My.Computer.FileSystem.ReadAllText Method
Visual Basic Language Concepts
VB
Dim fullPath As String
fullPath = My.Computer.FileSystem.CombinePath(folderPath, fileName)
MsgBox(fullPath)
See Also
Tasks
How to: Get the Collection of Files in a Directory in Visual Basic
How to: Determine the Absolute Path of a File in Visual Basic
How to: Get Information About a File in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.CombinePath Method
My.Computer.FileSystem.GetFileInfo Method
FileInfo
Visual Basic Language Concepts
Procedure
To get information about a file
1. Use the GetFileInfo method to retrieve a FileInfo object that can be examined to determine its properties. The following
example retrieves a FileInfo object for the file MyLogFile.log.
VB
Dim information As System.IO.FileInfo
information = My.Computer.FileSystem.GetFileInfo("C:\MyLogFile.log")
2. Examine the FileInfo object to extract the information you need. The following lines of code report the file's full name,
last access time, and length.
VB
MsgBox("The file's full name is " & information.FullName & ".")
MsgBox("Last access time is " & information.LastAccessTime & ".")
MsgBox("The length is " & information.Length & ".")
Robust Programming
The following conditions may cause an exception:
The path name is malformed. For example, it contains invalid characters or is only white space (ArgumentException).
The file does not exist or is Nothing (ArgumentNullException).
The path contains a colon in the middle of the string (NotSupportedException).
The path is too long (PathTooLongException).
The user lacks necessary permissions (SecurityException).
The user lacks ACL (access control list) access to the file (UnauthorizedAccessException).
See Also
Tasks
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
FileInfo
Other Resources
File Access with Visual Basic
Visual Basic Language Concepts
Robust Programming
The following conditions may cause an exception:
The path name is malformed. For example, it contains invalid characters or is only white space (ArgumentException).
The file does not exist or is Nothing (ArgumentNullException).
The path contains a colon in the middle of the string (NotSupportedException).
The path is too long (PathTooLongException).
The user lacks necessary permissions (SecurityException).
The user lacks ACL (access control list) access to the file (UnauthorizedAccessException).
See Also
Tasks
How to: Parse File Paths in Visual Basic
Reference
My.Computer.FileSystem.GetFileInfo Method
FileInfo
Visual Basic Language Concepts
See Also
Tasks
How to: Search for a String in an Array of Strings (Visual Basic)
How to: Parse File Paths in Visual Basic
Reference
My.Computer.FileSystem.GetFiles Method
Path
Visual Basic Language Concepts
See Also
Tasks
How to: Determine a File's Attributes in Visual Basic
How to: Determine a File's Creation Time in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetFileInfo Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Determine a File's Attributes in Visual Basic
How to: Determine a File's Creation Time in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetFileInfo Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Determine a File's Attributes in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetFileInfo Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Determine a File's Attributes in Visual Basic
How to: Determine a File's Last Accessed Time in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetFileInfo Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts
2. Get a FileAttributes object from the FileInfo object. This example gets FileAttributes from the FileInfo object.
VB
Dim attributeReader As System.IO.FileAttributes
attributeReader = infoReader.Attributes
3. Query FileAttributes to determine if the file is hidden. This example determines if the file is hidden and displays a result
accordingly.
VB
If (attributeReader And System.IO.FileAttributes.Hidden) > 0 Then
MsgBox("File is hidden!")
Else
MsgBox("File is not hidden!")
End If
See Also
Tasks
How to: Determine a File's Attributes in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem Object Members
My.Computer.FileSystem.GetFileInfo Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Determine if a Directory is Read-Only in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetFileInfo Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts
Hidden The file is hidden and will not be displayed in an ordinary directory listing.
NotContentIndexed The file will not be indexed by the operating system's content indexing service.
Offline The file is offline. The data in the file is not immediately available.
ReparsePoint The file contains a reparse point, which is a block of user-defined data.
SparseFile The file is a sparse file. Sparse files are usually large files containing data that is mostly zeroes.
System The file is a system file. The file is part of the operating system or is used exclusively by the operating syste
m.
Temporary The file is temporary. File systems attempt to keep all of the data in memory for quicker access, rather tha
n flushing the data back to mass storage. A temporary file should be deleted by the application as soon as
it is no longer needed.
2. Get a FileAttributes object from the FileInfo object. This example gets FileAttributes from the FileInfo object.
VB
Dim attributeReader As System.IO.FileAttributes
attributeReader = infoReader.Attributes
3. Query FileAttributes. This example determines if the file is encrypted and displays a result accordingly.
VB
If (attributeReader And System.IO.FileAttributes.Encrypted) > 0 Then
MsgBox("File is encrypted!")
Else
MsgBox("File is not encrypted!")
End If
See Also
Tasks
How to: Determine if a File is Hidden in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetFileInfo Method
FileAttributes
FileInfo
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks the necessary permissions to view the path (SecurityException).
See Also
Tasks
How to: Determine if a Directory Exists in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Reference
My.Computer.FileSystem.GetDirectoryInfo Method
DirectoryInfo
CreationTime
Visual Basic Language Concepts
Example
The following example, which presents the above snippet in complete form, determines whether the directory testDirectory
is read-only and reports the result in a message box.
VB
Dim reader As System.IO.DirectoryInfo
reader = My.Computer.FileSystem.GetDirectoryInfo("C:\testDirectory")
If (reader.Attributes And System.IO.FileAttributes.ReadOnly) > 0 Then
MsgBox("File is readonly!")
End If
Hidden 2 The file is hidden and therefore not included in an ordinary directory listing.
System 4 The file is a system file. The file is part of the operating system or used exclusively by the operatin
g system.
Archive 32 The file's archive status. Applications use this attribute to mark files for backup or removal.
Normal 128 The file is normal and no other attributes are set. This attribute is valid only if used alone.
Temporary 256 The file is temporary. File systems attempt to keep all of the data in memory for quicker access. A
temporary file should be deleted when it is no longer needed.
SparseFile 512 The file is a sparse file. Sparse files are typically large files containing data that is mostly zeroes.
ReparsePoint 1024 The file contains a reparse point, which is a block of user-defined data associated with a file or dir
ectory.
Offline 4096 The file is offline and the data is not immediately available.
NotContentIndexed 8192 The file will not be indexed by the operating system's content indexing service.
Encrypted 16384 The file or directory is encrypted. For files, this means that all data in the file is encrypted. For dire
ctories, this means that encryption is the default for newly created files and directories.
See Also
Tasks
How to: Determine a File's Attributes in Visual Basic
Reference
My.Computer.FileSystem.GetDirectoryInfo Method
DirectoryInfo
FileAttributes
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts
Procedure
To determine if a file exists
Use the My.Computer.FileSystem.FileExists method, supplying the path, to determine whether or not the specified file
exists. The following example checks to see whether or not the file Check.txt exists and supplies the information in a
message box.
VB
If My.Computer.FileSystem.FileExists("c://Check.txt") Then
MsgBox("File found.")
Else
MsgBox("File not found.")
End If
See Also
Tasks
How to: Determine if a Directory Exists in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem.FileExists Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Concepts
Procedure
To determine if a directory exists
Use the My.Computer.FileSystem.DirectoryExists method, supplying the path, to determine whether or not the
specified directory exists. The following example checks to determine whether or not the directory C:\backup\logs exists
and checks its properties.
VB
Dim logDirectoryProperties As System.IO.DirectoryInfo
If My.Computer.FileSystem.DirectoryExists("C:\backup\logs") Then
logDirectoryProperties = My.Computer.FileSystem.GetDirectoryInfo("C:\backup\logs")
End If
See Also
Tasks
How to: Determine if a File Exists in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem.DirectoryExists Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Determine a Drive's Total Space in Visual Basic
How to: Determine a Drive's Format in Visual Basic
How to: Determine a Drive's Type in Visual Basic
Reference
My.Computer.FileSystem.GetDriveInfo Method
Visual Basic Language Concepts
See Also
Tasks
How to: Determine a Drive's Total Space in Visual Basic
How to: Determine a Drive's Volume Label in Visual Basic
How to: Determine a Drive's Type in Visual Basic
Reference
My.Computer.FileSystem.GetDriveInfo Method
Visual Basic Language Concepts
CDRom 1 Drive is a CD-ROM. No distinction is made between read-only and read/write CD-ROM drives.
Fixed 3 Drive has fixed (nonremovable) media. This value includes all hard drives, even hard drives that are remova
ble.
RamDisk 4 Drive is a block of Random Access Memory (RAM) on the local computer that behaves like a disk drive.
Removabl 6 Drive has removable media. This includes all floppy drives.
e
See Also
Tasks
How to: Determine a Drive's Total Space in Visual Basic
How to: Determine a Drive's Volume Label in Visual Basic
Reference
My.Computer.FileSystem.GetDriveInfo Method
DriveInfo
Visual Basic Language Concepts
See Also
Tasks
How to: Determine a Drive's Physical Free Space in Visual Basic
How to: Determine a Drive's Volume Label in Visual Basic
How to: Determine a Drive's Type in Visual Basic
Reference
My.Computer.FileSystem.GetDriveInfo Method
DriveInfo
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in File system
- Processing Drives, Folders, and Files. For more information, see
How to: Insert Snippets Into Your Code (Visual Basic).
See Also
Tasks
How to: Determine a Drive's Total Space in Visual Basic
How to: Determine a Drive's Format in Visual Basic
How to: Determine a Drive's Type in Visual Basic
Reference
My.Computer.FileSystem.GetDriveInfo Method
DriveInfo
Visual Basic Language Concepts
See Also
Tasks
How to: Determine a Drive's Total Space in Visual Basic
How to: Determine a Drive's Type in Visual Basic
Reference
My.Computer.FileSystem.GetDriveInfo Method
DriveInfo
Visual Basic Language Concepts
Example
VB
Dim systemDirectory As String
systemDirectory = System.Environment.SystemDirectory
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Operating System > System Information. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
The property returns a value such as "c:\WINNT\System32".
Security
This code requires FileIOPermission Class.
See Also
Tasks
How to: Determine a Directory's Attributes in Visual Basic
Reference
Environment.GetFolderPath Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts
Other text files may have field widths that are fixed. In such cases, you need to define the TextFieldType as FixedWidth and
define the widths of each field, as in the following example. This example uses the SetFieldWidths method to define the
columns of text: the first column is 5 characters wide, the second is 10, the third is 11, and the fourth is of variable width.
VB
testReader.SetFieldWidths(5, 10, 11, -1)
Once the format is defined, you can loop through the file, using the ReadFields method to process each line in turn.
If a field does not match the specified format, a MalformedLineException exception is thrown. When such exceptions are
thrown, the ErrorLine and ErrorLineNumber properties hold the text causing the exception and the line number of that text..
Parsing Files with Multiple Formats
The PeekChars method of the TextFieldParser object can be used to check each field before reading it, allowing you to define
multiple formats for the fields and react accordingly. For more information, see
How to: Read From Text Files with Multiple Formats in Visual Basic.
See Also
Tasks
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
My.Computer.FileSystem.OpenTextFieldParser Method
TextFieldParser Object
TextFieldParser.PeekChars Method
TextFieldParser.ReadFields Method
TextFieldParser.CommentTokens Property
TextFieldParser.Delimiters Property
TextFieldParser.ErrorLine Property
TextFieldParser.ErrorLineNumber Property
TextFieldParser.FieldWidths Property
TextFieldParser.HasFieldsEnclosedInQuotes Property
TextFieldParser.LineNumber Property
TextFieldParser.TextFieldType Property
TextFieldParser.TrimWhiteSpace Property
TextFieldParser.SetDelimiters Method
TextFieldParser.SetFieldWidths Method
Visual Basic Language Concepts
File Encodings
File encodings, also known as character encodings, specify how to represent characters when text processing. One encoding
may be preferable over another in terms of which language characters it can or cannot handle, although Unicode is usually
preferred.
When reading from or writing to files, improperly matching file encodings may result in exceptions or incorrect results.
Types of Encodings
Unicode is the preferred encoding when working with files. Unicode is a worldwide character-encoding standard that uses 16-
bit code values to represent all the characters used in modern computing, including technical symbols and special characters
used in publishing.
Previous character-encoding standards consisted of traditional character sets, such as the Windows ANSI character set that
uses 8-bit code values, or combinations of 8-bit values, to represent the characters used in a specific language or geographical
region.
Encoding Class
The Encoding class represents a character encoding. This table lists the type of encodings available and describes each.
Name Description
ASCIIEncoding Represents an ASCII character encoding of Unicode characters.
See Also
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Visual Basic Language Concepts
Note
The Visual Studio Integrated Development Environment (IDE) will return to the Code Editor and position the insertion point
within the event handler where you should add the code.
1. To write to the file, use the Write method of the StreamWriter class. Add the following code directly after Dim fw As
StreamWriter. You do not need to worry that an exception will be thrown if the file is not found, because it will be created
if it does not already exist.
VB
Dim ReadString As String
Try
'Pass the file path and name to the StreamWriter constructor.
'Indicate that Append is True, so file will not be overwritten.
fw = New StreamWriter("C:\MyDiary.txt", True)
ReadString = Entry.Text
fw.WriteLine(ReadString)
Finally
'Close the file.
fw.Close()
End Try
2. Make sure that the user cannot submit a blank entry by adding the following code directly after Dim ReadString As
String.
VB
If (Entry.Text = "" Or Entry.Text = "Please enter something.") Then
Entry.Text = "Please enter something."
Return
End If
3. Because this is a diary, the user will want to assign a date to each entry. Insert the following code after fw = New
StreamWriter("C:\MyDiary.txt", True) to set the variable Today to the current date.
VB
Dim Today As DateTime
Today = Now
fw.Write(CStr(Today))
fw.Write(ControlChars.CrLf)
4. Finally, attach code to clear the TextBox. Add the following code to the Clear button's Click event.
VB
Entry.Text = ""
FileString = fr.ReadLine
Loop Until FileString = CStr(PickEntries.SelectedItem)
FileString = CStr(PickEntries.SelectedItem) & ControlChars.CrLf
ReadString = FileString & fr.ReadLine
2. To test your code, press F5 to compile the application, and then submit an entry. Click Get Entries, select an entry from
the ComboBox, and then click Display. The contents of the selected entry appear in the DisplayEntry TextBox.
Enabling Users to Delete or Modify Entries
Finally, you can include additional functionality enables users to delete or modify an entry by using DeleteEntry and
EditEntry buttons. Both buttons remain disabled unless an entry is displayed.
Add the controls in the following table to the form and set the corresponding values for their properties.
Control Properties Values
Button Name DeleteEntry
Text Delete Entry
Enabled False
Button Name EditEntry
Text Edit Entry
Enabled False
VB
DeleteEntry.enabled = True
2. Create a Click event handler for the DeleteEntry button and add the following code.
VB
Dim fr As StreamReader
Dim ReadString As String
Dim WriteString As String
Dim ConfirmDelete As MsgBoxResult
fr = New StreamReader("C:\MyDiary.txt")
ReadString = fr.ReadLine
' Read through the textfile
Do Until (fr.Peek < 0)
ReadString = ReadString & vbCrLf & fr.ReadLine
Loop
WriteString = Replace(ReadString, DisplayEntry.Text, "")
fr.Close()
' Check to make sure the user wishes to delete the entry
ConfirmDelete = MsgBox("Do you really wish to delete this entry?", _
MsgBoxStyle.OKCancel)
If ConfirmDelete = MsgBoxResult.OK Then
File.Delete("C:\MyDiary.txt")
Dim fw As StreamWriter = File.CreateText("C:\MyDiary.txt")
fw.WriteLine(WriteString)
fw.Close()
' Reset controls on the form
DisplayEntry.Text = ""
PickEntries.Text = ""
PickEntries.Items.Clear()
PickEntries.Enabled = False
DeleteEntry.Enabled = False
End If
3. When a user displays an entry, the EditEntry button becomes enabled. Add the following code to the Click event of the
Display button after DisplayEntry.Text = ReadString.
VB
EditEntry.Enabled = True
4. Create a Click event handler for the EditEntry button and add the following code.
VB
Entry.Text = DisplayEntry.Text
SubmitEdit.Enabled = True
5. Create a Click event handler for the SubmitEdit button and add the following code
VB
Dim fr As StreamReader
Dim ReadString As String
Dim WriteString As String
If Entry.Text = "" Then
MsgBox("Use Delete to Delete an Entry")
Return
End If
fr = New StreamReader("C:\MyDiary.txt")
ReadString = fr.ReadLine
Do Until (fr.Peek < 0)
ReadString = ReadString & vbCrLf & fr.ReadLine
Loop
WriteString = Replace(ReadString, DisplayEntry.Text, Entry.Text)
fr.Close()
File.Delete("C:\MyDiary.txt")
Dim fw As StreamWriter = File.CreateText("C:\MyDiary.txt")
fw.WriteLine(WriteString)
fw.Close()
DisplayEntry.Text = Entry.Text
Entry.Text = ""
EditEntry.Enabled = False
SubmitEdit.Enabled = False
To test your code, press F5 to compile the application. Click Get Entries, select an entry, and then click Display. The entry
appears in the DisplayEntry TextBox. Click Edit Entry. The entry appears in the Entry TextBox. Edit the entry in the Entry
TextBox and click Submit Edit. Open the MyDiary.txt file to confirm your correction. Now select an entry and click Delete
Entry. When the MessageBox requests confirmation, click OK. Close the application and open MyDiary.txt to confirm the
deletion.
See Also
Reference
StreamReader Class
StreamWriter Class
Other Resources
Visual Basic Language Walkthroughs
Visual Basic Language Concepts
VB
' This checks to make sure the path is not blank.
Catch ex As Exception When NewPath = ""
ErrorMessage = "You must enter a path."
' This catches errors caused by a path that is not valid.
Catch
ErrorMessage = "You must enter a valid path. If trying " & _
"to access a different drive, remember to include the drive " & _
"letter."
Finally
' Display the error message only if one exists.
If ErrorMessage <> Nothing Then
MsgBox(ErrorMessage)
End If
End Try
VB
fileList = My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.CurrentDirectory, _
FileIO.SearchOption.SearchTopLevelOnly, "*.txt")
For Each foundFile As String In fileList
lstFilePick.Items.Add(foundFile)
Next
The gathered information appears in the lstFilePick ComboBox, from which you can pick a specific file to examine.
Test the application by running it first on a directory that contains no .txt files and then on one that contains more than one .txt
file. In the first instance, the application displays the appropriate error message. In the second, the application creates a list in
the ComboBox of all .txt files within the directory specified in the txtDirectory TextBox.
Enabling a User to Select a File to Examine
Although the lstFilePick ComboBox displays all files in a directory, a user probably wants to select and examine a specific
file.
To enable selection of a specific file
Create a click event handler for btnExamine_Click and add the following code to confirm a file's selection.
VB
Dim thisFile As System.IO.FileInfo
thisFile = My.Computer.FileSystem.GetFileInfo(CStr(lstFilePick.SelectedItem))
The My.Computer.FileSystem.GetFileInfo method returns a FileInfo object that can be queried to get information
about a file.
2. Add the following code to the end of the btnExamine_Click event.
VB
' Check last access time.
If chkLastAccess.Checked = True Then
LastAccess = thisFile.LastAccessTime
End If
The LastAccessTime property determines the last time the file was accessed. The returned Date value indicates the date and
time when the file was created or last modified.
1. Add the following code to the end of the btnExamine_Click event.
VB
' Check Length.
If chkFileLength.Checked = True Then
Length = thisFile.Length
End If
The Length property, which determines the length of the file, returns a Long value specifying the length of the file in bytes.
Displaying the Results
To complete the application's functionality, a MsgBox reports the gathered information.
To display the results
1. At the end of the If statement that determines whether or not the chkLastAccess CheckBox has been selected, add the
following before the final End If.
VB
' Add to the messagebox.
FinalString = FinalString & stringLastAccess & LastAccess & "." _
& vbCrLf
2. At the end of the If statement that determines whether or not the chkFileLength CheckBox has been selected, add the
following before the final End If.
VB
' Add to the messagebox.
FinalString = FinalString & stringlength & CStr(Length) & "." _
& vbCrLf
3. At the end of the If statement that determines whether or not the chkFirstLine CheckBox has been selected, add the
following before the final End If.
VB
' Add to the messagebox.
FinalString &= FirstLine & vbCrLf
Development with My
Visual Basic provides new features for rapid application development that improve productivity and ease of use while
delivering power. One of these features, called My, provides access to information and default object instances that are related
to the application and its run-time environment. This information is organized in a format that is discoverable through
IntelliSense and logically delineated according to use.
Top-level members of My are exposed as objects. Each object behaves similarly to a namespace or a class with Shared
members, and it exposes a set of related members.
This table shows the top-level My objects and their relationship to each other.
In This Section
Performing Tasks with My.Application, My.Computer, and My.User
Describes the three central My objects, My.Application, My.Computer, and My.User, which provide access to information
and functionality
Default Object Instances Provided by My.Forms and My.WebServices
Describes the My.Forms and My.WebServices objects, which provide access to forms, data sources, and XML Web services
used by your application.
Rapid Application Development with My.Resources and My.Settings
Describes the My.Resources and My.Settings objects, which provide access to an application's resources and settings.
Overview of the Visual Basic Application Model
Describes the Visual Basic Application Startup/Shutdown model.
How My Depends on Project Type
Gives details on which My features are available in different project types.
See Also
Reference
My.Application Object
My.Computer Object
My.User Object
My.Forms Object
My.WebServices Object
Concepts
How My Depends on Project Type
Visual Basic Language Concepts
VB
' Gets a list of subfolders in a folder
My.Computer.FileSystem.GetDirectories _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments, True, "*Logs*")
In addition to retrieving information, the members exposed through these three objects also allow you to execute methods
related to that object. For instance, you can access a variety of methods to manipulate files or update the registry through
My.Computer.
File I/O is significantly easier and faster with My, which includes a variety of methods and properties for manipulating files,
directories, and drives. The TextFieldParser Object allows you to read from large structured files that have delimited or fixed-
width fields. This example opens the TextFieldParser reader and uses it to read from C:\TestFolder1\test1.txt.
VB
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
reader = My.Computer.FileSystem.OpenTextFieldParser _
("C:\TestFolder1\test1.txt")
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
Dim currentRow As String()
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
My.Application allows you to change the culture for your application. The following example demonstrates how this method
can be called.
VB
' Changes the current culture for the application to Jamaican English.
My.Application.ChangeCulture("en-JM")
See Also
Reference
My.Application Object
My.Computer Object
My.User Object
Concepts
How My Depends on Project Type
Visual Basic Language Concepts
VB
' With My.Forms, you can directly call methods on the default
' instance()
My.Forms.Form1.Show()
The My.Forms object returns a collection of default instances for every Form class that exists in your project. Similarly,
My.WebServices provides a default instance of the proxy class for every Web service that you have created a reference to in
your application.
See Also
Reference
My.Forms Object
My.WebServices Object
Concepts
How My Depends on Project Type
Visual Basic Language Concepts
The My.Resources object exposes only global resources. It does not provide access to resource files associated with forms.
You must access the form resources from the form. For more information, see Walkthrough: Localizing Windows Forms.
Similarly, the My.Settings object provides access to the application's settings and allows you to dynamically store and retrieve
property settings and other information for your application. For more information, see My.Resources Object and
My.Settings Object.
See Also
Reference
My.Resources Object
My.Settings Object
Concepts
Accessing Application Resources
Accessing Application Settings
Visual Basic Language Concepts
By handling the StartupNextInstance event, you can control how your single-instance application behaves. For example,
Microsoft Outlook typically runs as a single-instance application; when Outlook is running and you attempt to start Outlook
again, focus shifts to the original instance but another instance does not open.
Events in the Application Model
The following events are found in the application model:
Application startup. The application raises the Startup event when it starts. By handling this event, you can add code
that initializes the application before the main form is loaded. The Startup event also provides for canceling execution of
the application during that phase of the startup process, if desired.
You can configure the application to show a splash screen while the application startup code runs. By default, the
application model suppresses the splash screen when either the /nosplash or -nosplash command-line argument is
used.
Single-instance applications. The StartupNextInstance event is raised when a subsequent instance of a single-instance
application starts. The event passes the command-line arguments of the subsequent instance.
Unhandled exceptions. If the application encounters an unhandled exception, it raises the UnhandledException event.
Your handler for that event can examine the exception and determine whether to continue execution.
The UnhandledException event is not raised in some circumstances. For more information, see
My.Application.UnhandledException Event.
Network-connectivity changes. If the computer's network availability changes, the application raises the
NetworkAvailabilityChanged event.
The NetworkAvailabilityChanged event is not raised in some circumstances. For more information, see
My.Application.NetworkAvailabilityChanged Event.
Application shut down. The application provides the Shutdown event to signal when it is about to shut down. In that
event handler, you can make sure that the operations your application needs to perform—closing and saving, for
example—are completed. You can configure your application to shut down when the main form closes, or to shut down
only when all forms close.
Availability
By default, the Visual Basic Application model is available for Windows Forms projects. If you configure the application to use a
different startup object, or start the application code with a custom Sub Main, then that object or class may need to provide an
implementation of the WindowsFormsApplicationBase class to use the application model. For information about changing the
startup object, see How to: Change the Startup Object for an Application.
See Also
Reference
My.Application Object
My.Application.Startup Event
My.Application.StartupNextInstance Event
My.Application.UnhandledException Event
My.Application.Shutdown Event
My.Application.NetworkAvailabilityChanged Event
WindowsFormsApplicationBase
Concepts
Extending the Visual Basic Application Model
Visual Basic Language Concepts
In a Web site project, My exposes objects that are relevant to a Web developer (such as the My.Request and My.Response
objects) while suppressing objects that are not relevant (such as the My.Forms object). The following image shows the My
object model in a Web site project:
Project Details
The following table shows which My objects are enabled by default for eight project types: Windows application, class Library,
console application, Windows control library, Web control library, Windows service, empty, and Web site.
There are three versions of the My.Application object, two versions of the My.Computer object, and two versions of
My.User object; details about these versions are given in the footnotes after the table.
My Object Windows Appli Class Libr Console Applic Windows Control Web Control Li Windows Se Emp Web S
cation ary ation Library brary rvice ty ite
My.Applicat Yes 1 Yes 2 Yes 3 Yes 2 No Yes 3 No No
ion
My.Log No No No No No No No Yes
My.Request No No No No No No No Yes
My.Respons No No No No No No No Yes
e
1 Windows Forms version of My.Application. Derives from the console version (see Note 3); adds support for interacting with
the application's windows and provides the Visual Basic Application model.
2 Library version of My.Application. Provides the basic functionality needed by an application: provides members for writing
to the application log and accessing application information.
3 Console version of My.Application. Derives from the library version (see Note 2), and adds additional members for
accessing the application's command-line arguments and ClickOnce deployment information.
4 Windows version of My.Computer. Derives from the Server version (see Note 5), and provides access to useful objects on a
client machine, such as the keyboard, screen, and mouse.
5 Server version of My.Computer. Provides basic information about the computer, such as the name, access to the clock, and
so on.
6 Windows version of My.User. This object is associated with the thread's current identity.
7 Web version of My.User. This object is associated with the user identity of the application's current HTTP request.
See Also
Reference
/define (Visual Basic)
My.Application Object
My.Computer Object
My.Forms Object
My.Log Object
My.Request Object
My.Response Object
My.User Object
My.WebServices Object
Concepts
Customizing Which Objects are Available in My
Conditional Compilation Overview
Visual Basic Language Concepts
Step into only the code you have written and ignore other code, such as system c How to: Step Into Just My Code
alls.
Enable just-in-time debugging, which launches the Visual Studio debugger when Just-In-Time Debugging
a program running outside Visual Studio encounters a fatal error.
Handling Exceptions
The following table lists debugging tasks involving exception handling and points to their associated Help pages.
To See
Break on unhandled exceptions. How to: Break on User-Unhandled Exceptions
Break when an exception is thrown. How to: Break When an Exception is Thrown
Use the exception assistant. How to: Correct Run-Time Errors with the Exception Assistant
Continue execution after an exception has been thrown. Continuing Execution After an Exception
Apply edits in break mode. How to: Apply Edits in Break Mode with Edit and Continue
Use the Call Stack window to view function or procedure calls that are currently on t How to: Use the Call Stack Window
he stack.
Use the Disassembly window to view assembly code corresponding to the instructio How to: Use the Disassembly Window
ns created by the compiler.
Use the Modules window to list and describe modules used by your program. How to: Use the Modules Window
Use the Script Explorer window to list script files that are currently loaded into the pr How to: Use the Script Explorer Window
ogram.
Use the Processes window to show all processes that you have attached to or launch How to: Use the Processes Window
ed from Visual Studio.
Use the Threads window to examine and control threads in the program. How to: Use the Threads Window
Setting Breakpoints
The following table lists debugging tasks involving breakpoints and points to their associated Help pages.
To See
Set a breakpoint. How to: Set a Simple Breakpoint
Use a filter to limit the behavior of a breakpoint to specified computers, processes, and How to: Specify a Breakpoint Filter
threads.
Conditionally control whether or not a breakpoint is executed. How to: Specify a Breakpoint Condition
Use the Breakpoints window to accomplish breakpoint-related tasks. How to: Use the Breakpoints Window
See Also
Tasks
Walkthrough: Debugging a Windows Form
How to: Apply Edits in Break Mode with Edit and Continue
Concepts
Debugging SQL
Execution Control
Other Resources
Debugging Managed Code
Debugging Native Code
Debugging Web Applications
Debugging User Interface Reference
Debug Settings and Preparation
Debugger Roadmap
Debugging Preparation: C#, J#, and Visual Basic Project Types
Visual Basic Language Concepts
Types of Errors
In Visual Basic, errors (also called exceptions) fall into one of three categories: syntax errors, run-time errors, and logic errors.
Syntax Errors
Syntax errors are those that appear while you write code. Visual Basic checks your code as you type it in the Code Editor
window and alerts you if you make a mistake, such as misspelling a word or using a language element improperly. Syntax
errors are the most common type of errors. You can fix them easily in the coding environment as soon as they occur.
Note
The Option Explicit statement is one means of avoiding syntax errors. It forces you to declare, in advance, all the variables t
o be used in the application. Therefore, when those variables are used in the code, any typographic errors are caught immedi
ately and can be fixed.
Run-Time Errors
Run-time errors are those that appear only after you compile and run your code. These involve code that may appear to be
correct in that it has no syntax errors, but that will not execute. For example, you might correctly write a line of code to open a
file. But if the file is corrupted, the application cannot carry out the Open function, and it stops running. You can fix most run-
time errors by rewriting the faulty code, and then recompiling and rerunning it.
Logic Errors
Logic errors are those that appear once the application is in use. They are most often unwanted or unexpected results in
response to user actions. For example, a mistyped key or other outside influence might cause your application to stop working
within expected parameters, or altogether. Logic errors are generally the hardest type to fix, since it is not always clear where
they originate.
See Also
Concepts
Introduction to Exception Handling
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Other Resources
Exception Handling Tasks
Debugger Roadmap
Visual Basic Language Concepts
Suggested fix Displays possible ways to fix the error. Click one to have it applied to your code.
Preview Displays a preview of the corrected code. In situations where the fix does not affect the code, a preview will n
ot be shown.
Expand all previe Checking this box will expand all previews.
ws
See Also
Tasks
How to: Correct Compiler Errors with Auto Correction
Concepts
Types of Errors
Configuring Warnings in Visual Basic
Visual Basic Language Concepts
/warnaserror+:<warning list Treat specific warnings as errors, listed by their error ID number in a comma delimited list r.
>
/warnaserror-:<warning list Do not treat specific warnings as errors, listed by their error ID number in a comma delimited
>
list.
/nowarn:<warning list> Do not report specified warnings, listed by their error ID number in a comma delimited list.
The warning list contains the error ID numbers of the warnings that should be treated as errors, which can be used with the
command-line options to turn specific warnings on or off. If the warning list contains an invalid number, an error is reported.
Examples
This table of examples of command line arguments describes what each argument does.
Argument Description
vbc /warnaserror Specifies that all warnings should be treated as errors.
vbc /nowarn:42024,42025 Specifies that warnings 42024 and 42025 should not be reported.
Types of Warnings
Following is a list of warnings that you might want to treat as errors.
Implicit Conversion Warning
Generated for instances of implicit conversion. They do not include implicit conversions from an intrinsic numeric type to a
string when using the & operator. Default for new projects is off.
ID: 42016
Late bound Method Invocation and Overload Resolution Warning
Generated for instances of late binding. Default for new projects is off.
ID: 42017
Operands of Type Object Warnings
Generated when operands of type Object occur that would create an error with Option Strict On. Default for new projects is
on.
ID: 42018 and 42019
Declarations Require 'As' Clause Warnings
Generated when a variable, function, or property declaration lacking an As clause would have created an error with Option
Strict On. Variables that do not have a type assigned to them are assumed to be type Object. Default for new projects is on.
ID: 42020 (variable declaration), 42021 (function declaration), and 42022 (property declaration).
Possible Null Reference Exception Warnings
Generated when a variable is used before it has been assigned a value. Default for new projects is on.
ID: 42104, 42030
Unused Local Variable Warning
Generated when a local variable is declared but never referred to. Default is on.
ID: 42024
Access of Shared member through Instance Variable Warning
Generated when accessing a shared member through an instance may have side effects, or when accessing a shared member
through an instance variable is not the right-hand side of an expression or is being passed in as a parameter. Default for new
projects is on.
ID: 42025
Recursive Operator or Property Access Warnings
Generated when the body of a routine uses the same operator or property it is defined in. Default for new projects is on.
ID: 42004 (operator), 42026 (property)
Function or Operator without Return Value Warning
Generated when the function or operator does not have a return value specified. This includes omitting a Set to the implicit
local variable with the same name as the function. Default for new projects is on.
ID: 42105 (function), 42016 (operator)
Overloads Modifier Used in a Module Warning
Generated when Overloads is used in a Module. Default for new projects is on.
ID: 42028
Duplicate or Overlapping Catch Blocks Warnings
Generated when a Catch block is never reached due to its relation to other Catch blocks that have been defined. Default for
new projects is on.
ID: 42029, 42031
See Also
Tasks
How to: Enable or Disable Compiler Warnings
Reference
Exception Assistant Dialog Box
/nowarn
/warnaserror (Visual Basic)
Compiler Warnings That Are Off by Default
Concepts
Types of Errors
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
A reference to the System namespace.
Robust Programming
Unhandled exceptions can cause application execution to halt. Use Try…Catch blocks to anticipate and handle possible
exceptions.
See Also
Tasks
How to: Catch an Exception in Visual Basic
How to: Test Code with a Try…Catch Block in Visual Basic
How to: Clean up Resources with a Try…Finally Block in Visual Basic
How to: Filter Errors in a Catch Block in Visual Basic
How to: Check an Exception's Inner Exception
Troubleshooting Exception Handling
Reference
Exception Class
Throw Statement (Visual Basic)
Concepts
Choosing When to Use Structured and Unstructured Exception Handling
Visual Basic Language Concepts
2. Within the Try block, supply Catch statements aimed at specific types of errors, going from the most specific to the least
specific. Here, the Catch statement first catches any IOException exceptions before looking for general exceptions.
VB
Catch ex As System.IO.FileNotFoundException
MsgBox("No such file in this directory.")
Catch ex As System.Exception
MsgBox("An unspecified error occurred.")
See Also
Tasks
How to: Clean up Resources with a Try…Finally Block in Visual Basic
How to: Filter Errors in a Catch Block in Visual Basic
How to: Check an Exception's Inner Exception
Troubleshooting Exception Handling
Reference
Try...Catch...Finally Statement (Visual Basic)
Concepts
Choosing When to Use Structured and Unstructured Exception Handling
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts
See Also
Tasks
How to: Test Code with a Try…Catch Block in Visual Basic
How to: Check an Exception's Inner Exception
How to: Dispose of a System Resource
Reference
Using Statement (Visual Basic)
Concepts
Exception Handling for Visual Basic 6.0 Users
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts
See Also
Tasks
How to: Check an Exception's Inner Exception
Troubleshooting Exception Handling
Reference
Try...Catch...Finally Statement (Visual Basic)
Concepts
Exception Handling for Visual Basic 6.0 Users
Choosing When to Use Structured and Unstructured Exception Handling
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts
See Also
Tasks
How to: Catch an Exception in Visual Basic
How to: Throw an Exception in Visual Basic
How to: Test Code with a Try…Catch Block in Visual Basic
How to: Check an Exception's Inner Exception
Troubleshooting Exception Handling
Reference
Try...Catch...Finally Statement (Visual Basic)
Other Resources
Structured Exception Handling in Visual Basic
Visual Basic Language Concepts
To check an InnerException
Check the InnerException property of the exception to determine the cause of the original error.
VB
Try
My.Computer.FileSystem.CopyFile("file1", "file2")
Catch ex As System.IO.IOException
MsgBox(ex.InnerException)
End Try
See Also
Tasks
How to: Display an Exception's Message in Visual Basic
Troubleshooting Exception Handling
Reference
InnerException
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts
Try
' Starts a structured exception handler.
' Place executable statements that may generate
' an exception in this block.
Catch [optional filters]
' This code runs if the statements listed in
' the Try block fail and the filter on the Catch statement is true.
[Additional Catch blocks]
Finally
' This code always runs immediately before
' the Try statement exits.
End Try
' Ends a structured exception handler.
The Try block of a Try...Catch...Finally exception handler contains the section of code to be monitored for exceptions. If an
error occurs during execution of this section, Visual Basic examines each Catch statement within the Try...Catch...Finally until
it finds one with a condition that matches that error. If one is found, control transfers to the first line of code in the Catch block.
If no matching Catch statement is found, the search proceeds to the Catch statements of the outer Try...Catch...Finally block
that contains the block in which the exception occurred. This process continues through the entire stack until a matching Catch
block is found in the current procedure. If no match is found, an error is produced.
The code in the Finally section always executes last, just before the error-handling block loses scope, regardless of whether the
code in the Catch blocks has executed. Place cleanup code, such as that for closing files and releasing objects, in the Finally
section. If you do not need to catch exceptions, but do need to clean up resources, consider using the Using statement rather
than a Finally section. For more information, see Using Statement (Visual Basic).
Error Filtering in the Catch Block
Catch blocks allow three options for specific error filtering. In one, errors are filtered based on the class of the exception (in
this case ClassLoadException), as shown in the following code.
Try
' "Try" block.
Catch e as ClassLoadException
' "Catch" block.
Finally
' "Finally" block.
End Try
If a ClassLoadException error occurs, the code within the specified Catch block is executed.
In the second error-filtering option, the Catch section can filter on any conditional expression. One common use of this type of
Catch filter is to test for specific error numbers, as shown in the following code.
Try
' "Try" block.
Catch When ErrNum = 5 'Type mismatch.
' "Catch" block.
Finally
' "Finally" block.
End Try
When Visual Basic finds the matching error handler, it executes the code within that handler, and then passes control to the
Finally block.
Note
When trying to find a Catch block to handle an exception, each block's handler is evaluated until a match is found. Since thes
e handlers can be calls to functions, there may be unexpected side effects; for example, such a call can change a public variabl
e that is then used in the code of a different Catch block that ends up handling the exception.
As a third alternative, you can combine options one and two, using both for exception handling. Your Catch statements should
move from most specific to least specific. A Catch block by itself will catch all exceptions derived from Exception, and therefore
should always be the last block before Finally.
Branching Out of Try…Catch Blocks
It is possible to branch from a Catch block back into the initial Try statement or the End Try statement, but it is not possible to
branch into an enclosing Try…Catch block. This is illustrated here:
The Finally block is always run, regardless of any actions occurring in preceding Catch blocks. You cannot use Resume or
Resume Next in structured exception handling.
Note
In the preceding example, any exception other than the IOException class or the EndOfStreamException class is propagated
back to the caller unhandled.
See Also
Tasks
Troubleshooting Exception Handling
Reference
Try...Catch...Finally Statement (Visual Basic)
Concepts
Introduction to Exception Handling
Types of Errors
Unstructured Exception Handling Overview
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts
HResult Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.
InnerException Gets the Exception instance that caused the current exception.
Source Gets or sets the name of the application or object that caused the error.
StackTrace Gets a string representation of the frames on the call stack at the time the current exception was thrown.
See Also
Tasks
Troubleshooting Exception Handling
Concepts
Introduction to Exception Handling
Types of Errors
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
Adding Functionality
Now that the controls and their properties are added and set, you must place code behind them to make them function. The
following code handles the Click event for the Order button and displays a message to the customer.
To add functionality to the form and its controls
Add the following code to the Order button's Click event.
VB
Dim bearOrder As String
bearOrder = _
String.Format("You have ordered a {0} {1} bear.", _
bearSize.SelectedItem, bearColor.SelectedItem)
MsgBox(bearOrder)
The application is now ready for you to add structured exception handling code.
Adding a Try...Catch Block
To ensure that the customer has specified a color for the bear, add a Try...Catch statement. Remember the following:
A Catch clause with no identifier catches all exceptions.
A Catch clause with a When clause catches exceptions only when the expression evaluates to True; the expression type
must be implicitly convertible to Boolean.
To add a simple Try...Catch block
Add the following code to the Order button's Click event after the section that tests the size and color values, that is, after
String.Format ("You have ordered a {0} {1} bear.", BearSize.SelectedItem, BearColor.SelectedItem). This
code throws an exception if it encounters an invalid color value. In adding Try statements, be aware that the editor
automatically supplies End Try at the end of the statement.
VB
Try
If ((bearColor.SelectedIndex < 0) Or _
(bearColor.SelectedIndex > 2)) Then
Throw New System.Exception()
End If
' The Catch statement handles errors caused by a lack of bear color.
Catch ex As Exception When bearColor.SelectedIndex < 0
bearOrder = String.Format("You must select a bear color!")
Finally
Beep() ' Beep at the end.
End Try
VB
Catch ex As Exception When bearColor.SelectedIndex = 3
bearOrder = String.Format("There are no bears of that color.")
Sub TestSub
On Error GoTo ErrorHandler
' Code that may or may not contain errors.
Exit Sub
ErrorHandler:
' Code that handles errors.
Resume
End Sub
The example contains an error handler named ErrorHandler. If any code in the TestSub subroutine generates an error, Visual
Basic immediately executes the code that follows the ErrorHandler label. At the end of the error-handling block, the Resume
statement passes control back to the line of code where the error first occurred. The rest of the subroutine then continues
executing as if the error did not occur.
Note
You must place an Exit Sub statement immediately before the error-handling block. Otherwise, Visual Basic runs the error-h
andling code when it reaches the end of the subroutine, causing unwanted or unexpected results.
Resume also can be used on its own, outside the On Error statement. When Resume is used this way, Visual Basic returns
control to the statement that caused the error. You generally use Resume after an error handler corrects the error.
Visual Basic also provides the Resume Next statement, which directs control to the line immediately following the line of code
that caused the error. You might use Resume Next for cases in which an error will not cause your application to stop working.
You might also use it if an error will not change the expected results of your subroutine.
Another variation on the Resume statement is Resume Line, which is similar to On Error GoTo Line. Resume Line passes
control to a line you specify in the line argument. You can use Resume Line only within an error handler.
Note
When debugging your code, you must disable the On Error Resume Next statement.
On Error GoTo 0
The On Error GoTo 0 statement disables any error handler in the current procedure. If you do not include an On Error GoTo 0
statement, the error handler is still disabled when the procedure containing the exception handler ends.
Note
The On Error GoTo 0 statement is not meant to specify line 0 as the start of the error-handling code, even if the procedure c
ontains a line numbered 0.
On Error GoTo -1
The On Error GoTo -1 statement disables any exception handlers in the current procedure. If you do not include an On Error
GoTo -1 statement, the exception is automatically disabled when its procedure ends.
Note
The On Error GoTo -1 statement is not meant to specify line -1 as the start of the error-handling code, even if the procedure
contains a line numbered -1.
Sub ErrorTest ()
' Declare variables.
Dim x As Integer, y As Integer, z As Integer
' The exception handler is named "DivideByZero".
On Error GoTo DivideByZero
' The main part of the code, which might cause an error.
x = 2
y = 0
z = x \ y
' This is the exception handler, which deals with the error.
DivideByZero:
' Include a friendly message to let the user know what is happening.
Console.WriteLine("You have attempted to divide by zero!")
End Sub
See Also
Tasks
How to: Retrieve Information from an Error Object
Reference
End Statement
Err Object (Visual Basic)
Exit Statement (Visual Basic)
On Error Statement (Visual Basic)
Resume Statement
Concepts
Err Object in Unstructured Exception Handling
Introduction to Exception Handling
Types of Errors
Choosing When to Use Structured and Unstructured Exception Handling
Visual Basic Language Concepts
Application-Specific Errors
In addition to handling errors generated by Visual Basic, you might also want to handle errors specific to your application.
If you create an object that accesses other objects, you should write code to deal with any unhandled errors the other objects
pass back. If necessary, you can map the error codes in Err.Number to one of your own application-specific errors, and then
pass it back to the caller of your object.
See Also
Reference
On Error Statement (Visual Basic)
Description Property (Err Object)
Number Property (Err Object)
HelpFile Property (Err Object)
HelpContext Property (Err Object)
LastDllError Property (Err Object)
Source Property (Err Object)
Concepts
Introduction to Exception Handling
Types of Errors
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Visual Basic Language Concepts
2. You can also examine specific properties of the error object, such as Description, Erl, HelpContext, Helpfile,
LastDLLError, Number, and Source. This example displays the description in a message box.
VB
MsgBox(Err.Description)
See Also
Reference
Err Object (Visual Basic)
Err Object Members
Description Property (Err Object)
Erl Property (Err Object)
HelpContext Property (Err Object)
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
Source Property (Err Object)
Concepts
Choosing When to Use Structured and Unstructured Exception Handling
Visual Basic Language Concepts
Sign an assembly with a strong name How to: Sign an Assembly with a Strong Name
Sign an assembly, but defer assigning a private key until a later time How to: Delay Sign an Assembly (Visual Studio)
Create a public/private key pair to use in creating a strong name How to: Create a Public/Private Key Pair
View binding information in the log file Assembly Binding Log Viewer (Fuslogvw.exe)
Deploy a Windows Forms control How to: Develop a Simple Windows Forms Control
Deploy an application for COM access Deploying an Application for COM Access
Choose which ClickOnce update strategy to use with your appli Choosing a ClickOnce Update Strategy
cation
Choose whether to use a ClickOnce data directory, isolated stor Accessing Local and Remote Data in ClickOnce Applications
age, or other local files when reading and writing data
Discover what prerequisites must be met before successfully d Deploying Prerequisites (Visual Studio)
eploying an application
Specify an alternate location for deployment updates How to: Specify an Alternate Location for Deployment Updates
Elevate a ClickOnce application's permission level on a client co Trusted Application Deployment Overview
mputer
Difficulties when deploying applications with ClickOnce may be caused by HTTP compression issues, manifest parsing issues,
server configuration issues, and versioning issues. For more information, see Troubleshooting ClickOnce Deployment.
Windows Installer Deployment
Microsoft Windows Installer technology creates installers that give you complete control over the installation process.
This table shows tasks associated with Windows Installer deployment.
To See
Distribute files or applications o Deployment Via Distributable Media
n CD-ROM or other media
Create a new setup project or ad How to: Create or Add a Setup Project
d an existing deployment projec
t to a solution
Create a new .cab file for Web d How to: Create or Add a Cab Project
ownload or add an existing one
to a solution
Create a merge module for a co How to: Add Merge Modules to a Deployment Project
mponent
Deploy a Web site to a Web serv Deploying ASP.NET Web Sites (Visual Studio)
er
Pass data to a dynamic property Walkthrough: Using a Custom Action to Display a Message at Installation
during installation using a custo
m action
Use a custom action to pre-com Walkthrough: Using a Custom Action to Pre-Compile an Assembly at Installation
pile an assembly during installat
ion
Use a custom action to create a Walkthrough: Using a Custom Action to Create a Database at Installation
database during installation
Create a Web application that ca Walkthrough: Redirecting an Application to Target a Different XML Web Service at Installation
n be redirected to target a differ
ent XML Web service
See Also
Concepts
Deployment Alternatives
Other Resources
Windows Installer Deployment Walkthroughs
Visual Basic Language Concepts
See Also
Tasks
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
Other Resources
Authentication and Authorization in the .NET Framework with Visual Basic
Visual Basic Language Concepts
If My.User.IsInRole(ApplicationServices.BuiltInRole.Administrator) Then
Me.Label2.Text = "User is an Administrator"
Else
Me.Label2.Text = "User is not an Administrator"
End If
You can run the application, but because there is no authentication code, it will not authenticate any user. Adding
authentication code is discussed in the following section.
Creating an Identity
The .NET Framework uses the IIdentity and IPrincipal interfaces as the basis for authentication and authorization. Your
application can use custom user authentication by implementing these interfaces, as these procedures demonstrate.
To create a class that implements IIdentity
1. Select the SampleIIdentity.vb file in Solution Explorer.
This class encapsulates a user's identity.
2. In the line following Public Class SampleIIdentity, add the following code to inherit from IIdentity.
VB
Implements System.Security.Principal.IIdentity
After you add that code and press ENTER, the Code Editor creates stub properties that you must implement.
3. Add private fields to store the user name and a value that indicates if the user is authenticated.
VB
Private nameValue As String
Private authenticatedValue As Boolean
Private roleValue As ApplicationServices.BuiltInRole
The IsAuthenticated property needs to return a value that indicates whether the user has been authenticated.
6. The Name property needs to return the name of the user associated with this identity.
Enter the following code in the Name property.
VB
Return nameValue
8. Create a Sub New method that initializes the class by authenticating the user and then setting the user name and role,
based on a name and a password.
This method calls a method named IsValidNameAndPassword to determine if a user name and password combination is
valid.
VB
Public Sub New(ByVal name As String, ByVal password As String)
' The name is not case sensitive, but the password is.
If IsValidNameAndPassword(name, password) Then
nameValue = name
authenticatedValue = True
roleValue = ApplicationServices.BuiltInRole.Administrator
Else
nameValue = ""
authenticatedValue = False
roleValue = ApplicationServices.BuiltInRole.Guest
End If
End Sub
9. Create a method named IsValidNameAndPassword that determines if a user name and password combination is valid.
Security Note
The authentication algorithm must treat passwords securely. For example, the password should not be stored in a class
field.
You should not store user passwords in your system, because if that information is leaked, there is no more security. You
could store the hash of each user's password. (A hash function scrambles data so the input cannot be deduced from the
output.) A password cannot be directly determined from the hash of a password.
However, a malicious user could take the time to generate a dictionary of the hashes of all possible passwords, and then
look up the password for a given hash. To protect against this type of attack, you should add salt to the password before
hashing it, to generate a salted hash. Salt is extra data that is unique to each password, which make it impossible to
precompute a hash dictionary.
To protect the passwords from malicious users, you should store only salted hashes of the passwords, preferably on a
secure computer. It is very difficult for a malicious user to recover a password from a salted hash. This example uses the
GetHashedPassword and GetSalt methods to load a user's hashed password and salt.
VB
Private Function IsValidNameAndPassword( _
ByVal username As String, _
ByVal password As String) _
As Boolean
' Look up the stored hashed password and salt for the username.
Dim storedHashedPW As String = GetHashedPassword(username)
Dim salt As String = GetSalt(username)
10. Create functions named GetHashedPassword and GetSalt that return the hashed password and salt for the specified user.
Security Note
You should avoid hard coding the hashed passwords and salts into your client applications for two reasons. First, malici
ous users may be able to access them and find a hash collision. Second, you cannot change or revoke a user's passwor
d. The application should obtain the hashed password and salt for a given user from a secure source that an administra
tor maintains.
Although, for simplicity, this example has a hard-coded, hashed password and salt, you should use a more secure
approach in production code. For example, you could store the user information in a SQL Server database and access it
with stored procedures. For more information, see How to: Connect to Data in a Database.
Note
The password corresponding to this hard-coded hashed password is given in the "Testing the Application" section.
VB
Private Function GetHashedPassword(ByVal username As String) As String
' Code that gets the user's hashed password goes here.
' This example uses a hard-coded hashed passcode.
' In general, the hashed passcode should be stored
' outside of the application.
If Trim(username).ToLower = "testuser" Then
Return "ZFFzgfsGjgtmExzWBRmZI5S4w6o="
Else
Return ""
End If
End Function
End Class
Creating a Principal
Next, you need to implement a class that derives from IPrincipal, and have it return instances of the SampleIIdentity class.
To create a class that implements IPrincipal
1. Select the SampleIPrincipal.vb file in Solution Explorer.
This class encapsulates a user's identity. You can use the My.User object to attach this principal to the current thread and
access the user's identity.
2. In the line following Public Class SampleIPrincipal, add the following code to inherit from IPrincipal.
VB
Implements System.Security.Principal.IPrincipal
After you add that code and press ENTER, the Code Editor creates a stub property and method that you must implement.
3. Add a private field to store the identity associated with this principal.
VB
Private identityValue As SampleIIdentity
The Identity property needs to return the user identity of the current principal.
5. Enter the following code in the IsInRole method.
The IsInRole method determines whether the current principal belongs to the specified role.
VB
Return role = identityValue.Role.ToString
6. Create a Sub New method that initializes the class with a new instance of SampleIIdentity given a user name and
password.
VB
Public Sub New(ByVal name As String, ByVal password As String)
identityValue = New SampleIIdentity(name, password)
End Sub
This code sets the user identity for the SampleIPrincipal class.
The SampleIPrincipal.vb file should now contain the following code:
VB
Public Class SampleIPrincipal
Implements System.Security.Principal.IPrincipal
End Class
Connecting the Login Form
The application can use the login form to gather a user name and password. It can use this information to initialize an instance
of the SampleIPrincipal class and use the My.User object to set the current thread's identity to that instance.
To configure the login form
1. Select LoginForm1 in the designer.
2. Double-click the OK button to open the Code Editor for the Click event.
3. Replace the code in the OK_Click method with the following code.
VB
Dim samplePrincipal As New SampleIPrincipal( _
Me.UsernameTextBox.Text, Me.PasswordTextBox.Text)
Me.PasswordTextBox.Text = ""
If (Not samplePrincipal.Identity.IsAuthenticated) Then
' The user is still not validated.
MsgBox("The username and password pair is incorrect")
Else
' Update the current principal.
My.User.CurrentPrincipal = samplePrincipal
Me.Close()
End If
See Also
Tasks
How to: Connect to Data in a Database
Reference
My.User Object
IIdentity
IPrincipal
Concepts
Accessing User Data
Other Resources
Authentication and Authorization in the .NET Framework with Visual Basic
Authentication and Authorization in the .NET Framework with Visual Basic
Visual Basic Language Concepts
IdentityReference Represents an identity and is the base class for the NTAccount and SecurityIdentifier classes.
SecurityIdentifier Represents a security identifier (SID) and provides marshaling and comparison operations for SIDs.
The following classes implement the IPrincipal interface, which defines the basic functionality of a principal object.
Class Description
GenericPrincipal Represents a generic principal.
WindowsPrincipal Allows code to check the Windows group membership of a Windows user.
This table lists the most important enumerations used for .NET Framework user operations.
Enumeration Description
PrincipalPolicy Specifies how principal and identity objects should be created for an application domain.
See Also
Tasks
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
Other Resources
Authentication and Authorization in the .NET Framework with Visual Basic
Visual Basic Language Concepts
MessageQueuePermission Access to message queues through the managed Message Queuing (also known as MSMQ) i
nterfaces.
RegistryPermission Reading from, writing to, creating, or deleting registry keys and values.
SecurityPermission Executing, asserting permissions, calling into unmanaged code, skipping verification, and othe
r security-related rights.
Request optional permissions How to: Request Optional Permissions by Using the RequestOptional Flag
Request permission for a named per How to: Request Permission for a Named Permission Set
mission set
Refuse permissions How to: Refuse Permissions by Using the RequestRefuse Flag
Perform an imperative security check How to: Perform Imperative Security Checks
Share a library with partially trusted c Sharing a Library with Partially Trusted Code
ode
Require full trust for types within an Requiring Full Trust for Types Within an AllowPartiallyTrustedCallersAttribute Assembly
AllowPartiallyTrustedCallersAttribute
assembly
Create GenericPrincipal and How to: Create GenericPrincipal and GenericIdentity Objects
GenericIdentity objects
Internet Default policy permission set suitable for content from unknown origin.
Call functions in a specific application domain Calling Functions in a Specific Application Domain
Retrieve setup information from an application domain Retrieving Setup Information from an Application Domain
For more information, see AppDomain, Application Domain Hosts and Programming with Application Domains.
See Also
Tasks
Troubleshooting Code Access Security Exceptions
Concepts
Isolation by User, Domain, and Assembly
Other Resources
Configuring Security Policy Using the .NET Framework Configuration Tool (Mscorcfg.msc)
Configuring Security Policy Using the Code Access Security Policy Tool (Caspol.exe)
Visual Basic Language Concepts
BitArray Manages a compact array of bit values, which are represented as Boolean values, where True indicates that the bit
is on (1) and False indicates the bit is off (0).
Hashtable Represents a collection of key/value pairs that are organized based on the hash code of the key.
KeyedCollection Provides the abstract base class for a collection whose keys are embedded within the values.
List Implements the IList interface using an array whose size is dynamically increased as required.
SortedDictionary Represents a collection of key/value pairs that are sorted on the key.
SortedList Represents a collection of key/value pairs that are sorted by key based on the associated IComparer imple
mentation.
Stack Represents a variable size last-in-first-out (LIFO) collection of instances of the same arbitrary type.
System.Collections.Specialized Classes
The System.Collections.Specialized namespace provides specialized and strongly typed collection classes, such as string-
only collections and linked-list and hybrid dictionaries.
The following table lists some of the commonly used classes:
Class Description
CollectionsUtil Creates collections that ignore the case in strings.
HybridDictionary Implements IDictionary by using a ListDictionary while the collection is small, and then switching t
o a Hashtable when the collection gets large.
ListDictionary Implements IDictionary using a singly linked list. Recommended for collections that typically cont
ain 10 items or less.
NameObjectCollectionBase Provides the abstract base class for a collection of associated string keys and object values that can
be accessed either with the key or with the index.
NameValueCollection Represents a collection of associated string keys and string values that can be accessed either with
the key or with the index.
OrderedDictionary Represents a collection of key/value pairs that are ordered based on the key or index.
StringDictionary Implements a hash table with the key and the value strongly typed to be strings rather than object
s.
See Also
Reference
Collection Object (Visual Basic)
Concepts
Collections in Visual Basic
Other Resources
Going Further with Visual Basic
Visual Basic Language Concepts
Stream Operations
The data contained in the stream may come from memory, a file, or a TCP/IP socket. Streams have fundamental operations
that can be applied to them:
Reading. You can read from a stream, transferring data from the stream into a data structure, such as a string or an array
of bytes.
Writing. You can write to a stream, transferring data from a data source into the stream.
Seeking. You can query and modify your position in the stream.
For more information, see Composing Streams.
Types of Streams
In the .NET Framework, a stream is represented by the Stream class, which forms the abstract class for all other streams. You
cannot directly create an instance of the Stream class, but must use one of the classes it implements.
There are many types of streams, but for the purposes of working with file input/output (I/O), the most important types are the
FileStream class, which provides a way to read from and write to files, and the IsolatedStorageFileStream class, which provides
a way to create files and directories in isolated storage. Other streams that can be used when working with file I/O include:
BufferedStream
CryptoStream
MemoryStream
NetworkStream.
The following table lists tasks commonly accomplished with a stream:
To See
Read and write to a data file How to: Read and Write to a Newly Created Data File
Read characters from a string How to: Read Characters from a String
File Permissions
Controlling access to files and directories can be done with the FileIOPermission class. This may be particularly important for
developers working with Web Forms, which by default run within the context of a special local user account named ASPNET,
which is created as part of the ASP.NET and .NET Framework installations. When such an application requests access to a
resource, the ASPNET user account has limited permissions, which may prevent the user from performing actions such as
writing to a file from a Web application. For more information, see Security Permissions, Requesting Permissions, and the
FileIOPermission Class.
The following table lists tasks involving file permissions.
To See
Request minimum permissions How to: Request Permission to Access Unmanaged Code
Request optional permissions How to: Request Optional Permissions by Using the RequestOptional Flag
Refuse permissions How to: Refuse Permissions by Using the RequestRefuse Flag
Request built-in permissions How to: Request Permission for a Named Permission Set
Enumerate isolated stores How to: Enumerate Stores for Isolated Storage
Create a file or directory in isolated storage How to: Create Files and Directories in Isolated Storage
Find a file in isolated storage How to: Find Existing Files and Directories in Isolated Storage
Read from or write to a file in insolated storage How to: Read and Write to Files in Isolated Storage
Delete a file or directory in isolated storage How to: Delete Files and Directories in Isolated Storage
File Events
The FileSystemWatcher component allows you to watch for changes in files and directories on your system or on any
computer to which you have network access. For example, if a file is modified, you might want to send a user an alert that the
change has taken place. When changes occur, one or more events are raised, stored in a buffer, and handed to the
FileSystemWatcher component for processing. For more information, see Reacting to File System Events.
To See
Create a handler for file system events How to: Create Handlers for File System Events
Configure a FileSystemWatcher component instance How to: Configure FileSystemWatcher Component Instances
See Also
Concepts
Composing Streams
Basic File I/O
Asynchronous File I/O
Classes Used in .NET Framework File I/O and the File System
Other Resources
Isolated Storage
Visual Basic Language Concepts
Classes Used in .NET Framework File I/O and the File System
The following tables list the classes commonly used for .NET Framework file I/O, categorized into file I/O classes, classes used
for creating streams, and classes used to read and write to streams.
To enter the .NET Framework 2.0 documentation and find a more comprehensive listing, see
.NET Framework Class Library Overview.
Basic I/O Classes for Files, Drives, and Directories
The following table lists and describes the main classes used for file I/O.
Class Description
System.IO.Directory Provides static methods for creating, moving, and enumerating through directo
ries and subdirectories.
System.IO.DirectoryInfo Provides instance methods for creating, moving, and enumerating through dire
ctories and subdirectories.
System.IO.DriveInfo Provides instance methods for creating, moving, and enumerating through driv
es.
System.IO.File Provides static methods for creating, copying, deleting, moving, and opening fil
es, and aids in the creation of a FileStream.
System.IO.FileAttributes Provides attributes for files and directories such as Archive, Hidden, and
ReadOnly.
System.IO.FileInfo Provides static methods for creating, copying, deleting, moving, and opening fil
es, and aids in the creation of a FileStream.
System.IO.FileMode Controls how a file is opened. This parameter is specified in many of the constru
ctors for FileStream and IsolatedStorageFileStream, and for the Open meth
ods of File and FileInfo.
System.IO.FileShare Defines constants for controlling the type of access other file streams can have t
o the same file.
System.Security.Permissions.FileIOPermission Controls the access of files and folders by defining Read, Write, Append and
PathDiscovery permissions.
System.IO.FileStream Supports random access to files through its Seek method. FileStream opens file
s synchronously by default but also supports asynchronous operation.
System.IO.MemoryStream Creates a stream whose backing store is memory, rather than a file.
System.Net.Sockets.NetworkStream Provides the underlying stream of data for network access.
System.IO.StreamReader Reads characters from a FileStream, using CurrentEncoding to convert characters to and from bytes.
StreamReader has a constructor that attempts to ascertain the correct CurrentEncoding for a give
n stream, based on the presence of a CurrentEncoding-specific preamble, such as a byte order mar
k.
System.IO.StringReader Reads characters from a String. Output can be either a stream in any encoding or a String.
System.IO.StringWriter Writes characters to a String. Output can be either a stream in any encoding or a String.
See Also
Concepts
Composing Streams
Basic File I/O
Asynchronous File I/O
Basics of .NET Framework File I/O and the File System
Other Resources
Isolated Storage
Visual Basic Language Concepts
System.Drawing.Font Defines a particular format for text, including font face, size, and style attributes.
System.Drawing.Point Represents an ordered pair of integer x- and y-coordinates that defines a point in a two-dimensi
onal plane.
System.Drawing.Rectangle Stores a set of four integers that represent the location and size of a rectangle. For more advanc
ed region functions, use a Region object.
System.Drawing.SolidBrush Defines a brush of a single color. Brushes are used to fill graphics shapes, such as rectangles, elli
pses, pies, polygons, and paths.
System.Drawing.TextureBrush Each property of the TextureBrush class is a Brush object that uses an image to fill the interior
of a shape.
Resource Management
Many of the drawing classes implement IDisposable because they encapsulate unmanaged system resources. If you create a
new instance of one of these classes, you should call the class's Dispose method when you are through with the object.
Alternatively, you can create the object with the Using statement, which implicitly calls the object's Dispose method. For more
information, see Object Lifetime: How Objects Are Created and Destroyed and Using Statement (Visual Basic).
Related Sections
Graphics for Visual Basic 6.0 Users
Describes changes to the graphics rendering model in Visual Basic 2005.
Graphics and Drawing in Windows Forms
Roadmap for using graphics in Windows Forms applications.
Graphics Overview (Windows Forms)
Provides an introduction to the graphics-related managed classes.
About GDI+ Managed Code
Provides information regarding the managed GDI+ classes.
Using Managed Graphics Classes
Demonstrates how to complete a variety of tasks using the GDI+ managed classes.
Custom Control Painting and Rendering
Details how to provide code for painting controls.
Image Web Server Control Overview
Describes the control that you can use to display images on a Web Forms page and to manage the images with code.
Image Editor
Provides links to topics on how to use the image editor to create image files for use in your application.
See Also
Reference
Using Statement (Visual Basic)
System.Drawing
Concepts
Object Lifetime: How Objects Are Created and Destroyed
Visual Basic Language Concepts
Trace Provides a set of methods and properties that help you trace the execution of your code. This class cannot be inhe
rited.
TraceSource Provides a set of methods and properties that help you trace the execution of your code.
Log-Listener Classes
The following table lists and describes the main log-listener classes.
Class Description
TraceListener Provides the abstract base class for the listeners who monitor trace and debug output.
ConsoleTraceListener Directs tracing or debugging output to either the standard output or the standard error stream.
DefaultTraceListener Provides the default output methods and behavior for tracing.
DelimitedListTraceListener Directs tracing or debugging output to a TextWriter, such as StreamWriter, or to a Stream, such as
FileStream.
EventLogTraceListener Provides a simple listener that directs tracing or debugging output to an EventLog.
TextWriterTraceListener Directs tracing or debugging output to a TextWriter or to a Stream such as Out or FileStream.
BooleanSwitch Provides a simple on/off switch that controls debugging and tracing output.
SourceSwitch Provides a multilevel switch to control tracing and debug output without recompiling your code.
TraceSwitch Provides a multilevel switch to control tracing and debug output without recompiling your code.
EventTypeFilter Provides a severity level based switch that controls tracing output.
SourceFilter Specifies if a listener should trace a message based on the source of a trace.
See Also
Reference
System.Diagnostics
Concepts
Logging and Tracing in the .NET Framework with Visual Basic
Basics of .NET Framework Logs
Other Resources
Tracing and Instrumenting Applications
Visual Basic Language Concepts
Pluggable Protocols
The abstract WebRequest and WebResponse classes provide the base classes for pluggable protocols. By deriving protocol-
specific classes from WebRequest and WebResponse, an application can request data from an Internet resource and read the
response without specifying the protocol used.
For more information, see Programming Pluggable Protocols.
The following table lists common tasks involving pluggable protocols.
To See
Derive from WebRequest Deriving from WebRequest
Access protocol specific properties How to: Typecast a WebRequest to Access Protocol Specific Properties
Network Tracing
Network tracing provides access to information about invoking methods and information about network traffic generated by a
managed application. This feature is useful for debugging applications under development and for analyzing deployed
applications. The output provided by network tracing is customizable to support different usage scenarios at development time
and in a production environment.
For more information, see Network Tracing.
The following table lists common tasks involving network tracing.
To See
Enable network tracing Enabling Network Tracing
Cache Management
A cache provides temporary storage of resources that have been requested by an application. If an application requests the
same resource more than once, the resource can be returned from the cache, avoiding the overhead of requesting it again
from the server.
A cache policy defines rules that are used to determine whether a request can be satisfied using a cached copy of the requested
resource.
For more information, see Cache Management for Network Applications.
The following table lists common tasks involving cache management.
To See
Set a location-based cache policy How to: Set a Location-based Cache Policy for an Application
Set a default time-based cache policy How to: Set the Default Time-Based Cache Policy for an Application
Customize a time-based cache policy How to: Customize a Time-Based Cache Policy
Set cache policy for a request How to: Set Cache Policy for a Request
Security
The System.Net classes provide a secure environment for Internet applications by providing built-in support for commonly
used Internet-application authentication mechanisms and for .NET Framework code-access permissions.
For more information, see Best Practices for System.Net Classes.
The following table lists common tasks involving security.
To See
Use Secure Sockets Layer (SSL) connections to an HTTP server Using Secure Sockets Layer
Use HTTP authentication methods to establish an authenticated connectio Internet Authentication
n to an HTTP server.
Set code-access security for applications that use Internet connections. Web and Socket Permissions
Use System.Net to secure XML Web Services. Securing XML Web Services Created Using ASP.NET
See Also
Reference
System.Net
System.Net.Sockets
Concepts
Best Practices for System.Net Classes
Configuring Internet Applications
Other Resources
Network Programming
Network Namespaces in Visual Studio
Visual Basic Language Concepts
WebClient Provides common methods for sending data to and receiving data from a resource identified
by a URI (Uniform Resource Identifier).
System.Net.Sockets Provides a managed implementation of the Windows Sockets (Winsock) interface for develop
ers who need to tightly control access to the network.
See Also
Concepts
Basics of .NET Framework Network Operations
Visual Basic Language Concepts
Enumerations
This table lists and describes the main enumerations used for accessing a serial port:
Enumeration Description
Handshake Specifies the control protocol used in establishing a serial port communication for a SerialPort object.
SerialData Specifies the type of character that was received on the serial port of the SerialPort object.
SerialPinChange Specifies the type of change that occurred on the SerialPort object.
StopBits Specifies the number of stop bits used on the SerialPort object.
Tasks
This table lists and describes the main tasks for accessing a serial port:
To See
Show available serial ports How to: Show Available Serial Ports in Visual Basic
Dial a modem attached to the serial port of a computer How to: Dial Modems Attached to Serial Ports in Visual Basic
Send a string to a computer's serial port How to: Send Strings to Serial Ports in Visual Basic
Receive a string from a computer's serial port How to: Receive Strings From Serial Ports in Visual Basic
See Also
Reference
My.Computer.Ports Object
Other Resources
Accessing the Computer's Ports
Going Further with Visual Basic
Visual Basic Language Concepts
The object is serialized to a stream, which carries not just the data, but information about the object's type, such as its version,
culture, and assembly name. From that stream, it can be stored in a database, a file, or memory.
Uses for Serialization
Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well
as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by
means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string,
or maintaining security or user-specific information across applications.
Making an Object Serializable
To serialize an object, you need the object to be serialized, a stream to contain the serialized object, and a Formatter.
System.Runtime.Serialization contains the classes necessary for serializing and deserializing objects.
Apply the SerializableAttribute attribute to a type to indicate that instances of this type can be serialized. A
SerializationException exception is thrown if you attempt to serialize but the type does not have the SerializableAttribute
attribute.
If you do not want a field within your class to be serializable, apply the NonSerializedAttribute attribute. If a field of a
serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and the
field cannot be meaningfully reconstituted in a different environment, then you may want to make it nonserializable.
If a serialized class contains references to objects of other classes that are marked SerializableAttribute, those objects will
also be serialized.
Binary and XML Serialization
Either binary or XML serialization can be used. In binary serialization, all members, even those that are read-only, are serialized,
and performance is enhanced. XML serialization provides more readable code, as well as greater flexibility of object sharing
and usage for interoperability purposes.
Binary Serialization
Binary serialization uses binary encoding to produce compact serialization for uses such as storage or socket-based network
streams. It is not suitable for passing data through a firewall but provides better performance when storing data.
XML Serialization
XML serialization serializes the public fields and properties of an object, or the parameters and return values of methods, into
an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML serialization results in
strongly typed classes with public properties and fields that are converted to XML. System.Xml.Serialization contains the
classes necessary for serializing and deserializing XML.
You can apply attributes to classes and class members in order to control the way the XmlSerializer serializes or deserializes an
instance of the class. For more information, see Controlling XML Serialization Using Attributes and
Attributes That Control XML Serialization.
This table lists tasks associated with XML serialization:
To See
Serialize an object How to: Serialize an Object
Generate classes and XML Sch How to: Use the XML Schema Definition Tool to Generate Classes and XML Schema Documents
ema documentation
Qualify XML element and XML How to: Qualify XML Element and XML Attribute Names
attribute names
Specify an alternate element n How to: Specify an Alternate Element Name for an XML Stream
ame for an XML Stream
Override SOAP-encoded XML serialization How to: Override Encoded SOAP XML Serialization
System.Xml.Serialization Contains the classes necessary for serializing and deserializing XML.
NonSerializedAttribute Can be used to keep specific fields in an object from being serialized.
See Also
Concepts
Basics of .NET Framework Serialization
Visual Basic Language Concepts
Activate applications from a physical hardware button with a HardwareButton co How to: Use the HardwareButton Component
mponent in your application
Use an InputPanel component in your application How to: Use the InputPanel Component
Select Pocket PC input methods for user input in your application How to: Set Pocket PC Input Methods
Send and respond to a notification in your application How to: Send a Notification
Override the back key How to: Override the Smartphone Back Key
See Also
Concepts
.NET Compact Framework How-To Topics
Other Resources
Pocket PC Development and the .NET Compact Framework
Smartphone Development and the .NET Compact Framework
Windows CE Development
.NET Compact Framework Product Information
Visual Basic Language Concepts
Thread Timers
The System.Threading.Timer class is useful for periodically running a task on a separate thread. For example, you could use a
thread timer to check the status and integrity of a database or to back up critical files.
Thread Timer Example
The following example starts a task every two seconds and uses a flag to initiate the Dispose method that stops the timer. This
example posts status to the output window, so you should make this window visible by pressing CTRL+ALT+O before you test
the code.
VB
Class StateObjClass
' Used to hold parameters for calls to TimerTask
Public SomeValue As Integer
Public TimerReference As System.Threading.Timer
Public TimerCanceled As Boolean
End Class
Sub RunTimer()
Dim StateObj As New StateObjClass
StateObj.TimerCanceled = False
StateObj.SomeValue = 1
Dim TimerDelegate As New Threading.TimerCallback(AddressOf TimerTask)
' Create a timer that calls a procedure every 2 seconds.
' Note: There is no Start method; the timer starts running as soon as
' the instance is created.
Dim TimerItem As New System.Threading.Timer(TimerDelegate, StateObj, _
2000, 2000)
StateObj.TimerReference = TimerItem ' Save a reference for Dispose.
Thread timers are particularly useful when the System.Windows.Forms.Timer object is unavailable, such as when you are
developing console applications.
See Also
Reference
SyncLock Statement
System.Threading
Concepts
Advanced Multithreading with Visual Basic
Multithreaded Applications
Visual Basic Language Concepts
Thread Pooling
Thread pooling is a form of multithreading in which tasks are added to a queue and automatically started when threads are
created. With thread pooling, you call the System.Threading.ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback)
method with a delegate for the procedure you want to run, and Visual Basic creates the thread and runs your procedure.
Thread Pooling Example
The following example shows how you can use thread pooling to start several tasks.
VB
Sub DoWork()
' Queue a task
System.Threading.ThreadPool.QueueUserWorkItem( _
New System.Threading.WaitCallback(AddressOf SomeLongTask))
' Queue another task
System.Threading.ThreadPool.QueueUserWorkItem( _
New System.Threading.WaitCallback(AddressOf AnotherLongTask))
End Sub
Sub SomeLongTask(ByVal state As Object)
' Insert code to perform a long task.
End Sub
Sub AnotherLongTask(ByVal state As Object)
' Insert code to perform another long task.
End Sub
Thread pooling is useful when you want to start many separate tasks without individually setting the properties of each thread.
Each thread starts with a default stack size and priority. By default, up to 25 thread-pool threads can run per system processor.
Additional threads in excess of the limit can be queued, but they do not start until other threads finish.
One advantage of thread pooling is that you can pass arguments in a state object to the task procedure. If the procedure you
are calling requires more than one argument, you can cast a structure or an instance of a class into an Object data type.
Thread Pool Parameters and Return Values
Returning values from a thread-pool thread is not straightforward. The standard way of returning values from a function call is
not allowed because Sub procedures are the only type of procedure that can be queued to a thread pool. One way you can
provide parameters and return values is by wrapping the parameters, return values, and methods in a wrapper class as
described in Parameters and Return Values for Multithreaded Procedures.
An easer way to provide parameters and return values is by using the optional ByVal state object variable of the
QueueUserWorkItem method. If you use this variable to pass a reference to an instance of a class, the members of the
instance can be modified by the thread-pool thread and used as return values.
At first it may not be obvious that you can modify an object referred to by a variable that is passed by value. You can do this
because only the object reference is passed by value. When you make changes to members of the object referred to by the
object reference, the changes apply to the actual class instance.
Structures cannot be used to return values inside state objects. Because structures are value types, changes that the
asynchronous process makes do not change the members of the original structure. Use structures to provide parameters when
return values are not needed.
See Also
Reference
SyncLock Statement
QueueUserWorkItem
System.Threading
Concepts
Advanced Multithreading with Visual Basic
Multithreaded Applications
Thread Synchronization
Multithreading with Forms and Controls
Visual Basic Language Concepts
Thread Synchronization
As you write a threaded application, you may need to synchronize individual threads with other parts of your program.
Synchronization provides a compromise between the unstructured nature of multithreaded programming and the structured
order of synchronous processing.
You use synchronization techniques:
To explicitly control the order in which code runs whenever tasks must be performed in a specific sequence
-or-
To prevent the problems that can occur when two threads share the same resource at the same time.
For example, you could use synchronization to cause a display procedure to wait until a data retrieval procedure that is running
on another thread is complete.
Synchronization Techniques
There are two approaches to synchronization, polling and using synchronization objects. See
Advanced Synchronization Techniques for more information on synchronization objects.
Polling
Polling repeatedly checks the status of an asynchronous call from within a loop. Polling is the least efficient way to manage
threads because it wastes resources by repeatedly checking the status of the various thread properties.
For example, the IsAlive property can be used when polling to see if a thread has exited. Use this property with caution because
a thread that is alive is not necessarily running.
You can use the thread's ThreadState property to get more detailed information about a thread's status. Because threads can
be in more than one state at any given time, the value stored in ThreadState can be a combination of the values in the
System.Threading.ThreadState enumeration. Consequently, you should carefully check all relevant thread states when polling.
For example, if a thread's state indicates that it is not Running, it may be done. On the other hand, it may be suspended or
sleeping.
Waiting for a Thread to Finish
The System.Threading.Thread.Join method is useful for determining if a thread has completed before starting another task. The
Join method waits a specified amount of time for a thread to end. If the thread ends before the timeout, Join returns True;
otherwise it returns False.
As you can imagine, polling sacrifices many of the advantages of multithreading in return for control over the order that
threads run. Because it is so inefficient, polling is generally not recommended. A more efficient approach would use the Join
method to control threads. Join causes a calling procedure to wait either until a thread is done or until the call times out if a
time-out is specified. The name "join" is based on the idea that creating a new thread is a fork in the execution path. You use
Join to merge separate execution paths into a single thread again.
Figure 1 Threading
One point should be clear: Join is a synchronous or blocking call. Once you call Join, or a wait method of a wait handle, the
calling procedure stops and waits for the thread to signal that it is done.
VB
Sub JoinThreads()
Dim Thread1 As New System.Threading.Thread(AddressOf SomeTask)
Thread1.Start()
Thread1.Join() ' Wait for the thread to finish.
MsgBox("Thread is done")
End Sub
Sub SomeTask()
' Insert code to perform a task here.
End Sub
These simple ways of controlling threads, which are useful when you are managing a small number of threads, are difficult to
use with large projects. Advanced Synchronization Techniques discusses some techniques you can use to synchronize threads.
See Also
Concepts
Advanced Multithreading with Visual Basic
Parameters and Return Values for Multithreaded Procedures
Other Resources
Multithreading in Visual Basic
Visual Basic Language Concepts
ReaderWriter Locks
In some cases, you may want to lock a resource only when data is being written and permit multiple clients to simultaneously
read data when data is not being updated. The ReaderWriterLock class enforces exclusive access to a resource while a thread
is modifying the resource, but it allows non-exclusive access when reading the resource. ReaderWriter locks are a useful
alternative to exclusive locks, which cause other threads to wait, even when those threads do not need to update data.
Deadlocks
Thread synchronization is invaluable in multithreaded applications, but there is always the danger of creating a deadlock,
where multiple threads are waiting for each other and the application comes to a halt. A deadlock is analogous to a situation in
which cars are stopped at a four-way stop and each person is waiting for the other to go. Avoiding deadlocks is important; the
key is careful planning. You can often predict deadlock situations by diagramming multithreaded applications before you start
coding.
See Also
Reference
SyncLock Statement
System.Threading
Concepts
Advanced Multithreading with Visual Basic
Thread Synchronization
Thread States
Multithreaded Applications
Other Resources
Multithreading in Components
Visual Basic Language Concepts
Handle events from a form and its c How to: Create Event Handlers Using the Designer
ontrols
Use the ToolStrip Control How to: Create a Basic Windows Forms ToolStrip with Standard Items Using the Designer
Create custom controls How to: Inherit from the UserControl Class
Work with ADO.NET data sour How to: Sort and Filter ADO.NET Data with the Windows Forms BindingSource Component
ces
Use the Data Sources window Walkthrough: Displaying Data on a Form in a Windows Application
Use application settings How to: Create Application Settings Using the Designer
Update a ClickOnce deployment How to: Manage Updates for a ClickOnce Application
Check for application updates How to: Check for ClickOnce Application Updates
Manage security with ClickOnce How to: Enable ClickOnce Security Settings
Learn more about Windows Forms security Security in Windows Forms Overview
See Also
Reference
Windows Forms Overview
My.Forms Object
My.Application Object
Concepts
Overview of Windows-based Applications
Classes Used in .NET Framework Forms
Visual Basic Language Concepts
Form Represents a normal window, modeless window, dialog box, Multiple Document Interface (MDI) client, or MDI par
ent window. Forms make up an application's user interface.
UserControl Provides an empty control that can be used to create other controls or create a custom control that is a composite
of other controls.
Control Classes
The following table lists and describes a sampling of the System.Windows.Forms namespace's control classes. You can use
these controls to create rich user interfaces.
Class Description
TextBox Data-entry control. Represents a Windows text-box control.
ListView Data-display control. Represents a Windows list-view control, which displays a collection of items that can be dis
played using one of four different views.
PropertyGrid Designer control. Provides a user interface for browsing the properties of an object.
Component Classes
In addition to controls, the System.Windows.Forms namespace provides other classes that do not derive from the Control
class but still provide visual features to a Windows-based application. The following table shows some of the available
component classes.
Class Description
ToolTip Data-display component. Represents a small rectangular pop-up window that displays a brief descri
ption of a control's purpose when the user rests the pointer on the control.
ErrorProvider Data-display component. Provides a user interface for indicating that a control on a form has an err
or associated with it.
ToolStripDropDownMenu Menu component. Provides basic functionality for the ContextMenuStrip control.
SaveFileDialog Provides the functionality to display a dialog box that enables the user to browse to and enter the name of a
file to open or save.
FontDialog Displays a dialog box to change elements of the font used by your application
PageSetupDialog Displays a dialog box that enables the user to control aspects of printing documents.
PrintDialog Displays a dialog box that enables the user to control aspects of printing documents.
MessageBox Displays a message box that can display and retrieve data from the user.
See Also
Reference
Windows Forms Overview
System.Windows.Forms
System.Drawing.Printing
Concepts
Windows Forms Application Concepts in Visual Basic
Windows Forms Application Basics
Overview of Windows-based Applications
Visual Basic Language Concepts
This page describes ReportViewer controls and Reporting Services. For more information about Crystal Reports, see
Overview of Crystal Reports.
Overview of Microsoft Reporting Technology in Visual Basic Applications
Choose from the following approaches to use a Microsoft reporting technology in your application:
Add one or more instances of a ReportViewer control to a Visual Basic Windows application.
Integrate SQL Server Reporting Services programmatically by making calls to the Report Server Web service.
Use the ReportViewer control and Microsoft SQL Server 2005 Reporting Services together, using the control as a report
viewer and a report server as a report processor. (Note that you must use the SQL Server 2005 version of Reporting
Services if you want to use a report server and the ReportViewer control together).
Using ReportViewer Controls
The easiest way to embed report functionality into a Visual Basic Windows application is to add the ReportViewer control to a
form in your application. The control adds report processing capabilities directly to your application and provides an integrated
report designer so that you can build reports using data from any ADO.NET data object. A full-featured API provides
programmatic access to the control and reports so that you can configure run-time functionality.
ReportViewer provides built-in report processing and viewing capability in a single, freely distributable data control. Choose
ReportViewer controls if you require the following report functionality:
Report processing in the client application. A processed report appears in a view area provided by the control.
Data binding to ADO.NET data tables. You can create reports that consume DataTable instances supplied to the control.
You can also bind directly to business objects.
Redistributable controls that you can include in your application.
Runtime functionality such as page navigation, printing, searching, and export formats. A ReportViewer toolbar provides
support for these operations.
To use the ReportViewer control, you can drag it from the Data section of the Visual Studio Toolbox onto a form in your Visual
Basic Windows application. To learn more about ReportViewer, see ReportViewer Controls (Visual Studio) and
Samples and Walkthroughs.
Creating Reports in Visual Studio for ReportViewer Controls
To build a report that runs in ReportViewer, add a Report template to your project. Visual Studio creates a client report
definition file (.rdlc), adds the file to your project, and opens an integrated report designer in the Visual Studio workspace.
The Visual Studio Report Designer integrates with the Data Sources window. When you drag a field from the Data Sources
window to the report, the Report Designer copies metadata about the data source into the report definition file. This metadata
is used by the ReportViewer control to automatically generate data-binding code.
The Visual Studio Report Designer does not include report preview functionality. To preview your report, run the application
and preview the report embedded in it.
To add basic report functionality to your application
1. Drag a ReportViewer control from the Data tab of the Toolbox onto your form.
2. On the Project menu, choose Add New Item. In the Add New Item dialog box, select the Report icon and click Add.
The Report Designer opens in the development environment, and a report (.rdlc) file is added to the project.
3. Drag report items from the Toolbox on the report layout and arrange them as you want.
4. Drag fields from the Data Sources window to the report items in the report layout.
Next Steps in Working with ReportViewer and the Report Designer
To See
Add and configure a ReportViewer control Adding and Configuring the ReportViewer Control
Create and preview a local report Creating Reports for Local Processing Mode
Add data sources for ReportViewer reports Creating Data Sources for a ReportViewer Report
Use Visual Basic expressions in ReportViewer reports Using Expressions in a ReportViewer Report
Distribute reports and the ReportViewer controls as part of your applicatio Deploying Reports and the ReportViewer Control
n
For more step-by-step instruction on how to create reports and configure controls for a variety of scenarios, see
Samples and Walkthroughs.
Using Reporting Services in Visual Basic Applications
Reporting Services is a server-based reporting technology that is included with SQL Server. Reporting Services includes
additional features that are not found in the ReportViewer controls. Choose Reporting Services if you require any of the
following features:
Scale-out deployment and server-side report processing that provides improved performance for complex or long-
running reports and for high-volume report activity.
Integrated data and report processing, with support for custom report controls and rich rendering output formats.
Scheduled report processing so that you can specify exactly when reports are run.
Subscriber-based report distribution through e-mail or to file share locations.
Ad hoc reporting so that business users can create reports as needed.
Data-driven subscriptions that route customized report output to a dynamic list of recipients.
Custom extensions for data processing, report delivery, custom authentication, and report rendering.
The report server is implemented as Web service. Your application code must include calls to the Web service to access reports
and other metadata. The Web service provides complete programmatic access to a report server instance.
Because Reporting Services is a Web-based reporting technology, the default viewer shows reports that are rendered in HTML
format. If you do not want to use HTML as the default report presentation format, you will have to write a custom report viewer
for your application.
To learn more about Reporting Services, see SQL Server Reporting Services in SQL Server 2005 Books Online and
SQL Server Reporting Services Tutorials.
Creating Reports in Visual Studio for Reporting Services
To build reports that run on a report server, you create report definition (.rdl) files in Visual Studio through the Business
Intelligence Development Studio, which is included with SQL Server 2005.
Note
You must have SQL Server 2005 installed in order to use SQL Server Reporting Services and the Business Intelligence Devel
opment Studio.
The Business Intelligence Development Studio adds project templates that are specific to SQL Server components. To create
reports, you can choose from the Report Server Project or Report Server Project Wizard templates. You can specify data
source connections and queries to a variety of data source types, including SQL Server, Oracle, Analysis Services, XML, and SQL
Server Integration Services. A Data tab, Layout tab, and Preview tab allow you to define data, create a report layout, and
preview the report all in the same workspace.
Report definitions that you build for the control or the report server can be reused in either technology. For more information,
see Converting RDL and RDLC Files.
To create a report that runs on a report server
1. On the File menu, choose New.
The New Project dialog box opens.
2. In the Project types pane, click Business Intelligence Projects.
3. In the Templates pane, select Report Server Project or Report Server Project Wizard.
Using ReportViewer Controls and SQL Server Reporting Services Together
The ReportViewer controls and SQL Server 2005 Reporting Services can be used together in the same application.
The ReportViewer control provides a viewer that is used to display reports in your application.
Reporting Services provides the reports and performs all processing on a remote server.
The ReportViewer control can be configured to show reports that are stored and processed on a remote Reporting Services
report server. This type of configuration is called remote processing mode. In remote processing mode, the control requests a
report that is stored on a remote report server. The report server performs all report processing, data processing, and report
rendering. A finished, rendered report is returned to the control and displayed in the view area.
Reports that run on a report server support additional export formats, have a different report parameterization
implementation, use the data source types that are supported by the report server, and are accessed through the role-based
authorization model on the report server.
To use remote processing mode, specify the URL and path to a server report when configuring the ReportViewer control. For
more information about control configuration and how server reports compare with client reports, see
Configuring ReportViewer for Remote Processing.
See Also
Reference
Microsoft.Reporting.WebForms
Microsoft.Reporting.WinForms
Other Resources
ReportViewer Web Server and Windows Forms Controls
Creating Reports for Local Processing Mode
Introducing Reporting Services Programming
Creating, Managing, and Delivering Reports Overview
Defining Report Data
Working with Data in Reporting Services
Visual Basic Language Concepts
The Visual Basic Application Model also provides the StartupNextInstance and UnhandledException events. The following
graphics show the mechanism for raising these events.
The application startup sequence is canceled if this function returns False. This can be useful if there are circumstances in
which the application should not run.
The OnInitialize method calls the following methods:
a. ShowSplashScreen. Determines if the application has a splash screen defined and if it does, displays the splash
screen on a separate thread.
The ShowSplashScreen method contains the code that displays the splash screen for at least the number of
milliseconds specified by the MinimumSplashScreenDisplayTime property. To use this functionality, you must add
the splash screen to your application using the Project Designer (which sets the
My.Application.MinimumSplashScreenDisplayTime property to two seconds), or set the
My.Application.MinimumSplashScreenDisplayTime property in a method that overrides the OnInitialize or
OnCreateSplashScreen method. For more information, see
My.Application.MinimumSplashScreenDisplayTime Property.
b. OnCreateSplashScreen. Allows a designer to emit code that initializes the splash screen.
By default, this method does nothing. If you select a splash screen for your application in the Visual Basic Project
Designer, the designer overrides the OnCreateSplashScreen method with a method that sets the SplashScreen
property to a new instance of the splash-screen form.
2. OnStartup. Provides an extensibility point for raising the Startup event. The application startup sequence stops if this
function returns False.
By default, this method raises the Startup event. If the event handler sets the Cancel property of the event argument to
True, the method returns False to cancel the application startup.
3. OnRun. Provides the starting point for when the main application is ready to start running, after the initialization is done.
By default, before it enters the Windows Forms message loop, this method calls the OnCreateMainForm (to create the
application's main form) and HideSplashScreen (to close the splash screen) methods:
a. OnCreateMainForm. Provides a way for a designer to emit code that initializes the main form.
By default, this method does nothing. However, when you select a main form for your application in the Visual
Basic Project Designer, the designer overrides the OnCreateMainForm method with a method that sets the
MainForm property to a new instance of the main form.
b. HideSplashScreen. If application has a splash screen defined and it is open, this method closes the splash screen.
By default, this method closes the splash screen.
4. OnStartupNextInstance. Provides a way to customize how a single-instance application behaves when another instance
of the application starts.
By default, this method raises the StartupNextInstance event.
5. OnShutdown. Provides an extensibility point for raising the Shutdown event. This method does not run if an unhandled
exception occurs in the main application.
By default, this method raises the Shutdown event.
6. OnUnhandledException. Executed if an unhandled exception occurs in any of the above listed methods.
By default, this method raises the UnhandledException event as long as a debugger is not attached and the application is
handling the UnhandledException event.
If the application is a single-instance application, and the application is already running, the subsequent instance of the
application calls the OnStartupNextInstance method on the original instance of the application, and then exits.
The WindowsFormsApplicationBase constructor calls the UseCompatibleTextRendering property to determine which text
rendering engine to use for the application's forms. By default, the UseCompatibleTextRendering property returns False,
indicating that the GDI text rendering engine be used, which is the default in Visual Basic 2005. You can override the
UseCompatibleTextRendering property to return True, which indicates that the GDI+ text rendering engine be used, which
is the default in Visual Basic .NET 2002 and Visual Basic .NET 2003.
Configuring the Application
As a part of the Visual Basic Application model, the WindowsFormsApplicationBase class provides protected properties that
configure the application. These properties should be set in the constructor of the implementing class.
In a default Windows Forms project, the Project Designer creates code to set the properties with the designer settings. The
properties are used only when the application is starting; setting them after the application starts has no effect.
Property Determines Setting with the Project Designer
IsSingleInstance Whether the application runs as a single-instanc How to: Specify Instancing Behavior for an Application
e or multiple-instance application.
EnableVisualStyles If the application will use XP visual styles. How to: Enable Visual Styles
SaveMySettingsOnExit If application automatically saves application's u Select the Save My.Settings on Shutdown check bo
ser-settings changes when the application exits. x in the Application pane in the Project Designer.
ShutdownStyle What causes the application to terminate, such a How to: Specify Shutdown Behavior for an Application
s when the main form closes or when all forms c
lose.
See Also
Reference
My.Application Object
My.Application.Startup Event
My.Application.StartupNextInstance Event
My.Application.UnhandledException Event
My.Application.Shutdown Event
My.Application.NetworkAvailabilityChanged Event
WindowsFormsApplicationBase
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Concepts
/define:_MYTYPE=\"WindowsForms\"
This table shows what the _MYTYPE conditional-compilation constant is set to for several project types.
Project type _MYTYPE value
Class Library "Windows"
Web "Web"
Empty "Empty"
Note
All conditional-compilation string comparisons are case-sensitive, regardless of how the Option Compare statement is set.
By default, undefined conditional-compilation constants resolve to FALSE. You can specify values for the undefined constants
when compiling your project to override the default behavior.
Note
When _MYTYPE is set to "Custom", the project contains the My namespace, but it contains no objects. However, setting _MY
TYPE to "Empty" prevents the compiler from adding the My namespace and its objects.
This table describes the effects of the predefined values of the _MY compilation constants.
Constant Meaning
_MYAPPLICA Enables My.Application, if the constant is "Console," Windows," or "WindowsForms":
TIONTYPE
The "Console" version derives from ConsoleApplicationBase. and has fewer members than the "Windows"
version.
The "Windows" version derives from ApplicationBase.and has fewer members than the "WindowsForms"
version.
The "WindowsForms" version of My.Application derives from WindowsFormsApplicationBase. If the TA
RGET constant is defined to be "winexe", then the class includes a Sub Main method.
See Also
Reference
/define (Visual Basic)
My.Application Object
My.Computer Object
My.Forms Object
My.Log Object
My.Request Object
My.Response Object
My.User Object
My.WebServices Object
Concepts
How My Depends on Project Type
Conditional Compilation Overview
Visual Basic Language Concepts
The most common variety of this procedure is Sub Main(). For more information, see Main Procedure in Visual Basic.
See Also
Concepts
Visual Basic Version of Hello, World
Main Procedure in Visual Basic
Visual Basic Naming Conventions
Visual Basic Limitations
Visual Basic Language Concepts
The single quotation mark (') means that the rest of the line is a comment and will be ignored by the compiler. You can make
an entire line a comment, or you can append a comment to the end of another statement, as follows:
VB
MsgBox("Hello, World!") ' Display message on computer screen.
The most common variety of this procedure is Sub Main(). Unless you are creating a Windows Forms application, you must
write the Main procedure for applications that run on their own. For more information, see Main Procedure in Visual Basic.
Input and Output
This example uses the standard Visual Basic run-time library, which is available through the Microsoft.VisualBasic namespace.
If you compile the program in the integrated development environment (IDE), you can use all the procedures and properties of
Microsoft.VisualBasic without having to import it. If you compile from the command line, you must use the
Imports Statement in your source code, or the /imports (Visual Basic) command-line compiler option, to make the
Microsoft.VisualBasic members available to your program.
The Main procedure calls the MsgBox Function (Visual Basic) to display a message box containing the string "Hello, World!":
VB
MsgBox("Hello, World!") ' Display message on computer screen.
If your source file does not include an Imports statement for the Microsoft.VisualBasic namespace, you can include the
/imports command-line compiler option in the vbc command:
vbc Hello.vb /imports:Microsoft.VisualBasic
3. If your program does not contain any compilation errors, the compiler creates a Hello.exe file.
4. To run the program, enter the following command:
Hello
You can optionally include the /main command-line compiler option in the vbc command to specify the namespace and
module supplying Main.
To compile and run the program from the IDE
1. Create a Visual Basic console application project.
2. Copy the code into the project.
3. Choose the appropriate Build command from the Build menu, or press F5 to build and run (corresponding to Start in
the Debug menu).
For more information on the Visual Basic compiler and its options, see Building from the Command Line (Visual Basic).
See Also
Reference
Structure of a Visual Basic Program
Imports Statement
/imports (Visual Basic)
MsgBox Function (Visual Basic)
/main
Microsoft.VisualBasic
Concepts
Main Procedure in Visual Basic
Other Resources
Building from the Command Line (Visual Basic)
Visual Basic Language Concepts
The simplest way is to declare a Sub procedure that does not take arguments or return a value.
Module mainModule
Sub Main()
MsgBox("The Main procedure is starting the application.")
' Insert call to appropriate starting place in your code.
MsgBox("The application is terminating.")
End Sub
End Module
Main can also return an Integer value, which the operating system uses as the exit code for your program. Other
programs can test this code by examining the Windows ERRORLEVEL value. To return an exit code, you must declare
Main as a Function procedure instead of a Sub procedure.
Module mainModule
Function Main() As Integer
MsgBox("The Main procedure is starting the application.")
Dim returnValue As Integer = 0
' Insert call to appropriate starting place in your code.
' On return, assign appropriate value to returnValue.
' 0 usually means successful completion.
MsgBox("The application is terminating with error level " _
& CStr(returnValue) & ".")
Return returnValue
End Function
End Module
Main can also take a String array as an argument. Each string in the array contains one of the command-line arguments
used to invoke your program. You can take different actions depending on their values.
Module mainModule
Function Main(ByVal cmdArgs() As String) As Integer
MsgBox("The Main procedure is starting the application.")
Dim returnValue As Integer = 0
' See if there are any arguments.
If cmdArgs.Length > 0 Then
For argNum As Integer = 0 To UBound(cmdArgs, 1)
' Insert code to examine cmdArgs(argNum) and take
' appropriate action based on its value.
Next argNum
End If
' Insert call to appropriate starting place in your code.
' On return, assign appropriate value to returnValue.
' 0 usually means successful completion.
MsgBox("The application is terminating with error level " _
& CStr(returnValue) & ".")
Return returnValue
End Function
End Module
You can declare Main to examine the command-line arguments but not return an exit code, as follows.
Module mainModule
Sub Main(ByVal cmdArgs() As String)
MsgBox("The Main procedure is starting the application.")
Dim returnValue As Integer = 0
' See if there are any arguments.
If cmdArgs.Length > 0 Then
For argNum As Integer = 0 To UBound(cmdArgs, 1)
' Insert code to examine cmdArgs(argNum) and take
' appropriate action based on its value.
Next argNum
End If
' Insert call to appropriate starting place in your code.
MsgBox("The application is terminating."
End Sub
End Module
See Also
Reference
Structure of a Visual Basic Program
/main
Shared (Visual Basic)
MsgBox Function (Visual Basic)
Sub Statement (Visual Basic)
Function Statement (Visual Basic)
Integer Data Type (Visual Basic)
String Data Type (Visual Basic)
UBound Function (Visual Basic)
Length
Concepts
Visual Basic Version of Hello, World
Visual Basic Language Concepts
If you do not do either of these, then Visual Basic assumes use of the intrinsic Loop keyword and produces an error, as in the
following example:
' The following statement causes a compiler error.
Loop.Visible = True
You can use square brackets when referring to forms and controls, and when declaring a variable or defining a procedure with
the same name as a restricted keyword. It can be easy to forget to qualify names or include square brackets, and thus introduce
errors into your code and make it harder to read. For this reason, we recommend that you not use restricted keywords as the
names of program elements. However, if a future version of Visual Basic defines a new keyword that conflicts with an existing
form or control name, then you can use this technique when updating your code to work with the new version.
Note
Your program also might include element names provided by other referenced assemblies. If these names conflict with restri
cted keywords, then placing square brackets around them causes Visual Basic to interpret them as your defined elements.
See Also
Concepts
Visual Basic Naming Conventions
Other Resources
Program Structure and Code Conventions
Keywords (Visual Basic)
Visual Basic Language Concepts
Do not use "My" or "my" as part of a variable name. This creates confusion with the My objects.
Layout Conventions
Good layout uses formatting to emphasize the structure of the code and makes code easier to read.
Use the pretty listing feature to format code with the the default settings (smart indenting, 4 character indents, save tabs
as spaces). For more information, see VB Specific, Basic, Text Editor, Options Dialog Box.
Use only one statement per line. Do not use ":".
Use only one declaration per line.
Indent continuation lines one tab stop.
Add at least one blank line between method and property definitions.
Commenting Conventions
Do not use comments at the end of a line of code. Put comments on a separate line.
Begin the comment text with an uppercase letter.
End the comment with a period.
Insert one space between the comment delimiter (') and the comment text.
Language Guidelines
String Data Type
Use & to concatenate strings:
Use the { } syntax when declaring and initializing arrays of basic data types:
Example:
Use Try...Catch
Always use a Try...Catch with object that implements a Dispose method.
Don’t use On Error Goto.
Use the Using Statement
If you are using a Try...Catch statement, and the only code in the Finally block is a call to Dispose, use Using instead.
IsNot Keyword
Use the IsNot keyword in preference to Not ... Is Nothing.
Default Instances of Forms
Use Form1.ShowDialog rather than My.Forms.Form1.ShowDialog.
New Keyword
Use short instantiation:
Use the parameterless constructor and then set the properties using With:
Event Handling
Use Handles rather than AddHandler:
When you define an event, use the short syntax and let the compiler define the delegate:
Text All clickable controls should have a keyboard access key (shortcut).
Forecolor Default
Backcolor Default
BackgroundImage Default
Security
Follow the guidelines in Secure Coding Guidelines.
See Also
Other Resources
Design Guidelines for Developing Class Libraries
Secure Coding Guidelines
Visual Basic Language Concepts
If you set the value of the FrenchVersion constant to True at compile time, the conditional code for the French version is
compiled. If you set the value of the GermanVersion constant to True, the compiler uses the German version. If neither is set to
True, the code in the last Else block runs.
Note
Autocompletion will not function when editing code and using conditional compilation directives if the code is not part of the
current branch.
See Also
Tasks
How to: Declare Conditional Compilation Constants
How to: Collapse and Hide Sections of Code
Reference
#Const Directive
#If...Then...#Else Directives
Other Resources
Building from the Command Line (Visual Basic)
Visual Basic Language Concepts
No space is required between the /d switch and the first constant. For more information, see /define (Visual Basic).
Command-line declarations override declarations entered in the Project Designer, but do not erase them. Arguments
set in Project Designer remain in effect for subsequent compilations.
When writing constants in the code itself, there are no strict rules as to their placement, since their scope is the entire
module in which they are declared.
To set constants in your code
Place the constants in the declaration block of the module in which they are used. This helps keep your code organized
and easier to read.
See Also
Tasks
How to: Collapse and Hide Sections of Code
Reference
Conditional Compilation Constants
/define (Visual Basic)
#If...Then...#Else Directives
#Const Directive
Concepts
Conditional Compilation Overview
Other Resources
Building from the Command Line (Visual Basic)
Visual Basic Language Concepts
The #Region block can be used multiple times in a code file; thus, users can define their own blocks of procedures and
classes that can, in turn, be collapsed. #Region blocks can also be nested within other #Region blocks.
Note
Hiding code does not prevent it from being compiled and does not affect #If...#End If statements.
See Also
Tasks
How to: Declare Conditional Compilation Constants
How to: Outline and Hide Code
Reference
#Region Directive
#If...Then...#Else Directives
Concepts
Conditional Compilation Overview
Visual Basic Language Concepts
Using this sequence makes your code easier to read, both online and when printed.
Note
The line-continuation character is necessarily the last thing on a line. You cannot follow it with anything else on the sa
me line.
Some limitations exist as to where the line-continuation character can be used, such as in the middle of an argument
name. You can break an argument list with the line-continuation character, but the individual names of the arguments
must remain intact.
Note
You cannot continue a comment by using a line-continuation character. Once a comment begins, the compiler does not
examine the characters for special meaning. For a multiple-line comment, repeat the comment symbol (') on each line.
While placing each statement on a separate line is the recommended method, Visual Basic also allows you to place multiple
statements on the same line.
To place multiple statements on the same line
Separate the statements with a colon (:), as in the following example.
VB
text1.Text = "Hello" : text1.BackColor = System.Drawing.Color.Red
See Also
Other Resources
Program Structure and Code Conventions
Statements in Visual Basic
Visual Basic Language Concepts
See Also
Concepts
Statements Overview
Other Resources
Statements in Visual Basic
Program Structure and Code Conventions
Visual Basic Language Concepts
Following execution of the preceding code, the value of d is 8.225 and the value of e is 3. The calculation for d uses the default
precedence of / over + and is equivalent to d = b + (c / a). The parentheses in the calculation for e override the default
precedence.
Separators
Separators do what their name suggests: they separate sections of code. In Visual Basic, the separator character is the colon (:).
Use separators when you want to place multiple statements on a single line instead of separate lines, saving space and
improving the readability of your code. The following example shows three statements separated by colons (:).
VB
a = 3.2 : b = 7.6 : c = 2
Concatenation
Use the & operator for concatenation, or linking strings together. Do not confuse it with the + operator, which adds together
numeric values. Using the + operator to concatenate can cause incorrect results when operating on numeric values. The
following example demonstrates this.
VB
var1 = "10.01"
var2 = 11
resultA = var1 + var2
resultB = var1 & var2
Following execution of the preceding code, the value of resultA is 21.01 and the value of resultB is "10.0111".
Member Access Operators
To access a member of a type, you use the dot (.) or exclamation point (!) operator between the type name and the member
name.
Dot (.) Operator
Use the . operator on a class, structure, interface, or enumeration as a member access operator. The member can be a field,
property, event, or method.The following example illustrates this.
VB
Dim nextForm As New System.Windows.Forms.Form
' Access Text member (property) of Form class (on nextForm object).
nextForm.Text = "This is the next form"
' Access Close member (method) on nextForm.
nextForm.Close()
The three output lines of MsgBox all display the value 32856. The first line uses the traditional access to property index, the
second makes use of the fact that index is the default property of class hasDefault, and the third uses dictionary access to the
class.
Note that the second operand of the ! operator must be a string not enclosed in double quotation marks (" "). In other words,
you cannot use a string literal or string variable. The following change to the last line of the MsgBox call generates an error
because "X" is an enclosed string literal.
"Dictionary access returns " & hD!"X")
Note
References to default collections must be explicit. In particular, you cannot use the ! operator on a late-bound variable.
Comments in Code
As you read the code examples, you often encounter the comment symbol ('). This symbol tells the Visual Basic compiler to
ignore the text following it, or the comment. Comments are brief explanatory notes added to code for the benefit of those
reading it.
It is good programming practice to begin all procedures with a brief comment describing the functional characteristics of the
procedure (what it does). This is for your own benefit and the benefit of anyone else who examines the code. You should
separate the implementation details (how the procedure does it) from comments that describe the functional characteristics.
When you include implementation details in the description, remember to update them when you update the function.
Comments can follow a statement on the same line, or occupy an entire line. Both are illustrated in the following code.
VB
' This is a comment beginning at the left edge of the screen.
text1.Text = "Hi!" ' This is an inline comment.
If your comment requires more than one line, use the comment symbol on each line, as the following example illustrates.
VB
' This comment is too long to fit on a single line, so we break
' it into two lines. Some comments might need three or more lines.
Commenting Guidelines
The following table provides general guidelines for what types of comments can precede a section of code. These are
suggestions; Visual Basic does not enforce rules for adding comments. Write what works best, both for you and for anyone
else who reads your code.
Comment type Comment description
Purpose Describes what the procedure does (not how it does it)
Assumptions Lists each external variable, control, open file, or other element accessed by the procedure
Effects Lists each affected external variable, control, or file, and the effect it has (only if it is not obvious)
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
A reference to the System namespace.
Note
You cannot continue a comment using the line-continuation sequence ( _). You must repeat the comment character (')
at the beginning of each line of a comment.
See Also
Tasks
How to: Break and Combine Statements in Code
Concepts
Comments in Code
Visual Basic Language Concepts
F field: Dim
E event: Event
! error string
The rest of the string provides information about the error. The Visual Basic compiler generates error informatio
n for links that cannot be resolved.
The second part of the String is the fully qualified name of the item, starting at the root of the namespace. The name of
the item, its enclosing type(s), and the namespace are separated by periods. If the name of the item itself contains
periods, they are replaced by the number sign (#). It is assumed that no item has a number sign directly in its name. For
example, the fully qualified name of the String constructor would be System.String.#ctor.
For properties and methods, if there are arguments to the method, the argument list enclosed in parentheses follows. If
there are no arguments, no parentheses are present. The arguments are separated by commas. The encoding of each
argument follows directly how it is encoded in a .NET Framework signature.
Example
The following code shows how the ID strings for a class and its members are generated.
VB
Namespace SampleNamesapce
''' <summary>Signature is
''' "T:SampleNamesapce.SampleClass"
''' </summary>
Public Class SampleClass
''' <summary>Signature is
''' "M:SampleNamesapce.SampleClass.#ctor"
''' </summary>
Public Sub New()
End Sub
''' <summary>Signature is
''' "M:SampleNamesapce.SampleClass.#ctor(System.Int32)"
''' </summary>
Public Sub New(ByVal i As Integer)
End Sub
''' <summary>Signature is
''' "F:SampleNamesapce.SampleClass.SampleField"
''' </summary>
Public SampleField As String
''' <summary>Signature is
''' "F:SampleNamesapce.SampleClass.SampleConstant"
''' </summary>
Public Const SampleConstant As Integer = 42
''' <summary>Signature is
''' "M:SampleNamesapce.SampleClass.SampleFunction"
''' </summary>
Public Function SampleFunction() As Integer
End Function
''' <summary>Signature is
''' "M:SampleNamesapce.SampleClass.
''' SampleFunction(System.Int16[],System.Int32[0:,0:])"
''' </summary>
Public Function SampleFunction( _
ByVal array1D() As Short, _
ByVal array2D(,) As Integer) _
As Integer
End Function
''' <summary>Signature is
''' "M:SampleNamesapce.SampleClass.
''' op_Addition(SampleNamesapce.SampleClass,
''' SampleNamesapce.SampleClass)"
''' </summary>
Public Shared Operator +( _
ByVal operand1 As SampleClass, _
ByVal operand2 As SampleClass) _
As SampleClass
Return Nothing
End Operator
''' <summary>Signature is
''' "P:SampleNamesapce.SampleClass.SampleProperty"
''' </summary>
Public Property SampleProperty() As Integer
Get
End Get
Set(ByVal value As Integer)
End Set
End Property
''' <summary>Signature is
''' "P:SampleNamesapce.SampleClass.Item(System.String)"
''' </summary>
Default Public ReadOnly Property Item( _
ByVal s As String) As Integer
Get
End Get
End Property
''' <summary>Signature is
''' "T:SampleNamesapce.SampleClass.NestedClass"
''' </summary>
Public Class NestedClass
End Class
''' <summary>Signature is
''' "E:SampleNamesapce.SampleClass.SampleEvent(System.Int32)"
''' </summary>
Public Event SampleEvent As SampleDelegate
''' <summary>Signature is
''' "T:SampleNamesapce.SampleClass.SampleDelegate"
''' </summary>
Public Delegate Sub SampleDelegate(ByVal i As Integer)
End Class
End Namespace
See Also
Tasks
How to: Create XML Documentation in Visual Basic
Reference
/doc
Visual Basic Language Reference
4. Add additional code that uses the type or member with the new XML documentation comments.
IntelliSense displays the text from the <summary> tag for the type or member.
5. Compile the code to generate an XML file containing the documentation comments. For more information, see /doc.
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
/doc
Concepts
Documenting Your Code with XML (Visual Basic)
Visual Basic Language Concepts
Assemblies
Assemblies form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions for a
.NET-based application. Assemblies take the form of an executable (.exe) file or dynamic link library (.dll) file, and are the
building blocks of the .NET Framework. They provide the common language runtime with the information it needs to be aware
of type implementations. You can think of an assembly as a collection of types and resources that form a logical unit of
functionality and are built to work together.
With Visual Basic, you use the contents of assemblies, and add references to them, in much the same way as you use type
libraries with previous versions of Visual Basic. However, what makes assemblies different from .exe or .dll files in earlier
versions of Windows is that they contain all the information you would find in a type library, plus information about everything
else necessary to use the application or component.
Assembly Manifest
Within every assembly is an assembly manifest. Similar to a table of contents, the assembly manifest contains the following:
The assembly's identity (its name and version).
A file table describing all the other files that make up the assembly, for example, any other assemblies you created that
your .exe or .dll file relies on, or even bitmap or Readme files.
An assembly reference list, which is a list of all external dependencies—.dlls or other files your application needs that may
have been created by someone else. Assembly references contain references to both global and private objects. Global
objects reside in the global assembly cache, an area available to other applications, somewhat like the System32
directory. The Microsoft.VisualBasic namespace is an example of an assembly in the global assembly cache. Private
objects must be in a directory at either the same level as or below the directory in which your application is installed.
Because assemblies contain information about content, versioning, and dependencies, the applications you create with Visual
Basic do not rely on registry values to function properly. Assemblies reduce DLL conflicts and make your applications more
reliable and easier to deploy. In many cases, you can install a .NET-based application simply by copying its files to the target
computer.
References
To use an assembly, you must add a reference to it, as described in How to: Add or Remove References in Visual Studio. Next,
you use the Imports statement to choose the namespace of the items you want to use, as described in
References and the Imports Statement. Once an assembly is referenced and imported, all the accessible classes, properties,
methods, and other members of its namespaces are available to your application as if their code were part of your source file.
A single assembly can contain multiple namespaces, and each namespace can contain a different grouping of items, including
other namespaces.
For information on creating assemblies, see How to: Create and Use Assemblies.
See Also
Tasks
How to: Create and Use Assemblies
How to: Add or Remove References in Visual Studio
How to: View Assembly Contents
Reference
Imports Statement
Microsoft.VisualBasic
Concepts
Namespaces in Visual Basic
References and the Imports Statement
Other Resources
Assemblies in the Common Language Runtime
Language Changes for Visual Basic 6.0 Users
Visual Basic Language Concepts
To create an assembly
Compile your application by clicking Build on the Build menu or by building it from the command line using the
command-line compiler. For details about building assemblies from the command line, see
Building from the Command Line (Visual Basic).
To add a reference to another assembly
Click the Add Reference command on the Project menu, and select the assembly you want to use. For details, see
How to: Add or Remove References in Visual Studio.
To use objects in another assembly
Specify the fully qualified name for the object, or use an alias that has been defined for the object using an Imports
statement. For details about fully qualified names, see Namespaces in Visual Basic. For details about adding references
and using the Imports statement, see References and the Imports Statement.
See Also
Tasks
How to: Add or Remove References in Visual Studio
How to: View Assembly Contents
Reference
Imports Statement
Concepts
Assemblies
Creating Assemblies
Namespaces in Visual Basic
References and the Imports Statement
Other Resources
Assemblies in the Common Language Runtime
Language Changes for Visual Basic 6.0 Users
Building from the Command Line (Visual Basic)
Visual Basic Language Concepts
Imports statements must always be the first lines immediately following any Option statements in a module. The following
code fragment shows how to import and assign an alias to the Microsoft.VisualBasic.ControlChars module:
VB
Imports CtrlChrs = Microsoft.VisualBasic.ControlChars
If an Imports statement does not include an alias name, elements defined within the imported namespace can be used in the
module without qualification. If the alias name is specified, it must be used as a qualifier for names contained within that
namespace.
See Also
Tasks
How to: Add or Remove References in Visual Studio
How to: Create and Use Assemblies
Reference
Imports Statement
ControlChars Module (Visual Basic)
Microsoft.VisualBasic
Concepts
Namespaces in Visual Basic
Assemblies
Other Resources
Language Changes for Visual Basic 6.0 Users
Visual Basic Language Concepts
The following illustration shows two namespace hierarchies, both containing an object named ListBox.
By default, every executable file you create with Visual Basic contains a namespace with the same name as your project. For
example, if you define an object within a project named ListBoxProject, the executable file ListBoxProject.exe contains a
namespace called ListBoxProject.
Multiple assemblies can use the same namespace. Visual Basic treats them as a single set of names. For example, you can
define classes for a namespace called SomeNameSpace in an assembly named Assemb1, and define additional classes for the
same namespace from an assembly named Assemb2.
Fully Qualified Names
Fully qualified names are object references that are prefixed with the name of the namespace in which the object is defined.
You can use objects defined in other projects if you create a reference to the class (by choosing Add Reference from the
Project menu) and then use the fully qualified name for the object in your code. The following code fragment shows how to
use the fully qualified name for an object from another project's namespace:
VB
Dim LBC As New ListBoxProject.Form1.ListBox
Fully qualified names prevent naming conflicts because they make it possible for the compiler to determine which object is
being used. However, the names themselves can get long and cumbersome. To get around this, you can use the Imports
statement to define an alias—an abbreviated name you can use in place of a fully qualified name. For example, the following
code example creates aliases for two fully qualified names, and uses these aliases to define two objects.
VB
Imports LBControl = System.Windows.Forms.ListBox
Imports MyListBox = ListBoxProject.Form1.ListBox
VB
Dim LBC As LBControl
Dim MyLB As MyListBox
If you use the Imports statement without an alias, you can use all the names in that namespace without qualification, provided
they are unique to the project. If your project contains Imports statements for namespaces that contain items with the same
name, you must fully qualify that name when you use it. Suppose, for example, your project contained the following two
Imports statements:
VB
' This namespace contains a class called Class1.
Imports MyProj1
' This namespace also contains a class called Class1.
Imports MyProj2
If you attempt to use Class1 without fully qualifying it, Visual Basic produces an error stating that the name Class1 is
ambiguous.
Namespace Level Statements
Within a namespace, you can define items such as modules, interfaces, classes, delegates, enumerations, structures, and other
namespaces. You cannot define items such as properties, procedures, variables and events at the namespace level. These items
must be declared within containers such as modules, structures, or classes.
Note
If you have defined a nested hierarchy of namespaces, code inside that hierarchy might be blocked from accessing classes in
side of other namespaces with the same name. For example, if you define a namespace named System within a namespace n
amed SpecialSpace, the members of the .NET Framework System namespace will not be accessible unless you fully-qualify
the members with the Global keyword. For more information, see Global.
See Also
Tasks
How to: Create and Use Assemblies
Reference
Global
Imports Statement
ListBox
System.Windows.Forms
Concepts
Assemblies
References and the Imports Statement
Other Resources
Language Changes for Visual Basic 6.0 Users
Visual Basic Language Concepts
HideModuleNameAttribute Class Allows module members to be accessed using only the qualification needed for the module.
VBFixedStringAttribute Class Specifies the size of a fixed-length string in a structure for use with file input and output func
tions. Specific to Visual Basic.
VBFixedArrayAttribute Class Specifies the size of a fixed array in a structure for use with file input and output functions. S
pecific to Visual Basic.
WebMethodAttribute Makes a method callable using the SOAP protocol. Used in XML Web services.
MarshalAsAttribute Determines how a parameter should be marshaled between the managed code ofVisual Basi
c and unmanaged code such as a Windows API. Used by the common language runtime.
DllImportAttribute Indicates that the attributed method is implemented as an export from an unmanaged DLL.
VBFixedArrayAttribute
Use VBFixedArrayAttribute to declare arrays that are fixed in size. Like Visual Basic strings, arrays are of variable length by
default. This attribute is useful when serializing or writing data to files.
See Also
Reference
ComClassAttribute Class
VBFixedArrayAttribute Class
VBFixedStringAttribute Class
System.Runtime.InteropServices
Concepts
Global Attributes in Visual Basic
Applying Attributes
Retrieving Information Stored in Attributes
Writing Custom Attributes
Other Resources
Extending Metadata Using Attributes
Visual Basic Language Concepts
Application of Attributes
You apply attributes by adding attribute blocks to program elements such as properties, methods, events, classes, and
assemblies. An attribute block consists of angle brackets ("< >") enclosing a list of comma-separated attribute declarations. An
attribute declaration consists of an optional attribute modifier such as Module or Assembly, an attribute name, a (possibly
overloaded) list of required positional parameters, and a list of optional named arguments. You must place attributes with
modifiers in an attributes section at the top of a source file. For example, the following code sets an assembly attribute that
defines a title for the assembly, and a module attribute that indicates that the module is compliant with the common language
specification (CLS):
VB
Imports System.Reflection
<Assembly: AssemblyTitleAttribute("Production assembly 4"), _
Module: CLSCompliant(True)>
Assembly attributes also can be applied by means of the AssemblyInfo.vb file, which is added to projects automatically by the
Visual Studio user interface. This file contains assembly-level attributes with either default or empty values.
When applied to program elements such as properties, attributes precede the element. For example, the following code applies
an attribute to a class definition:
VB
<CustomAttr(Update:=True)> Class Class1
By convention, all attribute names end with the word "Attribute" to distinguish them from other items in the .NET Framework.
However, you do not need to specify the attribute suffix when using attributes. For example, if you had an attribute named
CustomAttrAttribute, then specifying <CustomAttr(Update:=True)> is equivalent to specifying
<CustomAttrAttribute(Update:=True)>.
Attribute Arguments
Attributes use optional, required, positional, and named arguments in much the same way that objects use these types of
arguments. Positional arguments are arguments that are specified in the order they are declared for the constructor of an
attribute. For example, the following code calls the Sub New constructor of an attribute with two values:
VB
<CustomAttr(True, False)> Class Class1
Arguments passed to Sub New in attribute classes are often used to initialize the values of fields and properties.
You can use named arguments to directly set the value of properties and fields. You specify a named argument by appending
":=" to the name of the argument, followed by the value being specified. Unlike positional arguments, named arguments can
be specified in any order. For example, the following code sets the value True for the Update field, and False for the Keep field:
VB
<CustomAttr(Update:=True, Keep:=False)> Class Class1
Note
Attribute arguments have one important difference from arguments used with standard method calls. You must use position
al arguments for arguments that are used with the Sub New constructor of attribute classes. Named arguments can only be
used to set the values of fields and properties of attribute classes.
Required arguments are those that must always be specified. Optional arguments are those that can be skipped using a
comma as a placeholder (when using positional arguments), or simply omitted (when using named arguments).
Attribute arguments must be constant expressions.
Attribute Examples
The following procedures provide examples of attribute declarations.
To use the MarshalAs attribute to control how parameters are marshaled
1. Add an Imports statement for the System.Runtime.InteropServices namespace to the top of your source code:
VB
Imports System.Runtime.InteropServices
2. Prefix parameters with the MarshalAsAttribute attribute and specify the data type the target requires. For example, the
following code marshals two parameters as the data type long pointer to a string (LPStr) for a Windows API function:
VB
Declare Auto Sub CopyFile Lib "Kernel32.Lib" ( _
<MarshalAs(UnmanagedType.LPStr)> ByVal existingfile As String, _
<MarshalAs(UnmanagedType.LPStr)> ByVal newfile As String, _
ByVal failifexists As Boolean _
)
The common language runtime uses the MarshalAsAttribute attribute to determine how a parameter should be marshaled
between the managed code of Visual Basic and the unmanaged code in a Windows API call.
To expose a method to remote Web clients
1. From the File menu, click Project, select the ASP.NET Web Service template, and add an Imports statement for the
System.Web namespace:
VB
Imports System.Web.Services
2. Define a method and use the WebMethodAttribute attribute to make it callable from remote Web clients:
VB
<WebMethod()> Public Function HelloWorld() As String
HelloWorld = "Hello World..."
End Function
Making an XML Web service method Public is not sufficient to expose it to Web clients. You must explicitly apply the
WebMethodAttribute attribute to a method before it can be called by a remote Web client.
See Also
Tasks
How to: Define Your Own Attributes
Reference
Imports Statement
WebMethodAttribute
MarshalAsAttribute
System.Web
Concepts
Attributes Overview in Visual Basic
Common Uses for Attributes
Argument Passing by Position and by Name
Other Resources
Custom Attributes in Visual Basic
Visual Basic Language Concepts
You place global attributes in source code after any top-level directives, such as Option Explicit and Imports statements, but
before any type or namespace declarations. Global attributes can appear in multiple source files in a project, but they are
generally placed in the file AssemblyInfo.vb file created automatically with Visual Basic projects.
Assembly attributes are values that provide information about an assembly. They fall into the following categories:
Assembly identity attributes
Informational attributes
Assembly manifest attributes
Strong name attributes
Assembly Identity Attributes
Three attributes (with a strong name, if applicable) determine the identity of an assembly: name, version, and culture. These
attributes form the full name of the assembly and are required when referencing it in code. You can set an assembly's version
and culture using attributes. The name value, however, is set by the compiler, the Visual Studio IDE in the
Assembly Information Dialog Box, or the Assembly Linker (Al.exe) when the assembly is created, based on the file containing
the assembly manifest. The AssemblyFlagsAttribute attribute specifies whether multiple copies of the assembly can coexist.
The following table shows the identity attributes.
Attribute Purpose
AssemblyName Fully describes an assembly's identity
AssemblyFlagsAttribute Specifies whether an assembly supports side-by-side execution on the same computer, in the same
process, or in the same application domain
The following code applies the version and culture attributes to an assembly:
VB
'Set version number for assembly.
<Assembly: Reflection.AssemblyVersionAttribute("4.3.2.1")>
'Set culture as German.
<Assembly: Reflection.AssemblyCultureAttribute("de")>
Informational Attributes
You can use informational attributes to provide additional company or product information for an assembly. The following
table shows the informational attributes defined in the System.Reflection namespace.
Attribute Purpose
AssemblyProductAttribute Defines a custom attribute that specifies a product name for an assembly manifest
AssemblyTrademarkAttribute Defines a custom attribute that specifies a trademark for an assembly manifest
AssemblyInformationalVersionAttribute Defines a custom attribute that specifies an informational version for an assembly ma
nifest
AssemblyCompanyAttribute Defines a custom attribute that specifies a company name for an assembly manifest
AssemblyCopyrightAttribute Defines a custom attribute that specifies a copyright for an assembly manifest
AssemblyFileVersionAttribute Instructs the compiler to use a specific version number for the Win32 file version reso
urce
CLSCompliantAttribute Indicates whether the assembly is compliant with the Common Language Specificatio
n (CLS).
Assembly Manifest Attributes
You can use assembly manifest attributes to provide information in the assembly manifest, including title, description, default
alias, and configuration. The following table shows the assembly manifest attributes defined in the System.Reflection
namespace.
Attribute Purpose
AssemblyTitleAttribute Defines a custom attribute that specifies an assembly title for an assembly manifest
AssemblyDescriptionAttribute Defines a custom attribute that specifies an assembly description for an assembly manifest
AssemblyConfigurationAttribute Defines a custom attribute that specifies an assembly configuration (such as retail or debug) f
or an assembly manifest
AssemblyKeyFileAttribute Indicates the file that contains a key. The location of the KeyFile should be relative to the project o
utput directory, which is %Project Directory%\obj\<configuration>. For example, if your KeyFile i
s located in the project directory, you would specify the AssemblyKeyFile attribute as
[assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
AssemblyKeyNameAttribute Refers to a key that has been installed in the Crypto Service Provider (CSP) on your computer. Yo
u must specify a key in order for your file to be signed.
If the KeyFile and the KeyName values are both specified, the following processing occurs:
If the KeyName can be found in the CSP, that key is used.
If the KeyName does not exist and the KeyFile does exist, the key in the KeyFile is installed into the CSP and used.
For more information, see Assembly Security Considerations.
Signing Assemblies
You can sign an assembly in two different but complementary ways: with a strong name or with signing. You can sign using
the Visual Studio IDE Signing Page, Project Designer or by using the File Signing Tool (Signcode.exe). Signing an assembly with
a strong name adds a public key encryption to the file containing the assembly manifest. Strong-name signing helps to verify
name uniqueness, prevent name spoofing, and provide callers with some identity when a reference is resolved. For more
information, see Managing Assembly and Manifest Signing and How to: Sign an Assembly with a Strong Name.
To sign an assembly with a strong name
1. Use the Strong Name Tool (Sn.exe) to generate a key file containing a key pair.
2. Add strong name attributes to the AssemblyInfo.vb file created automatically with Visual Basic projects. You can edit this
file by double-clicking its name in the Solution Explorer.
The following example uses delay signing to create a strong-named assembly with a public key file called myKey.snk.
VB
<Assembly: Reflection.AssemblyKeyFile("myKey.snk")>
<Assembly: Reflection.AssemblyDelaySign(True)>
Note
Assembly-level attributes are ignored if you are not creating an assembly, such as when compiling from the command
line using the /target:module option.
See Also
Tasks
How to: Define Your Own Attributes
How to: Sign an Assembly with a Strong Name
Reference
Strong Name Tool (Sn.exe)
File Signing Tool (Signcode.exe)
Signing Page, Project Designer
Assembly Information Dialog Box
Concepts
Application of Attributes
Assembly Security Considerations
Other Resources
Custom Attributes in Visual Basic
Managing Application Properties
Managing Assembly and Manifest Signing
Visual Basic Language Concepts
You can use the Or operator to combine multiple items from the AttributeTargets enumeration, as in the following code:
VB
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method)> _
Class TestAttribute2
Inherits Attribute
End Class
In This Section
How to: Define Your Own Attributes
Explains how to create your own attributes using attribute classes.
How to: Retrieve Custom Attributes
Demonstrates how to retrieve custom attributes using GetCustomAttribute or GetCustomAttributes.
Examples of Custom Attribute Usage
Provides example code that defines a custom attribute that can be applied only to classes, and shows how to use the new
attribute.
Related Sections
Visual Basic and the .NET Framework
Describes the role of Visual Basic in the .NET Framework.
Object-Oriented Programming in Visual Basic
Provides information about object-oriented programming and how it is used.
Metadata and Self-Describing Components
Provides detailed information about the kinds of metadata used in Visual Studio, including attributes.
Visual Basic Language Concepts
End Sub
3. Inside the procedure, declare a variable of type Attribute, and another variable of the same type as the attribute you
wish to retrieve:
VB
Dim Attr As Attribute
Dim CustAttr As CustomAttribute
4. Use the GetType operator to pass the type of the class and attribute to a call to the GetCustomAttribute method, and
then assign the returned value to the variable declared as Attribute:
VB
Attr = GetCustomAttribute(Me.GetType, _
GetType(CustomAttribute), False)
5. Use the CType function to convert the attribute's data type from generic attribute to the specific attribute of the type you
retrieved. Then assign the result to the variable declared as the custom attribute type:
VB
CustAttr = CType(Attr, CustomAttribute)
6. Check to see if the attribute was retrieved, and if it was, use the fields, properties, and methods of the attribute:
VB
If CustAttr Is Nothing Then
MsgBox("The attribute was not found.")
Else
'Get the label and value from the custom attribute.
MsgBox("The attribute label is: " & CustAttr.Label)
MsgBox("The attribute value is: " & CustAttr.Value)
End If
In the above example, the RetrieveAttribute procedure calls the GetCustomAttribute method of the
System.Attribute class to get the custom attribute applied to the class ThisClass. GetCustomAttribute is a shared
method, so you do not need to create an instance of System.Attribute first. The CType function converts the returned
attribute from type System.Attribute to the custom attribute type CustomAttribute.
See Also
Tasks
How to: Define Your Own Attributes
Reference
GetType Operator
CType Function
IsNothing Function
GetAttr Function
GetCustomAttribute
GetCustomAttributes
AttributeUsageAttribute
Concepts
Application of Attributes
Retrieving Information Stored in Attributes
Visual Basic Language Concepts
'The Sub New constructor is the only way to set the properties.
Public Sub New(ByVal _Label As String, ByVal _Value As Integer)
m_LlabelValue = _Label
m_VValueValue = _Value
End Sub
Only the constructor for the attribute class can set the properties defined in this attribute. The following code shows how you
could use the attribute:
VB
' Apply the custom attribute to this class.
<Custom("Some metadata", 66)> Class ThisClass
' Add class members here.
End Class
See Also
Tasks
How to: Define Your Own Attributes
How to: Retrieve Custom Attributes
Reference
AttributeUsageAttribute
Concepts
Application of Attributes
Retrieving Information Stored in Attributes
Visual Basic Language Concepts
See Also
Concepts
Attributes Overview in Visual Basic
Application of Attributes
Other Resources
Attributes in Visual Basic
Visual Basic Language Concepts
The following example shows some invalid element names. The first contains only an underscore, the second begins with a
decimal digit, and the third contains an invalid character ($).
' Three INVALID element names
_
12ABC
xyz$wv
Caution
Element names starting with an underscore (_) are not part of the Common Language Specification (CLS), so CLS-compliant
code cannot use a component that defines such names. However, an underscore in any other position in an element name is
CLS-compliant.
See Also
Concepts
Declared Element Names
Lifetime in Visual Basic
Scope in Visual Basic
Access Levels in Visual Basic
Data Types in Visual Basic
Variable Declaration in Visual Basic
Other Resources
Declared Elements in Visual Basic
References to Declared Elements
Visual Basic Language Concepts
In a class or structure, Shared (procedure i The first time the procedure is called either on a spec When your application stops
s not an instance member) ific instance or on the class or structure name itself running
In an instance of a class or structure, not S The first time the procedure is called on the specific i When the instance is release
hared (procedure is an instance member) nstance d for garbage collection (GC)
See Also
Tasks
How to: Lengthen a Variable's Lifetime
Troubleshooting Data Types
Reference
Shared (Visual Basic)
Nothing (Visual Basic)
Concepts
Declared Element Names
Scope in Visual Basic
Access Levels in Visual Basic
Variables in Visual Basic
Variable Declaration in Visual Basic
Other Resources
References to Declared Elements
Visual Basic Language Concepts
In the preceding example, the variable applesSold continues to exist after the procedure runningTotal returns to the calling
code. The next time runningTotal is called, applesSold retains its previously calculated value.
If applesSold had been declared without using Static, the previous accumulated values would not be preserved across calls to
runningTotal. The next time runningTotal was called, applesSold would have been recreated and initialized to 0, and
runningTotal would have simply returned the same value with which it was called.
Procedure scope Available to all code within the procedure in which it is declared
Module scope Available to all code within the module, class, or structure in which it is declared
These levels of scope progress from the narrowest (block) to the widest (namespace), where narrowest scope means the
smallest set of code that can refer to the element without qualification. For more information, see "Levels of Scope" on this
page.
Specifying Scope and Defining Variables
You specify the scope of an element when you declare it. The scope can depend on the following factors:
The region (block, procedure, module, class, or structure) in which you declare the element
The namespace containing the element's declaration
The access level you declare for the element
Use care when you define variables with the same name but different scope, because doing so can lead to unexpected results.
For more information, see Resolving a Reference When Multiple Variables Have the Same Name.
Levels of Scope
A programming element is available throughout the region in which you declare it. All code in the same region can refer to the
element without qualifying its name.
Block Scope
A block is a set of statements enclosed within initiating and terminating declaration statements, such as the following:
Do and Loop
For [Each] and Next
If and End If
Select and End Select
SyncLock and End SyncLock
Try and End Try
While and End While
With and End With
If you declare a variable within a block, you can use it only within that block. In the following example, the scope of the integer
variable cube is the block between If and End If, and you can no longer refer to cube when execution passes out of the block.
Procedure Scope
An element declared within a procedure is not available outside that procedure. Only the procedure that contains the
declaration can use it. Variables at this level are also known as local variables. You declare them with the
Dim Statement (Visual Basic), with or without the Static (Visual Basic) keyword.
Procedure and block scope are closely related. If you declare a variable inside a procedure but outside any block within that
procedure, you can think of the variable as having block scope, where the block is the entire procedure.
Note
All local elements, even if they are Static variables, are private to the procedure in which they appear. You cannot declare an
y element using the Public (Visual Basic) keyword within a procedure.
Module Scope
For convenience, the single term module level applies equally to modules, classes, and structures. You can declare elements at
this level by placing the declaration statement outside of any procedure or block but within the module, class, or structure.
When you make a declaration at the module level, the access level you choose determines the scope. The namespace that
contains the module, class, or structure also affects the scope.
Elements for which you declare Private (Visual Basic) access level are available to every procedure in that module, but not to
any code in a different module. The Dim statement at module level defaults to Private if you do not use any access level
keywords. However, you can make the scope and access level more obvious by using the Private keyword in the Dim
statement.
In the following example, all procedures defined in the module can refer to the string variable strMsg. When the second
procedure is called, it displays the contents of the string variable strMsg in a dialog box.
' Put the following declaration at module level (not in any procedure).
Private strMsg As String
' Put the following Sub procedure in the same module.
Sub initializePrivateVariable()
strMsg = "This variable cannot be used outside this module."
End Sub
' Put the following Sub procedure in the same module.
Sub usePrivateVariable()
MsgBox(strMsg)
End Sub
Namespace Scope
If you declare an element at module level using the Friend (Visual Basic) or Public (Visual Basic) keyword, it becomes available
to all procedures throughout the namespace in which the element is declared. With the following alteration to the preceding
example, the string variable strMsg can be referred to by code anywhere in the namespace of its declaration.
' Include this declaration at module level (not inside any procedure).
Public strMsg As String
Namespace scope includes nested namespaces. An element available from within a namespace is also available from within
any namespace nested inside that namespace.
If your project does not contain any Namespace Statements, everything in the project is in the same namespace. In this case,
namespace scope can be thought of as project scope. Public elements in a module, class, or structure are also available to any
project that references their project.
Choice of Scope
When you declare a variable, you should keep in mind the following points when choosing its scope.
Advantages of Local Variables
Local variables are a good choice for any kind of temporary calculation, for the following reasons:
Name Conflict Avoidance. Local variable names are not susceptible to conflict. For example, you can create several
different procedures containing a variable called intTemp. As long as each intTemp is declared as a local variable, each
procedure recognizes only its own version of intTemp. Any one procedure can alter the value in its local intTemp without
affecting intTemp variables in other procedures.
Memory Consumption. Local variables consume memory only while their procedure is running. Their memory is
released when the procedure returns to the calling code. By contrast, Shared (Visual Basic) and Static (Visual Basic)
variables consume memory resources until your application stops running, so use them only when necessary. Instance
variables consume memory while their instance continues to exist, which makes them less efficient than local variables,
but potentially more efficient than Shared or Static variables.
Minimizing Scope
In general, when declaring any variable or constant, it is good programming practice to make the scope as narrow as possible
(block scope is the narrowest). This helps conserve memory and minimizes the chances of your code erroneously referring to
the wrong variable. Similarly, you should declare a variable to be Static (Visual Basic) only when it is necessary to preserve its
value between procedure calls.
See Also
Tasks
How to: Control the Scope of a Variable
Concepts
Declared Element Characteristics
Lifetime in Visual Basic
Access Levels in Visual Basic
Resolving a Reference When Multiple Variables Have the Same Name
Variable Declaration in Visual Basic
Visual Basic Language Concepts
Example
The following example declares a variable at module level and limits its visibility to code within the module.
Module demonstrateScope
Private strMsg As String
Sub initializePrivateVariable()
strMsg = "This variable cannot be used outside this module."
End Sub
Sub usePrivateVariable()
MsgBox(strMsg)
End Sub
End Module
In the preceding example, all the procedures defined in module demonstrateScope can refer to the String variable strMsg.
When the usePrivateVariable procedure is called, it displays the contents of the string variable strMsg in a dialog box.
With the following alteration to the preceding example, the string variable strMsg can be referred to by code anywhere in the
namespace of its declaration.
Type Promotion
When you declare a programming element in a module, Visual Basic promotes its scope to the namespace containing the
module. This is known as type promotion.
The following example shows a skeleton definition of a module and two members of that module.
Namespace projNamespace
Module projModule
Public Enum basicEnum As Integer
one = 1
two = 2
End Enum
Public Class innerClass
Public Sub numberSub(ByVal firstArg As Integer)
End Sub
End Class
End Module
End Namespace
Within projModule, programming elements declared at module level are promoted to projNamespace. In the preceding
example, basicEnum and innerClass are promoted, but numberSub is not, because it is not declared at module level.
Effect of Type Promotion
The effect of type promotion is that a qualification string does not need to include the module name. The following example
makes two calls to the procedure in the preceding example.
Sub usePromotion()
projNamespace.projModule.innerClass.numberSub(projNamespace.projModule.basicEnum.one)
projNamespace.innerClass.numberSub(projNamespace.basicEnum.two)
End Sub
In the preceding example, the first call uses complete qualification strings. However, this is not necessary because of type
promotion. The second call also accesses the module's members without including projModule in the qualification strings.
Defeat of Type Promotion
If the namespace already has a member with the same name as a module member, type promotion is defeated for that module
member. The following example shows a skeleton definition of an enumeration and a module within the same namespace.
Namespace thisNamespace
Public Enum abc
first = 1
second
End Enum
Module thisModule
Public Class abc
Public Sub abcSub()
End Sub
End Class
Public Class xyz
Public Sub xyzSub()
End Sub
End Class
End Module
End Namespace
In the preceding example, Visual Basic cannot promote class abc to thisNameSpace because there is already an enumeration
with the same name at namespace level. To access abcSub, you must use the full qualification string
thisNamespace.thisModule.abc.abcSub. However, class xyz is still promoted, and you can access xyzSub with the shorter
qualification string thisNamespace.xyz.xyzSub.
Defeat of Type Promotion for Partial Types
If a class or structure inside a module uses the Partial (Visual Basic) keyword, type promotion is automatically defeated for that
class or structure, whether or not the namespace has a member with the same name. Other elements in the module are still
eligible for type promotion.
Consequences. Defeat of type promotion of a partial definition can cause unexpected results and even compiler errors. The
following example shows skeleton partial definitions of a class, one of which is inside a module.
Namespace sampleNamespace
Public Partial Class sampleClass
Public Sub sub1()
End Sub
End Class
Module sampleModule
Public Partial Class sampleClass
Public Sub sub2()
End Sub
End Class
End Module
End Namespace
In the preceding example, the developer might expect the compiler to merge the two partial definitions of sampleClass.
However, the compiler does not consider promotion for the partial definition inside sampleModule. As a result, it attempts to
compile two separate and distinct classes, both named sampleClass but with different qualification paths.
The compiler merges partial definitions only when their fully qualified paths are identical.
Recommendations
The following recommendations represent good programming practice.
Unique Names. When you have full control over the naming of programming elements, it is always a good idea to use
unique names everywhere. Identical names require extra qualification and can make your code harder to read. They can
also lead to subtle errors and unexpected results.
Full Qualification. When you are working with modules and other elements in the same namespace, the safest
approach is to always use full qualification for all programming elements. If type promotion is defeated for a module
member and you do not fully qualify that member, you could inadvertently access a different programming element.
See Also
Tasks
How to: Control the Scope of a Variable
Reference
Module Statement
Namespace Statement
Partial (Visual Basic)
Concepts
Scope in Visual Basic
Resolving a Reference When Multiple Variables Have the Same Name
Visual Basic Language Concepts
You can use Public only at module, interface, or namespace level. This means you can declare a public element at the level of a
source file or namespace, or inside an interface, module, class, or structure, but not within a procedure.
Protected
The Protected (Visual Basic) keyword in the declaration statement specifies that the elements are accessible only from within
the same class, or from a class derived from this class. The following code shows a sample Protected declaration.
You can use Protected only at class level, and only when declaring a member of a class. This means you can declare a
protected element in a class, but not at the level of a source file or namespace, or inside an interface, module, structure, or
procedure.
Friend
The Friend (Visual Basic) keyword in the declaration statement specifies that the elements are accessible from within the same
assembly, but not from outside the assembly. The following code shows a sample Friend declaration.
You can use Friend only at module, interface, or namespace level. This means you can declare a friend element at the level of a
source file or namespace, or inside an interface, module, class, or structure, but not within a procedure.
Protected Friend
The Protected and Friend keywords together in the declaration statement specify that the elements are accessible either from
derived classes or from within the same assembly, or both. The following code shows a sample Protected Friend declaration.
You can use Protected Friend only at class level, and only when declaring a member of a class. This means you can declare a
protected friend element in a class, but not at the level of a source file or namespace, or inside an interface, module, structure,
or procedure.
Private
The Private (Visual Basic) keyword in the declaration statement specifies that the elements are accessible only from within the
same module, class, or structure. The following code shows a sample Private declaration.
You can use Private only at module level. This means you can declare a private element inside a module, class, or structure,
but not at the level of a source file or namespace, inside an interface, or within a procedure.
At the module level, the Dim statement without any access level keywords is equivalent to a Private declaration. However, you
might want to use the Private keyword to make your code easier to read and interpret.
Access Modifiers
The keywords that specify access level are called access modifiers. The following table compares the access modifiers.
Access Access level granted Elements you can de Declaration context withi
modifi clare with this access n which you can use this
er level modifier
Public Unrestricted: Interfaces Source file
Any code that can see a public element can access it Modules Namespace
Classes Interface
Structures Module
Structure members Class
Procedures Structure
Properties
Member variables
Constants
Enumerations
Events
External declarations
Delegates
See Also
Tasks
How to: Control the Availability of a Variable
Reference
Dim Statement (Visual Basic)
Static (Visual Basic)
Concepts
Declared Element Names
Declared Element Characteristics
Lifetime in Visual Basic
Scope in Visual Basic
Variables in Visual Basic
Variable Declaration in Visual Basic
Other Resources
References to Declared Elements
Visual Basic Language Concepts
Security
The more restrictive the access level of a variable, the smaller the chances that malicious code can make improper use of it.
See Also
Reference
Dim Statement (Visual Basic)
Public (Visual Basic)
Protected (Visual Basic)
Friend (Visual Basic)
Private (Visual Basic)
Concepts
Access Levels in Visual Basic
Visual Basic Language Concepts
' Assume these two modules are both in the same assembly.
Module container
Public totalCount As Integer = 1
Public Sub showCount()
Dim totalCount As Integer = 6000
' The following statement displays the local totalCount (6000).
MsgBox("Unqualified totalCount is " & CStr(totalCount))
' The following statement displays the module's totalCount (1).
MsgBox("container.totalCount is " & CStr(container.totalCount))
End Sub
End Module
Module callingModule
Public Sub displayCount()
container.showCount()
' The following statement displays the containing module's totalCount (1).
MsgBox("container.totalCount is " & CStr(container.totalCount))
End Sub
End Module
The preceding example declares two variables, each named totalCount, at different levels of scope in module container.
When the procedure showCount displays totalCount without qualification, the Visual Basic compiler resolves the reference to
the declaration with the narrowest scope, namely the local declaration inside showCount. When it qualifies totalCount with the
containing module container, the compiler resolves the reference to the declaration with the broader scope.
Members of Other Containing Elements
When you use a nonshared member of another class or structure, you must first qualify the member name with a variable or
expression that points to an instance of the class or structure. In the following example, demoClass is an instance of a class
named class1.
You cannot use the class name itself to qualify a member that is not Shared (Visual Basic). You must first create an instance in
an object variable (in this case demoClass) and then reference it by the variable name.
If a class or structure has a Shared member, you can qualify that member either with the class or structure name or with a
variable or expression that points to an instance.
A module does not have any separate instances, and all its members are Shared by default. Therefore, you qualify a module
member with the module name.
Qualified Reference Example
The following example shows qualified references to module member procedures.
' Assume these three modules are all in the same assembly.
Module module1
Public Sub perform()
MsgBox("module1.perform() now returning")
End Sub
End Module
Module module2
Public Sub perform()
MsgBox("module2.perform() now returning")
End Sub
Public Sub doSomething()
' The following statement calls perform in module2, the active module.
perform()
' The following statement calls perform in module1.
module1.perform()
End Sub
End Module
Module module3
Public Sub callPerform()
' The following statement calls perform in module1.
module1.perform()
' The following statement makes an unresolvable name reference
' and therefore generates a COMPILER ERROR.
perform() ' INVALID statement
End Sub
End Module
The preceding example declares two Sub procedures, both named perform, in different modules in a project. Each one can be
specified without qualification within its own module but must be qualified if referenced from anywhere else. Because the final
reference in module3 does not qualify perform, the compiler is unable to resolve that reference.
References to Projects
To use Public (Visual Basic) elements defined in another project, you must first set a reference to that project's assembly or
type library. You can set a reference by choosing Add Reference from the Project menu, or with the /reference (Visual Basic)
command-line compiler option.
For example, you can use the XML object model of the .NET Framework. If you set a reference to the System.Xml namespace,
you can declare and use any of its classes, such as XmlDocument. The following example uses XmlDocument.
In addition, the Imports statement can define an import alias for each imported namespace. This can make your source code
shorter and easier to read. The following example rewrites the preceding example to use xD as an alias for the System.Xml
namespace.
The Imports statement does not make elements from other projects available to your application. That is, it does not take the
place of setting a reference. Importing a namespace simply removes the need to qualify the names defined in that namespace.
You can also use the Imports statement to import modules, classes, structures, and enumerations. You can then use the
members of such imported elements without qualification. However, you must always qualify nonshared members of classes
and structures with a variable or expression that evaluates to an instance of the class or structure.
Classes with the Same Name
When you create a new instance of an object, you might have to qualify the class with the namespace or type library to which it
belongs. For example, the System.Windows.Forms and System.Web.UI.WebControls namespaces both contain a Label class
(System.Windows.Forms.Label and System.Web.UI.WebControls.Label). If your application uses both, or if it defines its own
Label class, you must distinguish the different Label objects. Include the namespace or import alias in the variable declaration.
The following example uses the import alias.
Naming Guidelines
When you define two or more programming elements with the same name, a name ambiguity can result when the compiler
attempts to resolve a reference to that name. If more than one definition is in scope, or if no definition is in scope, the reference
is unresolvable. For an example, see "Qualified Reference Example" on this Help page.
You can avoid name ambiguity by giving all your elements unique names. Then you can make reference to any element
without needing to qualify its name with a namespace, module, or class. You also reduce the chances of accidentally referring
to the wrong element.
See Also
Tasks
How to: Modify Project Properties and Configuration Settings
How to: Qualify a Declared Element Name
How to: Distinguish Between Two Elements with the Same Name
Reference
Imports Statement
New (Visual Basic)
Public (Visual Basic)
Concepts
Variables in Visual Basic
Other Resources
References to Declared Elements
Visual Basic Language Concepts
2. Determine a qualification path based on the target element's location. Start with the highest-level namespace, proceed to
the lowest-level namespace, and end with the module, class, or structure containing the target element. Each element in
the path must contain the element that follows it.
outerSpace → innerSpace → holdsTotals → totals
3. Prepare the qualification string for the target element. Place a period (.) after every element in the path. Your application
must have access to every element in your qualification string.
outerSpace.innerSpace.holdsTotals.totals.
4. Write the expression or assignment statement referring to the target element in the normal way.
grandTotal = 9000
5. Precede the target element name with the qualification string. The name should immediately follow the period (.) that
follows the module, class, or structure that contains the element.
Namespace space1
Public Class innerClass
' String showMe is declared Shared to facilitate reference.
Public Shared showMe As String = "Shared string 1"
End Class
End Namespace
Namespace space2
Public Class innerClass
' String showMe is declared Shared to facilitate reference.
Public Shared showMe As String = "Shared string 2"
End Class
End Namespace
Public Module callShowMe
Public Sub showStrings()
MsgBox("From space1: " & space1.innerClass.showMe _
& vbCrLf & "From space2: " & space2.innerClass.showMe)
End Sub
End Module
The preceding example declares two variables, each named showMe, and each inside a class named innerClass. Because both
containing elements have the same name, the calling code must not only qualify the variable showMe with its container
innerClass, but it must also qualify innerClass with its container space1 or space2. The Visual Basic compiler can resolve each
reference because each qualification string provides an unambiguous path to a unique declaration.
Robust Programming
The fewer variables with the same name you have declared, the fewer opportunities you have for accidentally referring to one
in place of another. You can also minimize problems of reference matching.
Security
The fewer variables with the same name you have declared, the smaller the chances that malicious code can make improper
use of one of them.
See Also
Tasks
How to: Qualify a Declared Element Name
How to: Hide a Variable with the Same Name as Your Variable
How to: Hide an Inherited Variable
How to: Access a Variable Hidden by a Derived Class
Concepts
Declared Element Characteristics
Resolving a Reference When Multiple Variables Have the Same Name
Declaration Statements in Visual Basic
Other Resources
References to Declared Elements
Visual Basic Language Concepts
The following illustration shows two variables, both named temp. The local variable temp shadows the member variable temp
when accessed from within its own procedure p. However, the MyClass keyword bypasses the shadowing and accesses the
member variable.
Shadowing through scope
For an example of shadowing through scope, see How to: Hide a Variable with the Same Name as Your Variable.
Shadowing Through Inheritance
If a derived class redefines a programming element inherited from a base class, the redefining element shadows the original
element. You can shadow any type of declared element, or set of overloaded elements, with any other type. For example, an
Integer variable can shadow a Function procedure. If you shadow a procedure with another procedure, you can use a
different parameter list and a different return type.
The following illustration shows a base class b and a derived class d that inherits from b. The base class defines a procedure
named proc, and the derived class shadows it with another procedure of the same name. The first Call statement accesses the
shadowing proc in the derived class. However, the MyBase keyword bypasses the shadowing and accesses the shadowed
procedure in the base class.
Shadowing through inheritance
For an example of shadowing through inheritance, see How to: Hide a Variable with the Same Name as Your Variable and
How to: Hide an Inherited Variable.
Shadowing and Access Level
The shadowing element is not always accessible from the code using the derived class. For example, it might be declared
Private. In such a case, shadowing is defeated and the compiler resolves any reference to the same element it would have if
there had been no shadowing. This element is the accessible element the fewest derivational steps backward from the
shadowing class. If the shadowed element is a procedure, the resolution is to the closest accessible version with the same
name, parameter list, and return type.
The following example shows an inheritance hierarchy of three classes. Each class defines a Sub procedure display, and each
derived class shadows the display procedure in its base class.
In the preceding example, the derived class secondClass shadows display with a Private procedure. When module
callDisplay calls display in secondClass, the calling code is outside secondClass and therefore cannot access the private
display procedure. Shadowing is defeated, and the compiler resolves the reference to the base class display procedure.
However, the further derived class thirdClass declares display as Public, so the code in callDisplay can access it.
Shadowing and Overriding
Do not confuse shadowing with overriding. Both are used when a derived class inherits from a base class, and both redefine
one declared element with another. But there are significant differences between the two. For a comparison, see
Differences Between Shadowing and Overriding.
Shadowing and Overloading
If you shadow the same base class element with more than one element in your derived class, the shadowing elements
become overloaded versions of that element. For more information, see Procedure Overloading.
Accessing a Shadowed Element
When you access an element from a derived class, you normally do so through the current instance of that derived class, by
qualifying the element name with the Me keyword. If your derived class shadows the element in the base class, you can access
the base class element by qualifying it with the MyBase keyword.
For an example of accessing a shadowed element, see How to: Access a Variable Hidden by a Derived Class.
Declaration of the Object Variable
How you create the object variable can also affect whether the derived class accesses a shadowing element or the shadowed
element. The following example creates two objects from a derived class, but one object is declared as the base class and the
other as the derived class.
In the preceding example, the variable basObj is declared as the base class. Assigning a dervCls object to it constitutes a
widening conversion and is therefore valid. However, the base class cannot access the shadowing version of the variable z in
the derived class, so the compiler resolves basObj.z to the original base class value.
See Also
Reference
Shadows
Overrides
Me
MyBase
Concepts
Scope in Visual Basic
Widening and Narrowing Conversions
Other Resources
References to Declared Elements
Visual Basic Language Concepts
Redefined element Any declared element type Only a procedure (Function, Sub, or Operator
) or property
Redefining element Any declared element type Only a procedure or property with the identical
calling sequence1
Access level of redefining ele Any access level Cannot change access level of overridden elem
ment ent
Readability and writability of Any combination Cannot change readability or writability of over
redefining element ridden property
Control over redefining Base class element cannot enforce or prohibit sh Base class element can specify MustOverride,
adowing NotOverridable, or Overridable
Keyword usage Shadows recommended in derived class; Shado Overridable or MustOverride required in bas
ws assumed if neither Shadows nor Overrides e class; Overrides required in derived class
specified2
Inheritance of redefining ele Shadowing element inherited by further derived Overriding element inherited by further derive
ment by classes deriving fro classes; shadowed element still hidden3 d classes; overridden element still overridden
m your derived class
1 The calling sequence consists of the element type (Function, Sub, Operator, or Property), name, parameter list, and return
type. You cannot override a procedure with a property, or the other way around. You cannot override one kind of procedure
(Function, Sub, or Operator) with another kind.
2 If you do not specify either Shadows or Overrides, the compiler issues a warning message to help you be sure which kind of
redefinition you want to use. If you ignore the warning, the shadowing mechanism is used.
3 If the shadowing element is inaccessible in a further derived class, shadowing is not inherited. For example, if you declare the
shadowing element as Private, a class deriving from your derived class inherits the original element instead of the shadowing
element.
Guidelines
You normally use overriding in the following cases:
You are defining polymorphic derived classes.
You want the safety of having the compiler enforce the identical element type and calling sequence.
You normally use shadowing in the following cases:
You anticipate that your base class might be modified and define an element using the same name as yours.
You want the freedom of changing the element type or calling sequence.
See Also
Tasks
How to: Distinguish Between Two Elements with the Same Name
How to: Hide a Variable with the Same Name as Your Variable
How to: Hide an Inherited Variable
How to: Access a Variable Hidden by a Derived Class
Reference
Shadows
Overrides
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Shadowing in Visual Basic
Other Resources
References to Declared Elements
Visual Basic Language Concepts
How to: Hide a Variable with the Same Name as Your Variable
You can hide a variable by shadowing it, that is, by redefining it with a variable of the same name. You can shadow the variable
you want to hide in two ways:
Shadowing Through Scope. You can shadow it through scope by redeclaring it inside a subregion of the region
containing the variable you want to hide.
Shadowing Through Inheritance. If the variable you want to hide is defined at class level, you can shadow it through
inheritance by redeclaring it with the Shadows keyword in a derived class.
Two Ways to Hide a Variable
To hide a variable by shadowing it through scope
1. Determine the region defining the variable you want to hide, and determine a subregion in which to redefine it with your
variable.
Variable's region Allowable subregion for redefining it
Module A class within the module
You cannot redefine a procedure variable in a block within that procedure, for example in an If...End If construction or a
For loop.
2. Create the subregion if it does not already exist.
3. Within the subregion, write a Dim Statement (Visual Basic) declaring the shadowing variable.
When code inside the subregion refers to the variable name, the compiler resolves the reference to the shadowing
variable.
The following example illustrates shadowing through scope, as well as a reference that bypasses the shadowing.
Module shadowByScope
' The following statement declares num as a module-level variable.
Public num As Integer
Sub show()
' The following statement declares num as a local variable.
Dim num As Integer
' The following statement sets the value of the local variable.
num = 2
' The following statement displays the module-level variable.
MsgBox(CStr(shadowByScope.num))
End Sub
Sub useModuleLevelNum()
' The following statement sets the value of the module-level variable.
num = 1
show()
End Sub
End Module
The preceding example declares the variable num both at module level and at procedure level (in the procedure show). The
local variable num shadows the module-level variable num within show, so the local variable is set to 2. However, there is
no local variable to shadow num in the useModuleLevelNum procedure. Therefore, useModuleLevelNum sets the value of the
module-level variable to 1.
The MsgBox call inside show bypasses the shadowing mechanism by qualifying num with the module name. Therefore, it
displays the module-level variable instead of the local variable.
To hide a variable by shadowing it through inheritance
1. Be sure the variable you want to hide is declared in a class, and at class level (outside any procedure). Otherwise you
cannot shadow it through inheritance.
2. Define a class derived from the variable's class if one does not already exist.
3. Inside the derived class, write a Dim statement declaring your variable. Include the Shadows keyword in the declaration.
When code in the derived class refers to the variable name, the compiler resolves the reference to your variable.
The following example illustrates shadowing through inheritance. It makes two references, one that accesses the
shadowing variable and one that bypasses the shadowing.
The preceding example declares the variable shadowString in the base class and shadows it in the derived class. The
procedure showStrings in the derived class displays the shadowing version of the string when the name shadowString is
not qualified. It then displays the shadowed version when shadowString is qualified with the MyBase keyword.
Robust Programming
Shadowing introduces more than one version of a variable with the same name. When a code statement refers to the variable
name, the version to which the compiler resolves the reference depends on factors such as the location of the code statement
and the presence of a qualifying string. This can increase the risk of referring to an unintended version of a shadowed variable.
You can lower that risk by fully qualifying all references to a shadowed variable.
See Also
Tasks
How to: Distinguish Between Two Elements with the Same Name
How to: Hide an Inherited Variable
How to: Access a Variable Hidden by a Derived Class
Reference
Overrides
MyBase
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Shadowing in Visual Basic
Differences Between Shadowing and Overriding
Other Resources
References to Declared Elements
Visual Basic Language Concepts
The preceding example declares the variable shadowString in the base class and shadows it in the derived class. The
procedure showStrings in the derived class displays the shadowing version of the string when the name shadowString is
not qualified. It then displays the shadowed version when shadowString is qualified with the MyBase keyword.
Robust Programming
Shadowing introduces more than one version of a variable with the same name. When a code statement refers to the variable
name, the version to which the compiler resolves the reference depends on factors such as the location of the code statement
and the presence of a qualifying string. This can increase the risk of referring to an unintended version of a shadowed variable.
You can lower that risk by fully qualifying all references to a shadowed variable.
See Also
Tasks
How to: Distinguish Between Two Elements with the Same Name
How to: Hide a Variable with the Same Name as Your Variable
How to: Access a Variable Hidden by a Derived Class
Reference
Overrides
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Shadowing in Visual Basic
Differences Between Shadowing and Overriding
Other Resources
References to Declared Elements
Visual Basic Language Concepts
The preceding example declares the variable shadowString in the base class and shadows it in the derived class. The
procedure showStrings in the derived class displays the shadowing version of the string when the name shadowString is
not qualified. It then displays the shadowed version when shadowString is qualified with the MyBase keyword.
Robust Programming
To lower the risk of referring to an unintended version of a shadowed variable, you can fully qualify all references to a
shadowed variable. Shadowing introduces more than one version of a variable with the same name. When a code statement
refers to the variable name, the version to which the compiler resolves the reference depends on factors such as the location of
the code statement and the presence of a qualifying string. This can increase the risk of referring to the wrong version of the
variable.
See Also
Tasks
How to: Distinguish Between Two Elements with the Same Name
How to: Hide a Variable with the Same Name as Your Variable
How to: Hide an Inherited Variable
Reference
Shadows
Overrides
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Shadowing in Visual Basic
Differences Between Shadowing and Overriding
Other Resources
References to Declared Elements
Visual Basic Language Concepts
Literal With a literal type character; see "Literal Type Characters" in Type Characters
Dim searchChar As Char = "." C
Procedure parame In a Sub Statement (Visual Basic), Function Statement (Visual Basic), or Operator Statement
ter Sub addSale(ByVal amount As Double)
Procedure argume In the calling code; each argument is a programming element that has already been declared, or an express
nt ion containing declared elements
subString = Left( inputString , 5 )
See Also
Tasks
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Concepts
Type Characters
Composite Data Types
Generic Types in Visual Basic
Typeless Programming in Visual Basic
Other Resources
Elementary Data Types
Data Type Implementation
Type Conversions in Visual Basic
Structures: Your Own Data Types
Visual Basic Language Concepts
Type Characters
In addition to specifying a data type in a declaration statement, you can force the data type of some programming elements
with a type character. The type character must immediately follow the element, with no intervening characters of any kind.
The type character is not part of the name of the element. An element defined with a type character can be referenced without
the type character.
Identifier Type Characters
Visual Basic supplies a set of identifier type characters, which you can use in a declaration to specify the data type of a variable
or constant. The following table shows the available identifier type characters with examples of usage.
Identifier type character Data type Example
% Integer Dim L%
! Single Dim Q!
# Double Dim X#
No identifier type characters exist for the Boolean, Byte, Char, Date, Object, SByte, Short, UInteger, ULong, or UShort data
types, or for any composite data types such as arrays or structures.
In some cases, you can append the $ character to a Visual Basic function, for example Left$ instead of Left, to obtain a
returned value of type String.
In all cases, the identifier type character must immediately follow the identifier name.
Literal Type Characters
A literal is a textual representation of a particular value of a data type.
Default Literal Types
The form of a literal as it appears in your code normally determines its data type. The following table shows these default
types.
Textual form of literal Default data type Example
Numeric, no fractional part Integer 2147483647
I Integer J = 347I
L Long K = 347L
D Decimal X = 347D
F Single Y = 347F
R Double Z = 347R
US UShort L = 347US
UI UInteger M = 347UI
UL ULong N = 347UL
C Char Q = "."C
No literal type characters exist for the Boolean, Byte, Date, Object, SByte, or String data types, or for any composite data
types such as arrays or structures.
Literals can also use the identifier type characters (%, &, @, !, #, $), as can variables, constants, and expressions. However, the
literal type characters (S, I, L, D, F, R, C) can be used only with literals.
In all cases, the literal type character must immediately follow the literal value.
Hexadecimal and Octal Literals
The compiler normally construes an integer literal to be in the decimal (base 10) number system. You can force an integer
literal to be hexadecimal (base 16) with the &H prefix, and you can force it to be octal (base 8) with the &O prefix. The digits
following the prefix must be appropriate for the number system. The following table illustrates this.
Number base Prefix Valid digit values Example
Hexadecimal (base 16) &H 0-9 and A-F &HFFFF
You can follow a prefixed literal with a literal type character. The following example shows this.
In the preceding example, counter has the decimal value of -32768, and flags has the decimal value of +32768.
See Also
Tasks
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Concepts
Data Types in Visual Basic
Typeless Programming in Visual Basic
Variable Declaration in Visual Basic
Other Resources
Elementary Data Types
Data Type Implementation
Type Conversions in Visual Basic
Visual Basic Language Concepts
See Also
Reference
Data Type Summary (Visual Basic)
Concepts
Data Types in Visual Basic
Type Characters
Other Resources
Elementary Data Types
Visual Basic Language Concepts
See Also
Reference
Data Type Summary (Visual Basic)
Integer Data Type (Visual Basic)
Long Data Type (Visual Basic)
Decimal Data Type (Visual Basic)
UInteger Data Type
ULong Data Type (Visual Basic)
Concepts
Type Characters
Other Resources
Elementary Data Types
Visual Basic Language Concepts
You can test the function memoryRequired with the following code:
Caution
The UInteger data type is not part of the Common Language Specification (CLS), so CLS-compliant code cannot consu
me a component that uses it.
See Also
Tasks
How to: Call a Windows Function that Takes Unsigned Types
Reference
Data Type Summary (Visual Basic)
Integer Data Type (Visual Basic)
UInteger Data Type
Visual Basic Language Concepts
You can test the function messageThroughWindows with the following code.
Caution
The UInteger, ULong, UShort, and SByte data types are not part of the Common Language Specification (CLS), so CL
S-compliant code cannot consume a component that uses them.
Security Note
Making a call to unmanaged code, such as the Windows application programming interface (API), exposes your code to
potential security risks.
Security Note
Calling the Windows API requires unmanaged code permission, which might affect its execution in partial-trust situatio
ns. For more information, see SecurityPermission and Code Access Permissions.
See Also
Tasks
How to: Optimize Storage of Positive Integers With Unsigned Types
Walkthrough: Calling Windows APIs
Reference
Data Type Summary (Visual Basic)
Integer Data Type (Visual Basic)
UInteger Data Type
Declare Statement
Visual Basic Language Concepts
See Also
Reference
Data Type Summary (Visual Basic)
Single Data Type (Visual Basic)
Object Data Type
Concepts
Data Types in Visual Basic
Type Characters
Value Types and Reference Types
Other Resources
Elementary Data Types
Visual Basic Language Concepts
In the preceding example, array variables arrayA and arrayB are considered to be of the same data type — Byte() — even
though they are initialized to different lengths. Variables arrayB and arrayC are not of the same type because their element
types are different. Variables arrayC and arrayD are not of the same type because their ranks are different. Variables arrayD
and arrayE have the same type — Short(,) — because their ranks and element types are the same, even though arrayD is not
yet initialized.
For more information on arrays, see Arrays in Visual Basic.
Class Types
There is no single data type comprising all classes. Although one class can inherit from another class, each is a separate data
type. Multiple instances of the same class are of the same data type. If you assign one class instance variable to another, not
only do they have the same data type, they point to the same class instance in memory.
For more information on classes, see Understanding Classes.
See Also
Tasks
Troubleshooting Data Types
How to: Hold More Than One Value in a Variable
Concepts
Data Types in Visual Basic
Generic Types in Visual Basic
Typeless Programming in Visual Basic
Data Types Are .NET Framework Types
Other Resources
Elementary Data Types
Data Type Implementation
Type Conversions in Visual Basic
Structures: Your Own Data Types
Visual Basic Language Concepts
When you define a generic type, you parameterize it with one or more data types. This allows the using code to tailor the data
types to its requirements. Your code can declare several different programming elements from the generic element, each one
acting on a different set of data types. But the declared elements all perform the identical logic, no matter what data types they
are using.
For example, you might want to create and use a queue class that operates on a specific data type such as String. You can
declare such a class from System.Collections.Generic.Queue, as the following example shows.
VB
Public stringQ As New System.Collections.Generic.Queue(Of String)
You can now use stringQ to work exclusively with String values. Because stringQ is specific for String instead of being
generalized for Object values, you do not have late binding or type conversion. This saves execution time and reduces run-
time errors.
For more information on using a generic type, see How to: Use a Generic Class.
Example of a Generic Class
The following example shows a skeleton definition of a generic class.
VB
Public Class classHolder(Of t)
Public Sub processNewItem(ByVal newItem As t)
Dim tempItem As t
' Insert code that processes an item of data type t.
End Sub
End Class
In the preceding skeleton, t is a type parameter, that is, a placeholder for a data type that you supply when you declare the
class. Elsewhere in your code, you can declare various versions of classHolder by supplying various data types for t. The
following example shows two such declarations.
VB
Public integerClass As New classHolder(Of Integer)
Friend stringClass As New classHolder(Of String)
The preceding statements declare constructed classes, in which a specific type replaces the type parameter. This replacement is
propagated throughout the code within the constructed class. The following example shows what the processNewItem
procedure looks like in integerClass.
VB
Public Sub processNewItem(ByVal newItem As Integer)
Dim tempItem As Integer
' Inserted code now processes an Integer item.
End Sub
For a more complete example, see How to: Define a Class That Can Provide Identical Functionality on Different Data Types.
Eligible Programming Elements
You can define and use generic classes, structures, interfaces, procedures, and delegates. Note that the .NET Framework defines
several generic classes, structures, and interfaces that represent commonly used generic elements. The
System.Collections.Generic namespace provides dictionaries, lists, queues, and stacks. Before defining your own generic
element, see if it is already available in System.Collections.Generic.
Procedures are not types, but you can define and use generic procedures. See Generic Procedures in Visual Basic.
Advantages of Generic Types
A generic type serves as a basis for declaring several different programming elements, each of which operates on a specific
data type. The alternatives to a generic type are:
1. A single type operating on the Object data type.
2. A set of type-specific versions of the type, each version individually coded and operating on one specific data type such
as String, Integer, or a user-defined type such as customer.
A generic type has the following advantages over these alternatives:
Type Safety. Generic types enforce compile-time type checking. Types based on Object accept any data type, and you
must write code to check whether an input data type is acceptable. With generic types, the compiler can catch type
mismatches before run time.
Performance. Generic types do not have to box and unbox data, because each one is specialized for one data type.
Operations based on Object must box input data types to convert them to Object and unbox data destined for output.
Boxing and unboxing reduce performance.
Types based on Object are also late-bound, which means that accessing their members requires extra code at run time.
This also reduces performance.
Code Consolidation. The code in a generic type has to be defined only once. A set of type-specific versions of a type
must replicate the same code in each version, with the only difference being the specific data type for that version. With
generic types, the type-specific versions are all generated from the original generic type.
Code Reuse. Code that does not depend on a particular data type can be reused with various data types if it is generic.
You can often reuse it even with a data type that you did not originally predict.
IDE Support. When you use a constructed type declared from a generic type, the integrated development environment
(IDE) can give you more support while you are developing your code. For example, IntelliSense™ can show you the type-
specific options for an argument to a constructor or method.
Generic Algorithms. Abstract algorithms that are type-independent are good candidates for generic types. For example,
a generic procedure that sorts items using the IComparable interface can be used with any data type that implements
IComparable.
Constraints
Although the code in a generic type definition should be as type-independent as possible, you might need to require a certain
capability of any data type supplied to your generic type. For example, if you want to compare two items for the purpose of
sorting or collating, their data type must implement the IComparable interface. You can enforce this requirement by adding a
constraint to the type parameter.
Example of a Constraint
The following example shows a skeleton definition of a class with a constraint that requires the type argument to implement
IComparable.
VB
Public Class itemManager(Of t As IComparable)
' Insert code that defines class members.
End Class
If subsequent code attempts to construct a class from itemManager supplying a type that does not implement IComparable,
the compiler signals an error.
Types of Constraints
Your constraint can specify the following requirements in any combination:
The type argument must implement one or more interfaces
The type argument must be of the type of, or inherit from, at most one class
The type argument must expose a parameterless constructor accessible to the code that creates objects from it
The type argument must be a reference type, or it must be a value type
If you need to impose more than one requirement, you use a comma-separated constraint list inside braces ({ }). To require an
accessible constructor, you include the New (Visual Basic) keyword in the list. To require a reference type, you include the
Class (Visual Basic) keyword; to require a value type, you include the Structure (Visual Basic) keyword.
For more information on constraints, see Type List.
Example of Multiple Constraints
The following example shows a skeleton definition of a generic class with a constraint list on the type parameter. In the code
that creates an instance of this class, the type argument must implement both the IComparable and IDisposable interfaces, be
a reference type, and expose an accessible parameterless constructor.
VB
Public Class thisClass(Of t As {IComparable, IDisposable, Class, New})
' Insert code that defines class members.
End Class
Important Terms
Generic types introduce and use the following terms:
Generic Type. A definition of a class, structure, interface, procedure, or delegate for which you supply at least one data
type when you declare it.
Type Parameter. In a generic type definition, a placeholder for a data type you supply when you declare the type.
Type Argument. A specific data type that replaces a type parameter when you declare a constructed type from a generic
type.
Constraint. A condition on a type parameter that restricts the type argument you can supply for it. A constraint can
require that the type argument must implement a particular interface, be or inherit from a particular class, have an
accessible parameterless constructor, or be a reference type or a value type. You can combine these constraints, but you
can specify at most one class.
Constructed Type. A class, structure, interface, procedure, or delegate declared from a generic type by supplying type
arguments for its type parameters.
See Also
Tasks
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Of
As
Object Data Type
Concepts
Data Types in Visual Basic
Type Characters
Value Types and Reference Types
Other Resources
Data Type Implementation
Type Conversions in Visual Basic
Visual Basic Language Concepts
You can declare a class from simpleList to hold a list of Integer values, another class to hold a list of String values, and
another to hold Date values. Except for the data type of the list members, objects created from all these classes behave
identically.
The type argument that the using code supplies to itemType can be an intrinsic type such as Boolean or Double, a
structure, an enumeration, or any type of class, including one that your application defines.
You can test the class simpleList with the following code.
VB
Public Sub useSimpleList()
Dim iList As New simpleList(Of Integer)(2)
Dim sList As New simpleList(Of String)(3)
Dim dList As New simpleList(Of Date)(2)
iList.add(10)
iList.add(20)
iList.add(30)
sList.add("First")
sList.add("extra")
sList.add("Second")
sList.add("Third")
sList.remove(1)
dList.add(#1/1/2003#)
dList.add(#3/3/2003#)
dList.insert(#2/2/2003#, 1)
Dim s As String = _
"Simple list of 3 Integer items (reported length " _
& CStr(iList.listLength) & "):" _
& vbCrLf & CStr(iList.listItem(0)) _
& vbCrLf & CStr(iList.listItem(1)) _
& vbCrLf & CStr(iList.listItem(2)) _
& vbCrLf _
& "Simple list of 4 - 1 String items (reported length " _
& CStr(sList.listLength) & "):" _
& vbCrLf & CStr(sList.listItem(0)) _
& vbCrLf & CStr(sList.listItem(1)) _
& vbCrLf & CStr(sList.listItem(2)) _
& vbCrLf _
& "Simple list of 2 + 1 Date items (reported length " _
& CStr(dList.listLength) & "):" _
& vbCrLf & CStr(dList.listItem(0)) _
& vbCrLf & CStr(dList.listItem(1)) _
& vbCrLf & CStr(dList.listItem(2))
MsgBox(s)
End Sub
See Also
Tasks
How to: Use a Generic Class
Reference
Of
Type List
Object Data Type
Concepts
Data Types in Visual Basic
Generic Types in Visual Basic
Common Language Specification
Visual Basic Language Concepts
See Also
Tasks
How to: Define a Class That Can Provide Identical Functionality on Different Data Types
Reference
Of
Imports Statement
Concepts
Data Types in Visual Basic
Generic Types in Visual Basic
Common Language Specification
Visual Basic Language Concepts
If the compiler cannot infer the type arguments from the context of your call, it reports an error. One possible cause of such an
error is an array rank mismatch. For example, suppose you define a normal parameter as an array of a type parameter. If you
call the generic procedure supplying an array of a different rank (number of dimensions), the mismatch causes type inference
to fail. The following code shows a call in which a two-dimensional array is passed to a procedure that expects a one-
dimensional array.
Public Sub demoSub(Of t)(ByVal arg() As t)
End Sub
Public Sub callDemoSub()
Dim twoDimensions(,) As Integer
demoSub(twoDimensions)
End Sub
You can invoke type inference only by omitting all the type arguments. If you supply one type argument, you must supply
them all.
Type inference is supported only for generic procedures. You cannot invoke type inference on generic classes, structures,
interfaces, or delegates.
Example
The following example defines a generic Function procedure to find a particular element in an array. It defines one type
parameter and uses it to construct the two parameters in the parameter list.
VB
Public Function findElement(Of T As IComparable) _
(ByVal searchArray As T(), ByVal searchValue As T) As Integer
If searchArray.GetLength(0) > 0 Then
For i As Integer = 0 To searchArray.GetUpperBound(0)
If searchArray(i).CompareTo(searchValue) = 0 Then Return i
Next i
End If
Return -1
End Function
The preceding example requires the ability to compare searchValue against each element of searchArray. To guarantee this
ability, it constrains the type parameter T to implement the IComparable interface. The code uses the CompareTo method
instead of the = operator, because there is no guarantee that a type argument supplied for T supports the = operator.
You can test the findElement procedure with the following code.
VB
Public Sub tryFindElement()
Dim stringArray() As String = {"abc", "def", "xyz"}
Dim stringSearch As String = "abc"
Dim integerArray() As Integer = {7, 8, 9}
Dim integerSearch As Integer = 8
Dim dateArray() As Date = {#4/17/1969#, #9/20/1998#, #5/31/2004#}
Dim dateSearch As Date = Microsoft.VisualBasic.DateAndTime.Today
MsgBox(CStr(findElement(Of String)(stringArray, stringSearch)))
MsgBox(CStr(findElement(Of Integer)(integerArray, integerSearch)))
MsgBox(CStr(findElement(Of Date)(dateArray, dateSearch)))
End Sub
The preceding calls to MsgBox display "0", "1", and "-1" respectively.
See Also
Tasks
How to: Define a Class That Can Provide Identical Functionality on Different Data Types
How to: Use a Generic Class
Reference
Type List
Parameter List
Concepts
Generic Types in Visual Basic
Procedures in Visual Basic
Procedure Parameters and Arguments
Visual Basic Language Concepts
The variable ridesBusToWork can hold a value of True, a value of False, or no value at all. Its initial default value is no value at
all, which in this case could mean that the information has not yet been obtained for this person. In contrast, False could mean
that the information has been obtained and the person does not ride the bus to work.
You can declare variables and properties with nullable types, and you can declare an array with elements of a nullable type.
You can declare procedures with nullable types as parameters, and you can return a nullable type from a Function procedure.
You cannot construct a nullable type on a reference type such as an array, a String, or a class. The underlying type must be a
value type. For more information, see Value Types and Reference Types.
Using a Nullable Type Variable
The most important members of a nullable type are its HasValue and Value properties. For a variable of a nullable type,
HasValue tells you whether the variable contains a defined value. If HasValue is True, you can read the value from Value.
Note that both HasValue and Value are ReadOnly properties.
Default Values
When you declare a variable with a nullable type, its HasValue property has a default value of False. This means that the
variable itself defaults to having no defined value, rather than the default value of its underlying value type. In the following
example, the variable numberOfChildren initially has no defined value, even though the default value of the Integer type is 0.
A null value is useful to indicate an undefined or unknown value. If numberOfChildren had been declared as Integer, there
would be no value that could indicate that the information is not currently available.
Storing Values
You store a value in a variable or property of a nullable type in the normal way. The following example assigns a value to the
variable numberOfChildren declared in the preceding example.
numberOfChildren = 2
If a variable or property of a nullable type contains a defined value, you can cause it to revert to its initial state of not having a
value assigned. You do this by setting the variable or property to Nothing, as the following example shows.
numberOfChildren = Nothing
Note
Although you can assign Nothing to a variable of a nullable type, you cannot test it for Nothing. You must test its HasValu
e property for False.
Retrieving Values
To retrieve the value of a variable of a nullable type, you should first test its HasValue property to confirm that it has a value. If
you attempt to read the value when HasValue is False, Visual Basic throws an InvalidOperationException exception. The
following example shows the recommended way to read the variable numberOfChildren of the preceding examples.
If numberOfChildren.HasValue Then
MsgBox("There are " & CStr(numberOfChildren) & " children.")
Else
MsgBox("It is not known how many children there are.")
End If
You can also use the New keyword to initialize a value type. This is particularly useful if the type has a constructor that takes
parameters. An example of this is the Decimal constructor, which builds a new Decimal value from the supplied parts.
Data Types Have Members
Because they are supported by .NET Framework structures and classes, Visual Basic data types have members. These members
include constructors, methods, properties, and fields. You can access the members (except the constructors) on a variable the
same way you access methods and properties on an object.
The following example uses the Year, Month, and Day properties and the DaysInMonth method of the System.DateTime
structure to determine how many days are remaining in the current month.
Note that you must qualify a reference to a data type member with either the name of the type (Date) or the name of a variable
declared to be of that type (current).
Examples of Data Type Members
The following code prototypes illustrate some of the useful methods, properties, and fields on the data types.
<Char>.IsDigit() ' Returns True if character is a numeric digit.
<Char>.IsLower() ' Returns True if character is a lowercase letter.
<Date>.IsLeapYear() ' Returns True if current year is a leap year.
<Date>.ToUniversalTime() ' Returns local date/time converted to UTC.
<Double>.IsInfinity() ' Returns True if contents represent infinity.
<Double>.IsNaN() ' Returns True if contents are not a number (0/0).
<Long>.MaxValue ' Constant representing largest positive Int64 value.
<Object>.GetType() ' Returns Type object representing type of <Object>.
<Object>.GetType().GetTypeCode() ' Returns type code of <Object>.
<String>.Chars(<index>) ' Character at position <index> of <String>.
<String>.Length ' Number of characters currently in <String>.
All numeric types, including Byte and Char, expose the MaxValue and MinValue public fields, which can be very useful when
dealing with these types.
Equivalence of Data Type Members Is Not Assured
The .NET Framework also supplies a number of methods on data types that might appear to be equivalent to Visual Basic
functions and keywords. However, Visual Basic does not always use the .NET Framework methods to accomplish conversion or
other operations, and the results are not always identical.
For example, the ToSingle method performs the same type of action as the CSng keyword does on a Decimal expression. But
CSng is not guaranteed to use System.<data type>.ToSingle, and therefore the results are not guaranteed to be the same
under marginal or boundary conditions.
In general, you should use the Visual Basic programming elements because they are easier to use and make your code more
readable. In some cases you might need some additional functionality provided by a .NET Framework method. For an example
of this, see "Mod Operator Does Not Return Accurate Result" in Troubleshooting Data Types.
See Also
Reference
Boolean
Byte
Char
DateTime
Decimal
Double
Guid
TimeZone
Concepts
Value Types and Reference Types
Structures and Classes
Visual Basic Language Concepts
Byte Byte, Short, UShort, Integer, UInteger, Long, ULong, Decimal, Single, Double
Double Double
Any enumerated type (Enum) Its underlying integral type and any type to which the underlying type widens
2 Conversions from Integer, UInteger, Long, ULong, or Decimal to Single or Double might result in loss of precision, but
never in loss of magnitude. In this sense they do not incur information loss.
3 It might seem surprising that a conversion from a derived type to one of its base types is widening. The justification is that
the derived type contains all the members of the base type, so it qualifies as an instance of the base type. In the opposite
direction, the base type does not contain any new members defined by the derived type.
Widening conversions always succeed at run time and never incur data loss. You can always perform them implicitly, whether
the Option Strict Statement sets the type checking switch to On or to Off.
Narrowing Conversions
The standard narrowing conversions include the following:
The reverse directions of the widening conversions in the preceding table (except that every type widens to itself)
Conversions in either direction between Boolean and any numeric type
Conversions from any numeric type to any enumerated type (Enum)
Conversions in either direction between String and any numeric type, Boolean, or Date
Conversions from a data type or object type to a type derived from it
Narrowing conversions do not always succeed at run time, and can fail or incur data loss. An error occurs if the destination
data type cannot receive the value being converted. For example, a numeric conversion can result in an overflow. The compiler
does not allow you to perform narrowing conversions implicitly unless the Option Strict Statement sets the type checking
switch to Off.
When to Use Narrowing Conversions
You use a narrowing conversion when you know the source value can be converted to the destination data type without error
or data loss. For example, if you have a String that you know contains either "True" or "False", you can use the CBool keyword
to convert it to Boolean.
Exceptions During Conversion
Because widening conversions always succeed, they do not throw exceptions. Narrowing conversions, when they fail, most
commonly throw the following exceptions:
InvalidCastException — if no conversion is defined between the two types
OverflowException — (integral types only) if the converted value is too large for the target type
If a class or structure defines a CType Function to serve as a conversion operator to or from that class or structure, that CType
can throw any exception it deems appropriate. In addition, that CType might call Visual Basic functions or .NET Framework
methods, which in turn could throw a variety of exceptions.
See Also
Tasks
How to: Convert an Object to Another Type in Visual Basic
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Data Types in Visual Basic
Implicit and Explicit Conversions
Value Changes During Conversions
Conversions Between Strings and Other Types
Array Conversions
Typeless Programming in Visual Basic
Other Resources
Type Conversions in Visual Basic
Visual Basic Language Concepts
Dim k As Integer
Dim q As Double
' Integer widens to Double, so you can do this with Option Strict On.
k = 432
q = K
An explicit conversion uses a type conversion keyword. Visual Basic provides several such keywords, which coerce an
expression in parentheses to the desired data type. These keywords act like functions, but the compiler generates the code
inline, so execution is slightly faster than with a function call.
In the following extension of the preceding example, the CInt keyword converts the value of q back to an integer before
assigning it to k.
Conversion Keywords
The following table shows the available conversion keywords.
Type conversi Converts an expression to da Allowable data types of expression to be converted
on keyword ta type
CBool Boolean Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), String, Ob
ject
CByte Byte Data Type (Visual Basic) Any numeric type (including SByte and enumerated types), Boolean, String,
Object
CDbl Double Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object
CDec Decimal Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object
CInt Integer Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object
CLng Long Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object
CSByte SByte Data Type (Visual Basic) Any numeric type (including Byte and enumerated types), Boolean, String,
Object
CShort Short Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object
CSng Single Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object
CStr String Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
Char, Char array, Date, Object
CType Type specified following the co When converting to an elementary data type (including an array of an eleme
mma (,) ntary type), the same types as allowed for the corresponding conversion key
word
When converting to a composite data type, the interfaces it implements and t
he classes from which it inherits
When converting to a class or structure on which you have overloaded CTyp
e, that class or structure
CUInt UInteger Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object
CULng ULong Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object
CUShort UShort Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object
k = CType(q, Integer)
' The following statement coerces w to the specific object class Label.
f = CType(w, Label)
Composite Types
You can use CType to convert values to composite data types as well as to elementary types. You can also use it to coerce an
object class to the type of one of its interfaces, as in the following example.
Array Types
CType can also convert array data types, as in the following example.
Dim v() As classV
Dim obArray() As Object
' Assume some object array has been assigned to obArray.
' Check for run-time type compatibility.
If TypeOf obArray Is classV()
' obArray can be converted to classV.
v = CType(obArray, classV())
End If
Caution
Specifying CType to convert from one class type to another fails at run time if the source type does not derive from the desti
nation type. Such a failure throws an InvalidCastException exception.
However, if one of the types is a structure or class you have defined, and if you have defined CType on that structure or class, a
conversion can succeed if it satisfies the requirements of your CType. See How to: Define a Conversion Operator.
Performing an explicit conversion is also known as casting an expression to a given data type or object class.
See Also
Tasks
How to: Convert an Object to Another Type in Visual Basic
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Value Changes During Conversions
Conversions Between Strings and Other Types
Typeless Programming in Visual Basic
Other Resources
Type Conversions in Visual Basic
Structures: Your Own Data Types
Visual Basic Language Concepts
See Also
Tasks
How to: Convert an Object to Another Type in Visual Basic
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Widening and Narrowing Conversions
Implicit and Explicit Conversions
Conversions Between Strings and Other Types
Array Conversions
Typeless Programming in Visual Basic
Other Resources
Type Conversions in Visual Basic
Structures: Your Own Data Types
Visual Basic Language Concepts
When Visual Basic converts a string to a numeric value, it uses the Regional Options settings specified in the Windows
Control Panel to interpret the thousands separator, decimal separator, and currency symbol. This means that a conversion
might succeed under one setting but not another. For example, "$14.20" is acceptable in the English (United States) locale but
not in any French locale.
See Also
Tasks
How to: Convert an Object to Another Type in Visual Basic
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Widening and Narrowing Conversions
Implicit and Explicit Conversions
Value Changes During Conversions
Array Conversions
Introduction to International Applications Based on the .NET Framework
Other Resources
Type Conversions in Visual Basic
Visual Basic Language Concepts
If you know that the contents of an Object variable are of a particular data type, it is better to convert the variable to that data
type. If you continue to use the Object variable, you incur either boxing and unboxing (for a value type) or late binding (for a
reference type). These operations all take extra execution time and make your performance slower.
Compiling the Code
This example requires:
A reference to the System namespace.
See Also
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Object
Concepts
Widening and Narrowing Conversions
Implicit and Explicit Conversions
Value Changes During Conversions
Conversions Between Strings and Other Types
Array Conversions
Typeless Programming in Visual Basic
Other Resources
Type Conversions in Visual Basic
Structures: Your Own Data Types
Visual Basic Language Concepts
Array Conversions
You can convert an array type to a different array type provided you meet the following conditions:
Equal Rank. The ranks of the two arrays must be the same, that is, they must have the same number of dimensions.
However, the lengths of the respective dimensions do not need to be the same.
Element Data Type. The data types of the elements of both arrays must be reference types. You cannot convert an
Integer array to a Long array, or even to an Object array, because at least one value type is involved. For more
information, see Value Types and Reference Types.
Convertibility. A conversion, either widening or narrowing, must be possible between the element types of the two
arrays. An example that fails this requirement is an attempted conversion between a String array and an array of a class
derived from System.Attribute. These two types have nothing in common, and no conversion of any kind exists between
them.
A conversion of one array type to another is widening or narrowing depending on whether the conversion of the respective
elements is widening or narrowing. For more information, see Widening and Narrowing Conversions.
Conversion to an Object Array
When you declare an Object array without initializing it, its element type is Object as long as it remains uninitialized. When
you set it to an array of a specific class, it takes on the type of that class. However, its underlying type is still Object, and you
can subsequently set it to another array of an unrelated class. Since all classes derive from Object, you can change the array's
element type from any class to any other class.
In the following example, no conversion exists between types student and String, but both derive from Object, so all
assignments are valid.
See Also
Tasks
How to: Convert an Object to Another Type in Visual Basic
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Data Types in Visual Basic
Implicit and Explicit Conversions
Value Changes During Conversions
Conversions Between Strings and Other Types
Typeless Programming in Visual Basic
Other Resources
Type Conversions in Visual Basic
Arrays in Visual Basic
Visual Basic Language Concepts
The salary field in the preceding example is Private, which means it is inaccessible outside the structure, even from the
containing class. However, the giveRaise procedure is Public, so it can be called from outside the structure. Similarly,
you can raise the salaryReviewTime event from outside the structure.
In addition to variables, Sub procedures, and events, you can also define constants, Function procedures, and properties
in a structure. You can designate at most one property as the default property, provided it takes at least one argument.
You can handle an event with a Shared (Visual Basic) Sub procedure. For more information, see
How to: Declare and Call a Default Property in Visual Basic.
See Also
Tasks
Troubleshooting Data Types
Reference
User-Defined Data Type
Concepts
Data Types in Visual Basic
Composite Data Types
Structure Variables
Structures and Other Programming Elements
Structures and Classes
Other Resources
Elementary Data Types
Data Type Implementation
Structures: Your Own Data Types
Visual Basic Language Concepts
Structure Variables
Once you have created a structure, you can declare procedure-level and module-level variables as that type. For example, you
can create a structure that records information about a computer system. The following example demonstrates this.
You can now declare variables of that type. The following declaration illustrates this.
Note
In classes and modules, structures declared using the Dim Statement (Visual Basic) default to public access. If you intend a str
ucture to be private, make sure you declare it using the Private (Visual Basic) keyword.
mySystem.cPU = "486"
Dim tooOld As Boolean
If yourSystem.purchaseDate < #1/1/1992# Then tooOld = True
yourSystem = mySystem
If a structure element is a reference type, such as a String, Object, or array, the pointer to the data is copied. In the previous
example, if systemInfo had included an object variable, then the preceding example would have copied the pointer from
mySystem to yourSystem, and a change to the object's data through one structure would be in effect when accessed through the
other structure.
See Also
Tasks
Troubleshooting Data Types
How to: Declare a Structure
Reference
Structure Statement
Concepts
Data Types in Visual Basic
Composite Data Types
Structures and Other Programming Elements
Structures and Classes
Other Resources
Elementary Data Types
Data Type Implementation
Structures: Your Own Data Types
Visual Basic Language Concepts
You access the values of an array within a structure the same way you access a property on an object. The following example
illustrates this.
You can also declare an array of structures. The following example illustrates this.
You follow the same rules to access the components of this data architecture. The following example illustrates this.
ReDim allSystems(5).diskDrives(3)
allSystems(5).CPU = "386SX"
allSystems(5).diskDrives(2) = "100M SCSI"
You should use a specific object class in such a declaration, rather than Object.
Structures and Procedures
You can pass a structure as a procedure argument. The following example illustrates this.
The preceding example passes the structure by reference, which allows the procedure to modify its elements so that the
changes take effect in the calling code. If you want to protect a structure against such modification, pass it by value.
You can also return a structure from a Function procedure. The following example illustrates this.
You can also use this technique to encapsulate a structure defined in one module within a structure defined in a different
module.
Structures can contain other structures to an arbitrary depth.
See Also
Tasks
Troubleshooting Data Types
How to: Declare a Structure
Reference
Structure Statement
Concepts
Data Types in Visual Basic
Composite Data Types
Structure Variables
Structures and Classes
Other Resources
Elementary Data Types
Data Type Implementation
Structures: Your Own Data Types
Visual Basic Language Concepts
See Also
Tasks
Troubleshooting Data Types
Concepts
Data Types in Visual Basic
Composite Data Types
Structures and Other Programming Elements
Value Types and Reference Types
Other Resources
Data Type Implementation
Structures: Your Own Data Types
Understanding Classes
Visual Basic Language Concepts
Function safeSqrt(num)
' Make sure num is positive for square root.
tempVal = Math.Abs(num)
Return Math.Sqrt(tempVal)
End Function
Visual Basic automatically creates tempVal as a local variable, which you can use as if you had declared it explicitly. While this is
convenient, it can lead to subtle errors in your code if you misspell a variable name. Suppose you had written the procedure in
the preceding example as follows:
Function safeSqrt(num)
' Make sure num is positive for square root.
tempVal = Math.Abs(num)
Return Math.Sqrt(temVal)
End Function
At first glance, this code looks the same. But because the tempVal variable is misspelled as the argument to Sqrt, the compiler
creates an additional local variable called temVal, which is never assigned a value, and your function always returns zero.
Unintended Existing Element Reference
When Visual Basic encounters a new name, it cannot determine whether you meant to declare a new variable implicitly, or
whether you misspelled an existing variable name. Therefore it attempts to create a new variable with that name. There might
be a variable or other programming element already defined with that name, and your code would use that definition
unintentionally.
You can avoid problems with misnamed variables by using explicit declaration.
Explicit Declaration
Had explicit declaration been in effect for the source file containing the safeSqrt procedure in the preceding example, Visual
Basic would have recognized tempVal and temVal as undeclared variables and generated errors for both of them. As a result,
you would then explicitly declare tempVal. The following example illustrates this.
With this revised code, you would understand the problem immediately because Visual Basic would display an error message
for the incorrectly spelled temVal. Because explicit declaration helps you catch these kinds of errors, it is recommended that
you use it with all your code.
Note
The Option Explicit statement operates on a file-by-file basis. It must be at the beginning of every source code file in which
you want to control the enforcement of explicit variable declaration.
See Also
Tasks
How to: Modify Project Properties and Configuration Settings
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Typeless Programming in Visual Basic
Type Checking in Visual Basic
Object as the Universal Data Type
Efficient Use of Data Types
Variables in Visual Basic
Visual Basic Naming Conventions
Visual Basic Language Concepts
Dim v As Object
v = "17"
' v contains the 2-character String value "17".
v = v - 15
' v now contains the Integer value 2.
v = "H" & v
' v now contains the 2-character String value "H2".
While you can perform such operations on Object variables without much concern for the kind of data they contain, you must
avoid the following traps:
If you perform arithmetic operations or functions on an Object, it must hold numerical data or a run-time error occurs.
If you are concatenating strings, use the & operator instead of the + operator. There are complex rules governing when
the + operator adds its operands and when it concatenates them. The + operator also must perform type checking and
conversion in some cases, which reduces performance.
Changing an Object Variable's Data Type
Although an Object variable can accept data of any type, you cannot change the variable itself to a different data type.
However, you can redimension an Object variable to an array of Object variables. The following example illustrates both valid
and invalid uses of the ReDim Statement (Visual Basic).
The first ReDim statement changes someObj to an array of type Object. This is valid only with the Object data type. The
second ReDim statement is invalid because it involves a different data type. You can achieve the desired effect by using a
separate array. The following example illustrates this.
Private x As Double
Protected s As String
Character Conversion
The AscW and ChrW functions operate in Unicode. You should use them in preference to Asc and Chr, which must translate
into and out of Unicode.
See Also
Reference
Asc, AscW Functions
Chr, ChrW Functions
Concepts
Data Types in Visual Basic
Typeless Programming in Visual Basic
Implicit and Explicit Declaration
Type Checking in Visual Basic
Object as the Universal Data Type
Numeric Data Types
Variable Declaration in Visual Basic
Other Resources
Using IntelliSense
Visual Basic Language Reference
The preceding example uses the ToString method of the Double structure so that it can specify greater precision than the CStr
keyword uses. The default is 15 digits, but the "G17" format extends it to 17 digits.
Mod Operator Does Not Return Accurate Result
Because of the imprecision of floating-point storage, the Mod Operator (Visual Basic) can return an unexpected result when at
least one of the operands is floating-point.
The Decimal Data Type (Visual Basic) does not use floating-point representation. Many numbers that are inexact in Single and
Double are exact in Decimal (for example 0.2 and 0.3). Although arithmetic is slower in Decimal than in floating-point, it
might be worth the performance decrease to achieve greater precision.
To find the integer remainder of floating-point quantities
1. Declare variables as Decimal.
2. Use the literal type character D to force literals to Decimal, in case their values are too large for the Long data type.
The following example demonstrates the potential imprecision of floating-point operands.
VB
Dim two As Double = 2.0
Dim zeroPointTwo As Double = 0.2
Dim quotient As Double = two / zeroPointTwo
Dim doubleRemainder As Double = two Mod zeroPointTwo
MsgBox("2.0 is represented as " & two.ToString("G17") _
& vbCrLf & "0.2 is represented as " & zeroPointTwo.ToString("G17") _
& vbCrLf & "2.0 / 0.2 generates " & quotient.ToString("G17") _
& vbCrLf & "2.0 Mod 0.2 generates " _
& doubleRemainder.ToString("G17"))
The preceding example uses the ToString method of the Double structure so that it can specify greater precision than the
CStr keyword uses. The default is 15 digits, but the "G17" format extends it to 17 digits.
Because zeroPointTwo is Double, its value for 0.2 is an infinitely repeating binary fraction with a stored value of
0.20000000000000001. Dividing 2.0 by this quantity yields 9.9999999999999995 with a remainder of
0.19999999999999991.
In the expression for decimalRemainder, the literal type character D forces both operands to Decimal, and 0.2 has a precise
representation. Therefore the Mod operator yields the expected remainder of 0.0.
Note that it is not sufficient to declare decimalRemainder as Decimal. You must also force the literals to Decimal, or they
default to Double and decimalRemainder receives the same inaccurate value as doubleRemainder.
Boolean Type Does Not Convert to Numeric Type Accurately
Boolean Data Type (Visual Basic) values are not stored as numbers, and the stored values are not intended to be equivalent to
numbers. For compatibility with previous versions, Visual Basic provides conversion keywords (CType Function, CBool, CInt,
and so on) to convert between Boolean and numeric types. However, other languages sometimes perform these conversions
differently, as do the .NET Framework methods.
You should never write code that relies on equivalent numeric values for True and False. Whenever possible, you should
restrict usage of Boolean variables to the logical values for which they are designed. If it is necessary to mix Boolean and
numeric values, be sure that you understand the conversion method you choose.
Conversion in Visual Basic
When you use the CType or CBool conversion keywords to convert numeric data types to Boolean, 0 becomes False and all
other values become True. When you convert Boolean values to numeric types using the conversion keywords, False
becomes 0 and True becomes -1.
Conversion in the Framework
The ToInt32 method of the Convert class in the System namespace converts True to +1.
If you need to convert a Boolean value to a numeric data type, take care which conversion method you use.
Character Literal Generates Compiler Error
In the absence of any type characters, Visual Basic assumes default data types for literals. The default type for a character literal
— enclosed within double quotes (" ") — is String.
The String data type does not widen to the Char Data Type (Visual Basic). This means that if you want to assign a literal to a
Char variable, you must either make a narrowing conversion or force the literal to the Char type.
To create a Char literal to assign to a variable or constant
1. Declare the variable or constant as Char.
2. Enclose the character value within double quotation marks (" ").
3. Follow the closing double quotation mark with the literal type character C to force the literal to Char. This is necessary if
the type checking switch (Option Strict Statement) is On, and it is desirable in any case.
The following example demonstrates both unsuccessful and successful assignments of a literal to a Char variable.
VB
Option Strict On
VB
Dim charVar As Char
' The following statement attempts to convert a String literal to Char.
' Because Option Strict is On, it generates a compiler error.
charVar = "Z"
' The following statement succeeds because it specifies a Char literal.
charVar = "Z"c
' The following statement succeeds because it converts String to Char.
charVar = CChar("Z")
There is always a risk in using narrowing conversions, because they can fail at run time. For example, a conversion from String
to Char can fail if the String value contains more than one character. Therefore, it is better programming to use the C type
character.
String Conversion Fails at Run Time
The String Data Type (Visual Basic) participates in very few widening conversions. String widens only to itself and Object, and
only Char and Char() (a Char array) widen to String. This is because String variables and constants can contain values that
other data types cannot accommodate.
When the type checking switch (Option Strict Statement) is On, the compiler disallows all implicit narrowing conversions,
including those involving String. Your code can still use conversion keywords such as CStr and CType Function, which direct
the .NET Framework to attempt the conversion.
Narrowing Conversion Protection
The disadvantage of narrowing conversions is that they can fail at run time. For example, if a String variable contains anything
other than "True" or "False", it cannot be converted to Boolean. If it contains punctuation characters, conversion to any
numeric type fails. Unless you know that your String variable always holds values that the destination type can accept, you
should not attempt a conversion.
If you need to convert from String to another data type, the safest procedure is to enclose the attempted conversion in the
Try...Catch...Finally Statement (Visual Basic). This allows you to deal with a run-time failure.
Character Arrays
A single Char and an array of Char elements both widen to String. However, String does not widen to Char(). To convert a
String value to a Char array, you can use the ToCharArray method of the System.String class.
Meaningless Values
In general, String values are not meaningful in other data types, and conversion is highly artificial and dangerous. Whenever
possible, you should restrict usage of String variables to the character sequences for which they are designed. You should
never write code that relies on equivalent values in other types.
See Also
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Data Types in Visual Basic
Type Characters
Typeless Programming in Visual Basic
Data Types Are .NET Framework Types
Efficient Use of Data Types
Other Resources
Data Type Implementation
Type Conversions in Visual Basic
Visual Basic Language Concepts
Note
The equal sign (=) in this example is an assignment operator, not an equality operator. The value is being assigned to the vari
able applesSold.
For more information, see How to: Move Data Into and Out of a Variable.
Variables and Properties
Like a variable, a property represents a value you can access. However, it is more complex than a variable. A property uses code
blocks that control how to set and retrieve its value. For more information, see
Differences Between Properties and Variables in Visual Basic.
See Also
Tasks
Troubleshooting Variables in Visual Basic
How to: Move Data Into and Out of a Variable
Concepts
Variable Declaration in Visual Basic
Object Variables in Visual Basic
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts
Dim i, j, k As Integer
' All three variables in the preceding statement are declared as Integer.
Dim l, m As Long, x, y As Single
' In the preceding statement, l and m are Long, x and y are Single.
For more information on data types, see Data Types in Visual Basic. For more information on objects, see
Object-Oriented Programming in Visual Basic and Programming with Components.
Declaring Characteristics
The lifetime of a variable is the period of time during which it is available for use. In general, a variable exists as long as the
element that declares it (such as a procedure or class) continues to exist. In some cases it is possible to extend a variable's
lifetime. For more information, see Lifetime in Visual Basic.
The scope of a variable is the set of all code that can refer to it without qualifying its name. A variable's scope is determined by
where it is declared. Code located in a given region can use the variables defined in that region without having to qualify their
names. For more information, see Scope in Visual Basic.
A variable's access level is the extent of code that has permission to access it. This is determined by the access modifier (such as
Public (Visual Basic) or Private (Visual Basic)) that you use in the Dim statement. For more information, see
Access Levels in Visual Basic.
See Also
Tasks
How to: Create a New Variable
How to: Create a Variable that Does Not Change in Value
How to: Move Data Into and Out of a Variable
Reference
Data Type Summary (Visual Basic)
Protected (Visual Basic)
Friend (Visual Basic)
Static (Visual Basic)
Concepts
Deciding What Type of Variable to Define
Declared Element Characteristics
Visual Basic Language Concepts
Dim newCustomer
2. Include specifications for the variable's characteristics, such as Private (Visual Basic), Static (Visual Basic), Shadows, or
WithEvents. For more information, see Declared Element Characteristics.
You do not need the Dim keyword if you use other keywords in the declaration.
3. Follow the specifications with the variable's name, which must follow Visual Basic rules and conventions. For more
information, see Declared Element Names.
4. Follow the name with the As clause to specify the variable's data type.
See Also
Concepts
Variables in Visual Basic
Variable Declaration in Visual Basic
Declared Element Names
Declared Element Characteristics
Value Types and Reference Types
Declaration Statements in Visual Basic
Visual Basic Language Concepts
You can specify ReadOnly only on a member variable. This means you must define the variable at module level, outside
of any procedure.
2. If you can compute the value in a single statement at compile time, use an initialization clause in the Dim statement.
Follow the As clause with an equal sign (=), followed by an expression. Be sure the compiler can evaluate this expression
to a constant value.
You can assign a value to a ReadOnly variable only once. Once you do so, no code can ever change its value.
If you do not know the value at compile time, or cannot compute it at compile time in a single statement, you can still
assign it at run time in a constructor. To do this, you must declare the ReadOnly variable at class or structure level. In the
constructor for that class or structure, compute the variable's fixed value, and assign it to the variable before returning
from the constructor.
See Also
Reference
WriteOnly
Const Statement (Visual Basic)
Visual Basic Language Concepts
The value generated on the right side of the assignment statement is stored in the variable.
Getting Data from a Variable
You retrieve a variable's value by including the variable name in an expression.
To retrieve a value from a variable
Use the variable name in an expression. You can use a variable anywhere you can use a constant or a literal, except in an
expression that defines the value of a constant.
-or-
Use the variable name following the equal (=) sign in an assignment statement.
The following example reads the value of the variable startValue and then uses the value of the variable counter in an
expression.
counter = startValue
cellValue = (counter + 5) ^ 2
The value of the variable participates in the expression just as a constant would, and then it is stored in the variable or
property on the left side of the assignment statement.
See Also
Concepts
Variables in Visual Basic
Variable Declaration in Visual Basic
Object Variables in Visual Basic
Visual Basic Language Concepts
You can shorten this code, and speed up execution, if you use an object variable for the control. You should declare the object
variable with the specific class that you intend to assign to it (Control in this case). Once you assign an object to the variable,
you can treat it exactly the same as you treat the object to which it refers. You can set or retrieve the properties of the object or
use any of its methods. The following example uses an object variable to simplify the code in the preceding example.
See Also
Tasks
How to: Speed Up Access to an Object with a Long Qualification Path
Concepts
Variable Declaration in Visual Basic
Object Variable Declaration
Object Variable Assignment
Object Variable Values
Visual Basic Language Concepts
ctrlActv.Text = "Test"
ctrlActv.Location = New Point(100, 100)
ctrlActv.Show()
With someForm.ActiveForm.ActiveControl
2. Access the object's members inside the With block, before the End With statement.
.Text = "Test"
.Location = New Point(100, 100)
.Show()
End With
See Also
Reference
With...End With Statement (Visual Basic)
Concepts
Object Variables in Visual Basic
Visual Basic Language Concepts
You can also specify Public (Visual Basic), Protected (Visual Basic), Friend (Visual Basic), Protected Friend,
Private (Visual Basic), Shared (Visual Basic), or Static (Visual Basic) in the declaration. The following example declarations are
valid:
' Option statements must precede all other source file lines.
Option Strict On
' Imports statement must precede all declarations in the source file.
Imports System.Windows.Forms
Public Sub accessMembers()
Dim p As Object
Dim q As System.Windows.Forms.Label
p = New System.Windows.Forms.Label
q = New System.Windows.Forms.Label
Dim j, k As Integer
' The following statement generates a compiler ERROR.
j = p.Left
' The following statement retrieves the left edge of the label in pixels.
k = q.Left
End Sub
In this example, p can use only the members of the Object class itself, which do not include the Left property. On the other
hand, q was declared to be of type Label, so it can use all the methods and properties of the Label class in the
System.Windows.Forms namespace.
Flexibility of Object Variables
When working with objects in an inheritance hierarchy, you have a choice of which class to use for declaring your object
variables. In making this choice, you must balance flexibility of object assignment against access to a class's members. For
example, consider the inheritance hierarchy that leads to the System.Windows.Forms.Form class:
Object
Component
Control
ScrollableControl
ContainerControl
Form
Suppose your application defines a form class called specialForm, which inherits from class Form. You can declare an object
variable that refers specifically to specialForm, as the following example shows.
The declaration in the preceding example limits the variable nextForm to objects of class specialForm, but it also makes all the
methods and properties of specialForm available to nextForm, as well as all the members of all the classes from which
specialForm inherits.
You can make an object variable more general by declaring it to be of type Form, as the following example shows.
The declaration in the preceding example allows you to assign any form in your application to anyForm. However, although
anyForm can access all the members of class Form, it cannot use any of the additional methods or properties defined for
specific forms such as specialForm.
All the members of a base class are available to derived classes, but the additional members of a derived class are not available
to the base class.
See Also
Tasks
How to: Declare an Object Variable and Assign an Object to It in Visual Basic
How to: Access Members of an Object
Reference
New (Visual Basic)
Option Strict Statement
Concepts
Object Variables in Visual Basic
Object Variable Assignment
Object Variable Values
Typeless Programming in Visual Basic
Visual Basic Language Concepts
currentText = newForm.Text
If the member is Shared (Visual Basic), you do not need a variable to access it. For more information, see
How to: Access Shared and Nonshared Members of an Object.
With Option Strict On, you can assign only Form objects (or objects of a type derived from Form) to extraForm. If you
have defined a class or structure with a widening CType conversion to Form, you can also assign that class or structure
to extraForm.
2. Use the member-access operator (.) between the object variable name and the member name.
extraForm.Show()
You can access all of the methods and properties specific to the Form class, no matter what the Option Strict setting is.
Accessing Members of an Object of Unknown Type
If you do not know the type of an object at compile time, you must use late binding for any variable that refers to it.
To access members of an object for which you do not know the type at compile time
1. Declare the object variable to be of the Object Data Type. (Declaring a variable as Object is the same as declaring it as
System.Object.)
With Option Strict On, you can access only the members that are defined on the Object class.
2. Use the member-access operator (.) between the object variable name and the member name.
someControl.GetType()
To be able to access the members of any object you assign to the object variable, you must set Option Strict Off. When
you do this, the compiler cannot guarantee that a given member is exposed by the object you assign to the variable. If the
object does not expose a member you attempt to access, a MemberAccessException exception occurs.
See Also
Reference
Object Data Type
Option Strict Statement
Object
Form
MemberAccessException
Concepts
Object Variables in Visual Basic
Object Variable Declaration
Visual Basic Language Concepts
Disassociation
Setting an object variable to Nothing discontinues the association of the variable with any specific object. This prevents you
from accidentally changing the object by changing the variable. It also allows you to test whether the object variable points to a
valid object, as the following example shows.
If the object your variable refers to is in another application, this test cannot determine whether that application has terminated
or just invalidated the object.
An object variable with a value of Nothing is also called a null reference.
Current Instance
The current instance of an object is the one in which the code is currently executing. Since all code executes inside a procedure,
the current instance is the one in which the procedure was invoked.
The Me keyword acts as an object variable referring to the current instance. If a procedure is not Shared (Visual Basic), it can
use the Me keyword to obtain a pointer to the current instance. Shared procedures cannot be associated with a specific
instance of a class.
Using Me is particularly useful for passing the current instance to a procedure in another module. For example, suppose you
have a number of XML documents and wish to add some standard text to all of them. The following example defines a
procedure to do this.
Every XML document object could then call the procedure and pass its current instance as an argument. The following example
demonstrates this.
addStandardText(Me)
See Also
Tasks
How to: Declare an Object Variable and Assign an Object to It in Visual Basic
How to: Make an Object Variable Not Refer to Any Instance
Concepts
Object Variables in Visual Basic
Object Variable Declaration
Object Variable Values
Visual Basic Language Concepts
You can combine the declaration and assignment by initializing the variable as part of its declaration. The following example is
equivalent to the preceding example.
Robust Programming
If your code tries to access a member of an object variable that has been set to Nothing, a NullReferenceException occurs. If
you set an object variable to Nothing frequently, or if it is possible the variable is not initialized, it is a good idea to enclose
member accesses in a Try...Catch...Finally block.
Security
If you use an object variable for objects that contain confidential or sensitive data, you can set the variable to Nothing when
you are not actively dealing with one of those objects. This reduces the chance of malicious code gaining access to the data.
See Also
Reference
Nothing (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
Troubleshooting Exceptions: System.NullReferenceException
NullReferenceException
Concepts
Object Variables in Visual Basic
Object Variable Assignment
Visual Basic Language Concepts
IsDate Function (Visual Basic) A Date Data Type (Visual Basic) value, or a string that can be interpreted as a date and time v
alue
IsDBNull Function An object of type DBNull, which represents missing or nonexistent data
IsNothing Function Nothing (Visual Basic), that is, no object is currently assigned to the variable
IsNumeric Function (Visual Basic) A number, or a string that can be interpreted as a number
IsReference Function A reference type (such as a string, array, delegate, or class type)
You can use these functions to avoid submitting an invalid value to an operation or a procedure.
TypeOf Operator
You can also use the TypeOf Operator (Visual Basic) to determine whether an object variable currently refers to a specific data
type. The TypeOf...Is expression evaluates to True if the run-time type of the operand is derived from or implements the
specified type.
The following example uses TypeOf on object variables referring to value and reference types.
' The following statement puts a value type (Integer) in an Object variable.
Dim num As Object = 10
' The following statement puts a reference type (Form) in an Object variable.
Dim frm As Object = New Form()
If TypeOf num Is Long Then Debug.WriteLine("num is Long")
If TypeOf num Is Integer Then Debug.WriteLine("num is Integer")
If TypeOf num Is Short Then Debug.WriteLine("num is Short")
If TypeOf num Is Object Then Debug.WriteLine("num is Object")
If TypeOf frm Is Form Then Debug.WriteLine("frm is Form")
If TypeOf frm Is Label Then Debug.WriteLine("frm is Label")
If TypeOf frm Is Object Then Debug.WriteLine("frm is Object")
The preceding example writes the following lines to the Debug window:
num is Integer
num is Object
frm is Form
frm is Object
The object variable num refers to data of type Integer, and frm refers to an object of class Form.
Object Arrays
You can declare and use an array of Object variables. This is useful when you need to handle a variety of data types and object
classes. All the elements in an array must have the same declared data type. Declaring this data type as Object allows you to
store objects and class instances alongside other data types in the array.
See Also
Tasks
How to: Refer to the Current Instance of an Object
How to: Determine What Type an Object Variable Refers To
How to: Determine Whether Two Objects Are Related
How to: Determine Whether Two Objects Are Identical
Reference
Is (Visual Basic)
Concepts
Object Variables in Visual Basic
Object Variable Declaration
Object Variable Assignment
Data Types in Visual Basic
Visual Basic Language Concepts
Me.ForeColor = System.Drawing.Color.Crimson
Me.Close()
Although Me behaves like an object variable, you cannot declare it or assign anything to it. Me always refers to the
current instance.
See Also
Reference
Me
Concepts
Object Variables in Visual Basic
Object Variable Assignment
Visual Basic Language Concepts
2. On the System.Type class, call the shared method GetTypeCode to retrieve the TypeCode enumeration value for the
object's type.
You can test the TypeCode enumeration value against whichever enumeration members are of interest, such as Double.
To determine whether an object variable's type is compatible with a specified type
Use the TypeOf operator in combination with the Is Operator (Visual Basic) to test the object with a TypeOf...Is
expression.
The TypeOf...Is expression returns True if the object's run-time type is compatible with the specified type.
The criterion for compatibility depends on whether the specified type is a class, structure, or interface. In general, the
types are compatible if the object is of the same type as, inherits from, or implements the specified type. For more
information, see TypeOf Operator (Visual Basic).
Compiling the Code
Note that the specified type cannot be a variable or expression. It must be the name of a defined type, such as a class, structure,
or interface. This includes intrinsic types such as Integer and String.
See Also
Reference
Object Data Type
GetType
System.Type
GetTypeCode
TypeCode
Concepts
Object Variables in Visual Basic
Object Variable Values
Visual Basic Language Concepts
Example
The following example determines whether one object represents a class derived from another object's class.
Note the unexpected placement of the two object variables in the call to IsInstanceOfType. The supposed base type is used to
generate the System.Type class, and the supposed derived type is passed as an argument to the IsInstanceOfType method.
See Also
Tasks
How to: Determine Whether Two Objects Are Identical
Reference
Object Data Type
GetType
System.Type
IsInstanceOfType
Concepts
Object Variables in Visual Basic
Object Variable Values
Visual Basic Language Concepts
See Also
Tasks
How to: Determine Whether Two Objects Are Related
Reference
Object Data Type
Is Operator (Visual Basic)
IsNot Operator
Concepts
Object Variables in Visual Basic
Object Variable Values
Visual Basic Language Concepts
VB
Dim p As Object = New System.Windows.Forms.Label
Dim q As System.Windows.Forms.Label = New System.Windows.Forms.Label
Dim j, k As Integer
' The following statement generates a compiler error.
j = p.Left
' The following statement retrieves the left edge of the label
' in pixels.
k = q.Left
In this example, p can use only the members of the Object class itself, which do not include the Left property. On the other
hand, q was declared to be of type Label, so it can use all the methods and properties of the Label class in the
System.Windows.Forms namespace.
Correct Approach
To be able to access all the members of an object of a particular class, declare the object variable to be of the type of that class
when possible. If you cannot do this, for example if you do not know the object type at compile time, you must set Option
Strict to Off and declare the variable to be of the Object Data Type. This allows objects of any type to be assigned to the
variable, and you should take steps to ensure that the currently assigned object is of an acceptable type. You can use the
TypeOf Operator (Visual Basic) to make this determination.
Other Components Cannot Access Your Variable
Visual Basic names are case-insensitive. If two names differ in alphabetic case only, the compiler interprets them as the same
name. For example, it considers ABC and abc to refer to the same declared element.
However, the common language runtime (CLR) uses case-sensitive binding. Therefore, when you produce an assembly or a
DLL and make it available to other assemblies, your names are no longer case-insensitive. For example, if you define a class
with an element called ABC, and other assemblies make use of your class through the common language runtime, they must
refer to the element as ABC. If you subsequently recompile your class and change the element's name to abc, the other
assemblies using your class can no longer access that element. Therefore, when you release an updated version of an
assembly, you should not change the alphabetic case of any public elements.
For more information, see Common Language Runtime.
Correct Approach
To allow other components to access your variables, treat their names as if they were case-sensitive. When you are testing
your class or module, make sure other assemblies are binding to the variables you expect them to. Once you have published a
component, do not make any modifications to existing variable names, including changing their cases.
Wrong Variable Being Used
When you have more than one variable with the same name, the Visual Basic compiler attempts to resolve each reference to
that name. If the variables have different scope, the compiler resolves a reference to the declaration with the narrowest scope.
If they have the same scope, the resolution fails and the compiler signals an error. For more information, see
Resolving a Reference When Multiple Variables Have the Same Name.
Correct Approach
Avoid using variables with the same name but different scope. If you are using other assemblies or projects, avoid using any
names defined in those external components as much as possible. If you have more than one variable with the same name, be
sure you qualify every reference to it. For more information, see
How to: Distinguish Between Two Elements with the Same Name.
See Also
Tasks
How to: Access Members of an Object
How to: Determine What Type an Object Variable Refers To
Concepts
Variables in Visual Basic
Variable Declaration in Visual Basic
Object Variables in Visual Basic
Object Variable Declaration
Object Variable Values
Resolving a Reference When Multiple Variables Have the Same Name
Declared Element Names
Visual Basic Language Concepts
The array students in the preceding example contains 7 elements. The indexes of the elements range from 0 through 6. Having
this array is simpler than declaring 7 different variables.
The following illustration shows the array students. For each element of the array:
The index of the element represents the grade (index 0 represents kindergarten).
The value contained in the element represents the number of students in that grade.
Elements of the "students" array
The following example shows how to refer to the first, second, and last element of the array students.
You can refer to the array as a whole by using just the array variable name without indexes.
Array Types and Other Types
Data Types
Every array has a data type, but it is not the same as the data type of its elements. For example, the array students in the
preceding example is of type Integer(), while each of its elements is of type Integer. The notation Integer() means an array of
Integer elements. For more information, see Array Data Types in Visual Basic.
Every array inherits from the System.Array class, and you can declare a variable to be of type Array, but you cannot create an
array of type Array. Also, the ReDim Statement (Visual Basic) cannot operate on a variable declared as type Array. For these
reasons, and for type safety, it is advisable to declare every array as a specific type, such as Integer in the preceding example.
Array Dimensions
The array students in the preceding example uses one index and is said to be one-dimensional. An array that uses more than
one index or subscript is called multidimensional.
Another kind of array is one which holds other arrays as elements. This is known as an array of arrays or a jagged array. A
jagged array can be either one-dimensional or multidimensional, and so can its elements.
Contrasting Types
In contrast to an array, a variable containing a single value is called a scalar variable.
An array is not the same as a collection. For more information, see Collections as an Alternative to Arrays.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Array Dimensions in Visual Basic
Multidimensional Arrays in Visual Basic
Jagged Arrays in Visual Basic
Array Data Types in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
The preceding example declares an array variable but does not assign an array to it. You still must create a one-
dimensional array, initialize it, and assign it to cargoWeights.
The preceding example declares an array variable but does not assign an array to it. You still must create a four-
dimensional array, initialize it, and assign it to atmospherePressures.
The preceding example declares an array variable but does not assign an array to it. You still must create an array of
arrays of arrays, initialize it, and assign it to inquiriesByYearMonthDay.
See Also
Tasks
How to: Create an Array
How to: Create an Array with More Than One Dimension
How to: Create an Array of Arrays
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Multidimensional Arrays in Visual Basic
Jagged Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
Following the execution of this statement, the array in variable validDates has length 0.
Note
The New clause must specify the type name, followed by parentheses, followed by braces, {}. The parentheses do not r
epresent a call to an array constructor. Instead, they indicate that the object type is an array type. The braces supply initi
alization values. The compiler requires the braces even if you are not supplying any values. Therefore, the New clause
must include both the parentheses and the braces, even if they are empty.
Following the execution of these statements, the array in variable scores has length 0.
-or-
Use the ReDim Statement (Visual Basic) to not only create an array but initialize its length.
ReDim scores(4)
Following the execution of this statement, the array in variable scores has length 5, with all the elements holding default
values.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array with More Than One Dimension
How to: Create an Array of Arrays
How to: Create an Array with Mixed Element Types
How to: Create an Array with No Elements
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
When you use the Object data type, keep in mind that the performance is not as efficient as when you use a more
specific data type. This is because the runtime has to convert the data between its natural data type and Object, using
operations called boxing and unboxing. This additional processing can hurt your performance if you do it often.
To retrieve information of different data types from an Object array, you can convert an element to the appropriate data
type, as the following example illustrates.
In a situation where the elements are not similar or related to each other, another possibility is to put them in a collection
instead of an Object array. For more information, see Collections as an Alternative to Arrays.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Create an Array with More Than One Dimension
How to: Create an Array of Arrays
How to: Create an Array with No Elements
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Collections as an Alternative to Arrays
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
Following the execution of this statement, the array in variable twoDimensionalStrings is two-dimensional with length 0.
It is empty, but it nonetheless exists. Therefore, a variable pointing to the array is not equal to Nothing. Subsequently,
you can create a nonempty array and assign it to twoDimensionalStrings.
In contrast, the following example declares an array variable that does not initially point to any array.
Unlike twoDimensionalStrings in the earlier example, the variable twoDimStrings has the value Nothing.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Create an Array with More Than One Dimension
How to: Create an Array of Arrays
How to: Create an Array with Mixed Element Types
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
Following the execution of this statement, the array in variable testChars has length 3, with elements at index 0 through
index 2 holding initialized values. If you supply both the upper bound and the values, you must include a value for every
element from index 0 through the upper bound.
Note the literal type character c, which forces a character literal to the Char data type. Without any type character, a
literal enclosed within double quotes (" ") defaults to String.
You do not need to specify the index upper bound if you supply element values in the New clause. The following
example declares, creates, and initializes a variable to hold an array with elements of the
Boolean Data Type (Visual Basic), specifying only the element values.
Following the execution of this statement, the array in variable answers has length 4, with elements at indexes 0 through
3 holding initialized values.
You can initialize the index upper bound without initializing any elements. If you create an array in this way, you must use a
subsequent assignment statement to initialize each element value.
To initialize an array in subsequent assignment statements
1. Specify the index upper bound in the array variable declaration.
2. Use one or more assignment statements, each of which assigns a value to one of the array's elements. The following
example declares and creates a variable to hold an array with elements of the String Data Type (Visual Basic), and
supplies two element values in subsequent statements.
Following the execution of these statements, the array in variable comments has length 31, with elements at indexes 0 and
5 holding initialized values, and the other 29 elements holding default values. If you initialize an array in this way, you
can initialize some elements and skip over others.
-or-
Use the ReDim Statement (Visual Basic) to initialize the array's length.
ReDim comments(5)
Following the execution of this statement, the array in variable comments has length 6, with all the elements holding
default values.
Note
You can initialize the index upper bound in only one place. If you specify an upper bound in the parentheses following t
he array variable name, you cannot use a New clause. If you specify the upper bound in the parentheses in the New cl
ause, you must leave the parentheses following the variable name empty.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize a Multidimensional Array
How to: Initialize a Jagged Array
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
Two-dimensional array
Three-dimensional array
One Dimension
Many arrays have only one dimension, such as the number of people of each age. The only requirement to specify an element
is the age for which that element holds the count. Therefore, such an array uses only one index. The following example declares
a variable to hold a one-dimensional array of age counts for ages 0 through 120.
Two Dimensions
Some arrays have two dimensions, such as the number of offices on each floor of each building on a campus. The specification
of an element requires both the building number and the floor, and each element holds the count for that combination of
building and floor. Therefore, such an array uses two indexes. The following example declares a variable to hold a two-
dimensional array of office counts, for buildings 0 through 40 and floors 0 through 5.
Now suppose you want to track the same information not only for every day of a month but also for every month of the year.
You might declare a two-dimensional array with 12 rows (for the months) and 31 columns (for the days), as the following
example shows.
Now suppose you decide to have your array hold information for more than one year. If you want to track sales amounts for 5
years, you could declare a three-dimensional array with 5 layers, 12 rows, and 31 columns, as the following example shows.
Note that, because each index varies from 0 to its maximum, each dimension of salesAmounts is declared as one less than the
required length for that dimension. Note also that the size of the array increases with each new dimension. The three sizes in
the preceding examples are 31, 372, and 1,860 elements respectively.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Multidimensional Arrays in Visual Basic
Jagged Arrays in Visual Basic
Array Data Types in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
The lower bound must always be 0, but your code can be more readable when you explicitly declare it. Specifying both bounds
also reminds the reader that the lower bound is 0.
Alternative Array Creation. You can create an array without using the Dim Statement (Visual Basic) or the New (Visual Basic)
clause. For example, you can call the CreateInstance method, or another component can pass your code an array created in this
manner. Such an array can have lower bounds other than 0. You can always test for the lower bound of a dimension with the
GetLowerBound method or the LBound Function (Visual Basic).
See Also
Tasks
Troubleshooting Arrays
Concepts
Array Dimensions in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
The total number of elements is the product of the lengths of all the dimensions. In the preceding example, populations has a
total of 804 elements (201 x 4), and matrix has 1056 elements (6 x 16 x 11). Each index ranges from 0 through the length
specified for its dimension.
A two-dimensional array is also called a rectangular array.
Note
When you add dimensions to an array, the total storage needed by the array increases considerably, so use multidimensional
arrays with care.
Following the execution of this statement, the array in variable weights has length 0.
Note
When you add dimensions to an array, the total storage needed by the array increases considerably, so use multidimen
sional arrays with care.
A multidimensional array is not the same as a jagged array. For more information, see How to: Create an Array of Arrays.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Create an Array with Mixed Element Types
How to: Create an Array with No Elements
How to: Initialize a Multidimensional Array
Troubleshooting Arrays
Reference
For...Next Statement (Visual Basic)
Concepts
Multidimensional Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
Following the execution of this statement, the array in variable sizes has a total of four elements, at indexes (0, 0), (0, 1),
(1, 0), and (1, 1), holding default values. If you create an array in this way, you must use a subsequent assignment
statement to assign each element value.
-or-
Follow the declaration with an equal sign (=) and a New (Visual Basic) clause. In the New clause, repeat the element data
type, specify the index upper bounds inside parentheses, and supply empty braces ({}). The following example declares
and creates a variable to hold a three-dimensional array with elements of the Short data type, specifying only the upper
bounds.
Following the execution of this statement, the array in variable replyCounts has 18 elements holding default values. If
you create an array in this way, you must use a subsequent assignment statement to assign each element value.
Note
You can initialize the index upper bounds in only one place. If you specify upper bounds in the parentheses following th
e array variable name, you cannot use a New clause. If you specify upper bounds in the parentheses in the New clause,
you must leave the parentheses following the variable name empty.
-or-
In the New clause, specify each index upper bound inside the parentheses, and supply the element values inside the
braces ({}). The following example declares, creates, and initializes a variable to hold a two-dimensional array with
elements of the Short data type, specifying the upper bounds and the values. Note the two levels of braces in the New
clause.
Following the execution of this statement, the array in variable startingScores holds four initialized elements. If you
supply both the upper bounds and the values, you must include a value for every element from index 0 through the
upper bound in every dimension.
-or-
In the New clause, leave the parentheses empty except for commas for the appropriate number of dimensions, and
supply the element values inside the braces ({}). The following example declares, creates, and initializes a variable to hold
a two-dimensional array with elements of the Single Data Type (Visual Basic), specifying only the element values. Note
the two levels of braces in the New clause.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array with More Than One Dimension
How to: Initialize an Array Variable
How to: Initialize a Jagged Array
Troubleshooting Arrays
Concepts
Multidimensional Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
The New clause in the declaration of sales sets the array variable to a 12-element array, each element of which is of type
Double(), an array of Double elements. The For loop then determines how many days are in each month this year
(Year(Now)), and sets the corresponding element of sales to a Double array of the appropriate size.
In the preceding example, the jagged array saves seven elements (six in a leap year) compared to a two-dimensional array. In a
more extreme case the memory savings could be significant.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array of Arrays
How to: Initialize a Jagged Array
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Array Dimensions in Visual Basic
Multidimensional Arrays in Visual Basic
Array Data Types in Visual Basic
Writing CLS-Compliant Code
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
Following the execution of this statement, the array in variable ratings has length 0.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Create an Array with More Than One Dimension
How to: Create an Array with Mixed Element Types
How to: Create an Array with No Elements
How to: Initialize a Jagged Array
Troubleshooting Arrays
Concepts
Jagged Arrays in Visual Basic
Writing CLS-Compliant Code
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
Following the execution of this statement, the array in variable rainfall holds 12 elements, each of which is an empty
array of Byte elements.
-or-
In the New clause, specify the top-level index upper bound inside the first pair of parentheses, and supply empty braces
({}). The following example declares and creates a variable to hold a jagged array of Short elements, specifying only the
top-level upper bound.
Following the execution of this statement, the array in variable snowfall holds 12 elements, each of which is an empty
array of Short elements.
Note
You can initialize the top-level index upper bound in only one place. If you specify an upper bound in the parentheses f
ollowing the array variable name, you cannot use a New clause. If you specify the upper bound in the parentheses in th
e New clause, you must leave the parentheses following the variable name empty.
-or-
In the New clause, specify the top-level index upper bound inside the parentheses, and supply the element values inside
the braces ({}). The following example declares, creates, and initializes a variable to hold a jagged array of Char elements,
specifying the top-level upper bound and the values. Note the nested New clauses to initialize the bottom-level arrays.
Dim decodeValues()() As Char = New Char(1)() {New Char() {"a"c, "b"c}, New Char() {"p"
c, "q"c}}
Following the execution of this statement, the array in variable decodeValues holds two elements, each of which is a Char
array of length 1 with the element at index 0 holding an initialized value. If you supply both the top-level upper bound
and the values, you must include a value for every top-level element from index 0 through the upper bound.
-or-
In the New clause, omit the top-level parentheses and supply the element values inside the braces ({}). The following
example declares, creates, and initializes a variable to hold a jagged array of Byte elements, specifying only the element
values. Note the two levels of braces in the New clause.
Dim firstValues()() As Byte = {New Byte() {2, 1}, New Byte() {3, 0}}
Following the execution of this statement, the array in variable firstValues has length 2, with elements firstValues(0)
and firstValues(1). Each of the elements is initialized to a two-element Byte array, the first with element values 2 and 1
and the second with element values 3 and 0.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array of Arrays
How to: Initialize an Array Variable
How to: Initialize a Multidimensional Array
Troubleshooting Arrays
Reference
New (Visual Basic)
Concepts
Jagged Arrays in Visual Basic
Writing CLS-Compliant Code
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
Following the execution of the preceding statements, the following data type relationships apply to the array variables:
Variables firstArray and secondArray are not of the same data type because they have different ranks.
Variables firstArray and thirdArray are not of the same data type because they have different element data types.
Variables firstArray and fourthArray are of the same data type, and you can assign one to the other.
Jagged Array Data Types
Arrays of arrays, that is, arrays that contain other arrays as elements, are also known as jagged arrays because the lengths of
the element arrays are not necessarily equal. The following example declares two jagged array variables, which have different
data types.
The array in twoDimOfOneDim is two-dimensional, and its element data type is Integer(), or one-dimensional Integer arrays.
The array in oneDimOfTwoDim is one-dimensional, and its element data type is Integer(,), or two-dimensional Integer arrays.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Determine the Data Type of an Array
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Array Dimensions in Visual Basic
Multidimensional Arrays in Visual Basic
Jagged Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
The MsgBox call displays "Type of thisTwoDimArray is Integer(,)", which shows you both the element type and the
number of dimensions. It does not display the current lengths of the dimensions, because they are not part of an array's
data type.
To determine the data type of an array element
Select an existing element and call TypeName on that element.
When you ReDim an array, the existing values of its elements are normally lost. However, you can retain them by including the
Preserve keyword in the ReDim statement.
To resize an array variable preserving existing element values
1. Specify the new dimension lengths for the array variable in the ReDim statement.
2. Add the Preserve keyword in the ReDim statement. The following example creates a new array, initializes its elements
from the corresponding elements of the existing array in arrayToIncrease, and assigns the new array to the array
variable arrayToIncrease.
If you use Preserve on a multidimensional array, you can change only the last dimension length. If you attempt to change any
of the other dimensions, an ArrayTypeMismatchException exception occurs.
If you resize a large array using the Preserve keyword, keep in mind that Visual Basic must copy all the existing elements into
the new array. This can make your performance slower.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Determine the Size of an Array
How to: Determine the Length of One Dimension of an Array
How to: Assign One Array to Another Array
How to: Change an Array to a Different Array
Troubleshooting Arrays
Concepts
Array Size in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
numbers(i + 1) = 0
matrix(3, j * 2) = j
For each array dimension, the GetUpperBound method returns the highest value the index can have. The lowest index
value is always 0.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Get a Value from an Array
How to: Locate an Element in an Array in Visual Basic
How to: Reverse the Contents of An Array in Visual Basic
How to: Sort An Array in Visual Basic
Troubleshooting Arrays
Concepts
Array Dimensions in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
For each array dimension, the GetUpperBound method returns the highest value the index can have. The lowest index value is
always 0.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Put a Value into an Array
How to: Locate an Element in an Array in Visual Basic
How to: Reverse the Contents of An Array in Visual Basic
How to: Sort An Array in Visual Basic
Troubleshooting Arrays
Concepts
Array Dimensions in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
When you assign one array to another, the following rules apply:
Equal Ranks. The rank (number of dimensions) of the destination array must be the same as that of the source array.
Provided the ranks of the two arrays are equal, the dimensions do not need to be equal. The number of elements in a
given dimension can change during assignment.
Element Types. Either both arrays must have reference type elements or both arrays must have value type elements.
For more information, see Value Types and Reference Types.
If both arrays have value type elements, the element data types must be exactly the same. The only exception to
this is that you can assign an array of Enum elements to an array of the base type of that Enum.
If both arrays have reference type elements, the source element type must derive from the destination element
type. When this is the case, the two arrays have the same inheritance relationship as their elements. This is called
array covariance.
The compiler reports an error if the above rules are violated, for example if the data types are not compatible or the ranks are
unequal. You can add error handling to your code to make sure that the arrays are compatible before attempting an
assignment. You can also use the TryCast keyword if you want to avoid throwing an exception.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Change the Size of an Array
How to: Change an Array to a Different Array
How to: Pass an Array to a Procedure or Property
How to: Return an Array from a Procedure or Property
Troubleshooting Arrays
Reference
Enum Statement (Visual Basic)
Concepts
Array Conversions
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
You can change an array variable to point to an array object with different dimension lengths, but you cannot change it to
point to an array object of a different data type. This means that the rank and the element data type must remain the same,
because they are inherently part of the array variable's data type.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Assign One Array to Another Array
How to: Pass an Array to a Procedure or Property
How to: Return an Array from a Procedure or Property
How to: Change the Size of an Array
Troubleshooting Arrays
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Assign One Array to Another Array
How to: Change an Array to a Different Array
How to: Return an Array from a Procedure or Property
Troubleshooting Arrays
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Assign One Array to Another Array
How to: Change an Array to a Different Array
How to: Pass an Array to a Procedure or Property
Troubleshooting Arrays
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
The declaration of the custFile collection specifies that it can contain elements only of type customer. It also provides for an
initial capacity of 200 elements. The procedure addNewCustomer checks the new element for validity and then adds it to the
collection. The procedure printCustomers uses a For Each loop to traverse the collection and display its elements.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
Troubleshooting Arrays
Reference
ReDim Statement (Visual Basic)
Concepts
Collections in Visual Basic
Generic Types in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
Troubleshooting Arrays
This page lists some common problems that can occur when working with arrays.
Compilation Errors Declaring and Initializing an Array
Compilation errors can arise from misunderstanding of the rules for declaring, creating, and initializing arrays. The most
common causes of errors are the following:
Supplying a New (Visual Basic) clause after specifying dimension lengths in the array variable declaration. The following
code lines show invalid declarations of this type.
Dim INVALIDsingleDimByteArray(2) As Byte = New Byte()
Specifying dimension lengths for more than the top-level array of a jagged array. The following code line shows an
invalid declaration of this type.
Dim INVALIDjaggedByteArray(1)(1) As Byte
Omitting the New keyword when specifying the element values. The following code line shows an invalid declaration of
this type.
Dim INVALIDoneDimShortArray() As Short = Short() {0, 1, 2, 3}
Supplying a New clause without braces ({}). The following code lines show invalid declarations of this type.
Dim INVALIDsingleDimByteArray() As Byte = New Byte()
3. Add the New (Visual Basic) keyword to initialize the variable to a new instance of the class.
4. You can now access the members of the class through the object variable.
nextCustomer.accountNumber = lastAccountNumber + 1
Robust Programming
Whenever possible, you should declare the variable to be of the class type you intend to assign to it. This is called early
binding. If you do not know the class type at compile time, you can invoke late binding by declaring the variable to be of the
Object Data Type. However, late binding can make performance slower and limit access to the run-time object's members. For
more information, see Object Variable Declaration.
See Also
Tasks
How to: Reuse a Working Component
How to: Define a Class That Uses Members of an Existing Class
How to: Access Shared and Nonshared Members of an Object
Concepts
Objects and Classes
Visual Basic Language Concepts
The first Dim Statement (Visual Basic) declares an object variable of type TimeZone and assigns to it a TimeZone object
returned by the CurrentTimeZone property.
See Also
Tasks
How to: Create an Object
How to: Define a Class That Uses Members of an Existing Class
How to: Access Shared and Nonshared Members of an Object
Concepts
Objects and Classes
Visual Basic Language Concepts
Be sure an End Class statement follows the last line of code in your class. By default, the integrated development
environment (IDE) automatically generates an End Class when you enter a Class statement.
2. Follow the Class statement immediately with an Inherits Statement. Specify the class from which your new class derives.
Inherits System.Windows.Forms.Button
Your new class inherits all the members defined by the base class.
3. Add the code for the additional members your derived class exposes. For example, you might add a reverseColors
method, and your derived class might look as follows:
If you create an object from the reversibleButton class, it can access all the members of the Button class, as well as the
reverseColors method and any other new members you define on reversibleButton.
Object Members
Objects are the basic units of object-oriented programming. An object is an element of an application, representing an instance
of a class. Fields, properties, methods, and events are the building blocks of objects and constitute their members.
Objects
An object represents an instance of a class, such as Form or Label. You must create an object before you can access its
nonshared members. To do this, you use the New keyword to specify the class from which to create the object, and then assign
the new object to an object variable.
2. In the statement that accesses the member, follow the object variable name with the member-access operator (.) and
then the member name.
secondForm.Show()
If you have already created an object from the class, you can alternatively access a Shared member through the object's
variable.
See Also
Tasks
How to: Create an Object
How to: Reuse a Working Component
How to: Define a Class That Uses Members of an Existing Class
How to: Access Members of an Object
Concepts
Object Members
Visual Basic Language Concepts
A String variable can also accept any expression that evaluates to a string. Examples are shown below:
VB
Dim OneString As String
Dim TwoString As String
OneString = "one, two, three, four, five"
' Evaluates to "two".
TwoString = OneString.Substring(5, 3)
OneString = "1"
' Evaluates to "11".
TwoString = OneString & "1"
Any literal that is assigned to a String variable must be enclosed in quotation marks (""). This means that a quotation mark
within a string cannot be represented by a quotation mark. For example, the following code causes a compiler error:
VB
Dim myString As String
This code causes an error because the compiler terminates the string after the second quotation mark, and the remainder of
the string is interpreted as code. To solve this problem, Visual Basic interprets two quotation marks in a string literal as one
quotation mark in the string. The following example demonstrates the correct way to include a quotation mark in a string:
VB
' The value of myString is: He said, "Look at this example!"
myString = "He said, ""Look at this example!"""
In the preceding example, the two quotation marks preceding the word Look become one quotation mark in the string. The
three quotation marks at the end of the line represent one quotation mark in the string and the string termination character.
Characters in Strings
A string can be thought of as a series of Char values, and the String type has built-in functions that allow you to perform
many manipulations on a string that resemble the manipulations allowed by arrays. Like all array in .NET Framework, these are
zero-based arrays. You may refer to a specific character in a string through the Chars property, which provides a way to access
a character by the position in which it appears in the string. For example:
VB
Dim myString As String = "ABCDE"
Dim myChar As Char
' The value of myChar is "C".
myChar = myString.Chars(3)
In the above example, the Chars property of the string returns the fourth character in the string, which is D, and assigns it to
myChar. You can also get the length of a particular string through the Length property. If you need to perform multiple array-
type manipulations on a string, you can convert it to an array of Char instances using the ToCharArray function of the string.
For example:
VB
Dim myString As String = "abcdefghijklmnop"
Dim myArray As Char() = myString.ToCharArray
The variable myArray now contains an array of Char values, each representing a character from myString.
The Immutability of Strings
A string is immutable, which means its value cannot be changed once it has been created. However, this does not prevent you
from assigning more than one value to a string variable. Consider the following example:
VB
Dim myString As String = "This string is immutable"
myString = "Or is it?"
Here, a string variable is created, given a value, and then its value is changed.
More specifically, in the first line, an instance of type String is created and given the value This string is immutable. In the
second line of the example, a new instance is created and given the value Or is it?, and the string variable discards its
reference to the first instance and stores a reference to the new instance.
Unlike other intrinsic data types, String is a reference type. When a variable of reference type is passed as an argument to a
function or subroutine, a reference to the memory address where the data is stored is passed instead of the actual value of the
string. So in the previous example, the name of the variable remains the same, but it points to a new and different instance of
the String class, which holds the new value.
See Also
Reference
String Data Type (Visual Basic)
Char Data Type (Visual Basic)
Other Resources
Introduction to Strings in Visual Basic
Basic String Operations
Visual Basic Language Concepts
In this example, the Mid function performs a direct operation on aString and assigns the value to bString.
Shared Methods and Instance Methods
You can also manipulate strings with the methods of the String class. There are two types of methods in String: shared
methods and instance methods.
Shared Methods
A shared method is a method that stems from the String class itself and does not require an instance of that class to work.
These methods can be qualified with the name of the class (String) rather than with an instance of the String class. For
example:
VB
Dim aString As String = String.Copy("A literal string")
In the preceding example, the System.String.Copy(System.String) method is a static method, which acts upon an expression it
is given and assigns the resulting value to bString.
Instance Methods
Instance methods, by contrast, stem from a particular instance of String and must be qualified with the instance name. For
example:
VB
Dim aString As String = "A String"
Dim bString As String
' Assign "String" to bString.
bString = aString.Substring(2, 6)
In this example, the System.String.Substring(System.Int32) method is a method of the instance of String (that is, aString). It
performs an operation on aString and assigns that value to bString.
See Also
Other Resources
Introduction to Strings in Visual Basic
Visual Basic Language Concepts
The Visual Basic runtime usually evaluates Nothing as an empty string (""). The .NET Framework does not, however, and
throws an exception whenever an attempt is made to perform a string operation on Nothing.
See Also
Other Resources
Introduction to Strings in Visual Basic
Visual Basic Language Concepts
Note
Date literals are always interpreted according to the English culture.
Comparing Strings
There are two important situations where string comparisons are needed:
Sorting data for display to the user. Use operations based on the current culture so the strings sort appropriately.
Determining if two application-internal strings exactly match (typically for security purposes). Use operations
that disregard the current culture.
You can perform both types of comparisons with the Visual Basic StrComp function. Specify the optional Compare argument
to control the type of comparison: Text for most input and output, Binary for determining exact matches.
The StrComp function returns an integer that indicates the relationship between the two compared strings based on the
sorting order. A positive value for the result indicates that the first string is greater than the second string. A negative result
indicates the first string is smaller, and zero indicates equality between the strings.
VB
' Defines variables.
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)
You can also use the .NET Framework partner of the StrComp function, the
System.String.Compare(System.String,System.String) method. This is a static, overloaded method of the base string class. The
following example illustrates how this method is used:
VB
Dim myString As String = "Alphabetical"
Dim secondString As String = "Order"
Dim result As Integer
result = String.Compare(myString, secondString)
For finer control over how the comparisons are performed, you can use additional overloads of the Compare method. With
the System.String.Compare(System.String,System.String,System.StringComparison) method, you can use the comparisonType
argument to specify which type of comparison to use.
Value for comparisonTyp Type of comparison When to use
e argument
Ordinal Comparison based on strings' component bytes. Use this value when comparing: case-sensitive
identifiers, security-related settings, or other n
on-linguistic identifiers where the bytes must
match exactly.
OrdinalIgnoreCase Comparison based on strings' component bytes. Use this value when comparing: case-insensiti
ve identifiers, security-related settings, and dat
OrdinalIgnoreCase uses the invariant culture info a stored in Windows.
rmation to determine when two characters differ o
nly in capitalization.
CurrentCulture or Comparison based on the strings' interpretation in Use these values when comparing: data that is
CurrentCultureIgnoreCase the current culture. displayed to the user, most user input, and oth
er data that requires linguistic interpretation.
InvariantCulture or Comparison based on the strings' interpretation in Use these values only when comparing persisti
InvariantCultureIgnoreCase the invariant culture. ng data or displaying linguistically-relevant dat
a that requires a fixed sort order.
This is different than the Ordinal and OrdinalIgn
oreCase, because the invariant culture treats chara
cters outside its accepted range as equivalent invar
iant characters.
Security Considerations
If your application makes security decisions based on the result of a comparison or case-change operation, then the operation
should use the System.String.Compare(System.String,System.String,System.StringComparison) method, and pass
Ordinal or OrdinalIgnoreCase for the comparisonType argument.
See Also
Reference
Type Conversion Functions
CultureInfo
Other Resources
Introduction to Strings in Visual Basic
Visual Basic Language Concepts
See Also
Reference
&= Operator (Visual Basic)
Concepts
Using the StringBuilder Class
Creating New Strings
Strings Sample
Other Resources
Strings in Visual Basic
Manipulating Strings
Building Strings in Visual Basic
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Data Types -
defined by Visual Basic. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
An Imports statement specifying the System namespace. For more information, see Imports Statement.
See Also
Concepts
Converting Strings to .NET Framework Data Types
Creating New Strings
Strings Sample
Other Resources
Strings in Visual Basic
Parsing Strings
Manipulating Strings
Building Strings in Visual Basic
Visual Basic Language Concepts
Return System.Text.Encoding.Unicode.GetString(bytes)
End Function
You can choose from several encoding options to convert a byte array into a string:
System.Text.Encoding.ASCII: Gets an encoding for the ASCII (7-bit) character set.
System.Text.Encoding.BigEndianUnicode: Gets an encoding for the UTF-16 format using the big-endian byte order.
System.Text.Encoding.Default: Gets an encoding for the system's current ANSI code page.
System.Text.Encoding.Unicode: Gets an encoding for the UTF-16 format using the little-endian byte order.
System.Text.Encoding.UTF32: Gets an encoding for the UTF-32 format using the little-endian byte order.
System.Text.Encoding.UTF7: Gets an encoding for the UTF-7 format.
System.Text.Encoding.UTF8: Gets an encoding for the UTF-8 format.
See Also
Tasks
How to: Convert Strings into an Array of Bytes in Visual Basic
Reference
System.Text.Encoding
GetString
Visual Basic Language Concepts
Return System.Text.Encoding.Unicode.GetBytes(str)
End Function
You can choose from several encoding options to convert a string into a byte array:
System.Text.Encoding.ASCII: Gets an encoding for the ASCII (7-bit) character set.
System.Text.Encoding.BigEndianUnicode: Gets an encoding for the UTF-16 format using the big-endian byte order.
System.Text.Encoding.Default: Gets an encoding for the system's current ANSI code page.
System.Text.Encoding.Unicode: Gets an encoding for the UTF-16 format using the little-endian byte order.
System.Text.Encoding.UTF32: Gets an encoding for the UTF-32 format using the little-endian byte order.
System.Text.Encoding.UTF7: Gets an encoding for the UTF-7 format.
System.Text.Encoding.UTF8: Gets an encoding for the UTF-8 format.
See Also
Tasks
How to: Convert an Array of Bytes into a String in Visual Basic
Reference
System.Text.Encoding
GetBytes
Visual Basic Language Concepts
See Also
Reference
Hex Function (Visual Basic)
ToInt32
Visual Basic Language Concepts
It is more difficult to split a string into its Unicode text characters, but this is necessary if you need information about the visual
representation of a string. This example uses the SubstringByTextElements method to get information about the Unicode text
characters that make up a string.
VB
' This string is made up of a surrogate pair (high surrogate
' U+D800 and low surrogate U+DC00) and a combining character
' sequence (the letter "a" with the combining grave accent).
Dim testString2 As String = ChrW(&HD800) & ChrW(&HDC00) & "a" & ChrW(&H300)
See Also
Tasks
How to: Access Characters in Strings in Visual Basic
Reference
Chars
System.Globalization.StringInfo
Other Resources
Converting Between Strings and Other Data Types in Visual Basic
Strings in Visual Basic
Visual Basic Language Concepts
4. Add a private method that creates a byte array of a specified length from the hash of the specified key.
VB
Private Function TruncateHash( _
ByVal key As String, _
ByVal length As Integer) _
As Byte()
' Use the crypto stream to write the byte array to the stream.
encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
encStream.FlushFinalBlock()
' Use the crypto stream to write the byte array to the stream.
decStream.Write(encryptedBytes, 0, encryptedBytes.Length)
decStream.FlushFinalBlock()
The wrapper class can now be used to protect user assets. In this example, it is used to securely store private user data in
a publicly accessible text file.
To test the encryption wrapper
1. In a separate class, add a method that uses the wrapper's EncryptData method to encrypt a string and write it to the
user's My Documents folder.
VB
Sub TestEncoding()
Dim plainText As String = InputBox("Enter the plain text:")
Dim password As String = InputBox("Enter the password:")
2. Add a method that reads the encrypted string from the user's My Documents folder and decrypts the string with the
wrapper's DecryptData method.
VB
Sub TestDecoding()
Dim cipherText As String = My.Computer.FileSystem.ReadAllText( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments & _
"\cipherText.txt")
Dim password As String = InputBox("Enter the password:")
Dim wrapper As New Simple3Des(password)
3. Add user interface code to call the TestEncoding and TestDecoding methods.
4. Run the application.
When you test the application, notice that it will not decrypt the data if you provide the wrong password.
See Also
Reference
System.Security.Cryptography
DESCryptoServiceProvider
DES
TripleDES
Rijndael
Concepts
Cryptography Overview
Other Resources
Walkthroughs For Strings in Visual Basic
Visual Basic Language Concepts
This example does not check if the name has incorrectly placed colons, or directories with no name, or if the length of the name
exceeds the system-defined maximum length. It also does not check if the application has permission to access the file-system
resource with the specified name.
See Also
Reference
GetInvalidPathChars
Other Resources
Validating Strings in Visual Basic
Visual Basic Language Concepts
# Digit or space. Entry optional. If this position is left blank in the mask, it will be rendered as [ \d+-]?
a space. Plus (+) and minus (-) signs are allowed.
\ Escapes a mask character, turning it into a literal. “\\” is the escape sequence for a backslash \
.
All other cha Literals. All non-mask elements will appear as themselves within MaskedTextBox. All other characters.
racters.
The decimal (.), thousandths (,), time (:), date (/), and currency ($) symbols default to displaying those symbols as defined by the
application's culture. You can force them to display symbols for another culture by using the FormatProvider property.
Regular Expressions and Masks
Although you can use regular expressions and masks to validate user input, they are not completely equivalent. Regular
expressions can express more complex patterns than masks, but masks can express the same information more succinctly and
in a culturally relevant format.
The following table compares four regular expressions and the equivalent mask for each.
Regular Exp Mask Notes
ression
\d{2}/\d{2} 00/00/ The / character in the mask is a logical date separator, and it will appear to the user as the date separator
/\d{4} 0000
appropriate to the application's current culture.
\d{2}-[A-Z] 00->L< A date (day, month abbreviation, and year) in United States format in which the three-letter month abbre
[a-z]{2}-\d LL-000
{4} 0 viation is displayed with an initial uppercase letter followed by two lowercase letters.
(\(\d{3}\)- (999)- United States phone number, area code optional. If the user does not wish to enter the optional character
)?\d{3}-d{4 000-00
} 00 s, she can either enter spaces or place the mouse pointer directly at the position in the mask represented
by the first 0.
$\d{6}.00 $999,9 A currency value in the range of 0 to 999999. The currency, thousandth, and decimal characters will be r
99.00
eplaced at run-time with their culture-specific equivalents.
See Also
Reference
Mask
MaskedTextBox
Other Resources
Validating Strings in Visual Basic
MaskedTextBox Control (Windows Forms)
Visual Basic Language Concepts
To match any single character in charlist, use [charlist]. To match any single character in charlist, use [charlist].
To match any single character not in charlist, use [!charlist]. To match any single character not in charlist, use [^ch
arlist].
To match any single digit (0–9), use #. To match any single digit (0–9), use the character class
for decimal digits, \d.
To match any single character, use ?. To match any single character, specify mutually exclusi
ve character classes for the charlist in [charlist]. For ex
ample, [\s\S].
To match zero or more characters, use *. To match zero or more characters, specify mutually exc
lusive character classes for the charlist in [charlist]*. Fo
r example, [\s\S]*.
To match a special character char, enclose it in brackets: [char]. To match a special character char, precede it with a bac
kslash: \char.
To match any character in a range, use a hyphen (–) to separate the lo To match any character in a range, use a hyphen (–) to
wer and upper bounds of the range in a charlist. separate the lower and upper bounds of the range in a
charlist.
See Also
Reference
Like Operator
Other Resources
Validating Strings in Visual Basic
.NET Framework Regular Expressions
Visual Basic Language Concepts
' Replace [A-Z] with \p{Lu}, to allow for Unicode uppercase letters.
Dim upper As New System.Text.RegularExpressions.Regex("[A-Z]")
Dim lower As New System.Text.RegularExpressions.Regex("[a-z]")
Dim number As New System.Text.RegularExpressions.Regex("[0-9]")
' Special is "none of the above".
Dim special As New System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]")
' Check the length.
If Len(pwd) < minLength Then Return False
' Check for minimum number of occurrences.
If upper.Matches(pwd).Count < numUpper Then Return False
If lower.Matches(pwd).Count < numLower Then Return False
If number.Matches(pwd).Count < numNumbers Then Return False
If special.Matches(pwd).Count < numSpecial Then Return False
' Passed all checks.
Return True
End Function
Sub TestValidatePassword()
Dim password As String = "Password"
' Demonstrate that "Password" is not complex.
MsgBox(password & " is complex: " & ValidatePassword(password))
password = "Z9f%a>2kQ"
' Demonstrate that "Z9f%a>2kQ" is not complex.
MsgBox(password & " is complex: " & ValidatePassword(password))
End Sub
Compiling the Code
Call this method by passing the string that contains that password.
This example requires:
Access to the members of the System.Text.RegularExpressions namespace. Add an Imports statement if you are not fully
qualifying member names in your code. For more information, see Imports Statement.
Security
If you are moving the password across a network, you need to use a secure method for transferring data. For more
information, see ASP.NET Web Application Security.
You can improve the accuracy of the ValidatePassword function by adding additional complexity checks:
Compare the password and its substrings against the user's name, user identifier, and an application-defined dictionary.
In addition, treat visually similar characters as equivalent when performing the comparisons. For example, treat the
letters "l" and "e" as equivalent to the numerals "1" and "3".
If there is only one uppercase character, make sure it is not the password's first character.
Make sure that the last two characters of the password are letter characters.
Do not allow passwords in which all the symbols are entered from the keyboard's top row.
See Also
Reference
Regex
Other Resources
ASP.NET Web Application Security
Walkthroughs For Strings in Visual Basic
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Data Types -
defined by Visual Basic. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
An Imports statement specifying the System namespace. For more information, see Imports Statement.
Robust Programming
The IndexOf method is case-sensitive and uses the current culture.
For optimal error control, you might want to enclose the string search in the Try block of a
Try...Catch...Finally Statement (Visual Basic) construction.
See Also
Tasks
How to: Search Within a String (Visual Basic)
Reference
Try...Catch...Finally Statement (Visual Basic)
IndexOf
Other Resources
Introduction to Strings in Visual Basic
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Data Types -
defined by Visual Basic. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
An Imports statement specifying the System namespace. For more information, see Imports Statement.
Robust Programming
The IndexOf method reports the location of the first character of the first occurrence of the substring. The index is 0-based,
which means the first character of a string has an index of 0.
If IndexOf does not find the substring, it returns -1.
The IndexOf method is case-sensitive and uses the current culture.
For optimal error control, you might want to enclose the string search in the Try block of a
Try...Catch...Finally Statement (Visual Basic) construction.
See Also
Reference
Try...Catch...Finally Statement (Visual Basic)
IndexOf
Other Resources
Introduction to Strings in Visual Basic
Search and Replace for Strings in Visual Basic
Visual Basic Language Concepts
VB
Dim withParts As String = "Books and Chapters and Pages"
Dim withoutParts As String = Replace(withParts, "and ", "")
See Also
Reference
Replace Function (Visual Basic)
String Data Type (Visual Basic)
Visual Basic Language Concepts
See Also
Reference
Uri
Other Resources
Parsing Strings in Visual Basic
Visual Basic Language Concepts
''' <summary>
''' Parses an e-mail address into its parts.
''' </summary>
''' <param name="emailString">E-mail address to parse.</param>
''' <remarks> For example, this method displays the following
''' text when called with "someone@mail.contoso.com":
''' User name: someone
''' Address part: mail
''' Address part: contoso
''' Address part: com
''' </remarks>
Sub ParseEmailAddress(ByVal emailString As String)
Dim emailRegEx As New Regex("(\S+)@([^\.\s]+)(?:\.([^\.\s]+))+")
Dim m As Match = emailRegEx.Match(emailString)
If m.Success Then
Dim output As String = ""
output &= "User name: " & m.Groups(1).Value & vbCrLf
For i As Integer = 2 To m.Groups.Count - 1
Dim g As Group = m.Groups(i)
For Each c As Capture In g.Captures
output &= "Address part: " & c.Value & vbCrLf
Next
Next
MsgBox(output)
Else
MsgBox("The e-mail address cannot be parsed.")
End If
End Sub
This example requires that you use the Imports statement to import the System.Text.RegularExpressions namespace. For more
information, see Imports Statement.
See Also
Tasks
How to: Verify That Strings are in Valid E-Mail Format
Other Resources
Parsing Strings in Visual Basic
Visual Basic Language Concepts
This example requires that you use the Imports statement to import the System.Text.RegularExpressions namespace. For more
information, see Imports Statement.
See Also
Tasks
How to: Identify Hyperlinks in an HTML String in Visual Basic
How to: Strip Invalid Characters from a String
Other Resources
Parsing Strings in Visual Basic
Visual Basic Language Concepts
This example requires that you use the Imports statement to import the System.Text.RegularExpressions namespace. For more
information, see Imports Statement.
See Also
Tasks
How to: Identify Hyperlinks in an HTML String in Visual Basic
How to: Strip Invalid Characters from a String
Other Resources
Parsing Strings in Visual Basic
Visual Basic Language Concepts
This example requires that you use the Imports statement to import the System.Text.RegularExpressions namespace. For more
information, see Imports Statement.
See Also
Concepts
Example: Scanning for HREFs
Other Resources
Parsing Strings in Visual Basic
Visual Basic Language Concepts
''' <summary>
''' Parses an e-mail address into its parts.
''' </summary>
''' <param name="emailString">E-mail address to parse.</param>
''' <remarks> For example, this method displays the following
''' text when called with "someone@mail.contoso.com":
''' User name: someone
''' Address part: mail
''' Address part: contoso
''' Address part: com
''' </remarks>
Sub ParseEmailAddress(ByVal emailString As String)
Dim emailRegEx As New Regex("(\S+)@([^\.\s]+)(?:\.([^\.\s]+))+")
Dim m As Match = emailRegEx.Match(emailString)
If m.Success Then
Dim output As String = ""
output &= "User name: " & m.Groups(1).Value & vbCrLf
For i As Integer = 2 To m.Groups.Count - 1
Dim g As Group = m.Groups(i)
For Each c As Capture In g.Captures
output &= "Address part: " & c.Value & vbCrLf
Next
Next
MsgBox(output)
Else
MsgBox("The e-mail address cannot be parsed.")
End If
End Sub
See Also
Tasks
Troubleshooting Strings in Visual Basic
Concepts
Constructing a Validation Function in Visual Basic
Visual Basic Language Concepts
Constants Overview
A constant is a meaningful name that takes the place of a number or string that does not change. Constants store values that,
as the name implies, remain the same throughout the execution of an application. You can greatly improve the readability of
your code and make it easier to maintain by using constants. Use them in code that contains values that reappear or that
depends on certain numbers that are difficult to remember or have no obvious meaning.
How to Create and Use Constants
Visual Basic contains a number of predefined constants, mainly using for printing and displaying. You can also create your own
constants with the Const statement, using the same guidelines you would for creating a variable name. If Option Strict is On,
you must explicitly declare the constant type.
A constant's scope, which is the set of all code that can refer to it without qualifying its name, is the same as that of a variable
declared in the same location. To create a constant that exists within the scope of a particular procedure, declare it inside that
procedure. To create a constant that is available throughout an application, declare it using the Public keyword in the
declarations section of the class.
Note
Although constants somewhat resemble variables, you cannot modify them or assign new values to them as you can to varia
bles.
The constants you use in your code can be defined by the object model for controls or components you work with, or they can
be user-defined (that is, those you create yourself).
Compile-time and Run-time Constants
A compile-time constant is computed at the time the code is compiled, while a run-time constant can only be computed while
the application is running. A compile-time constant will have the same value each time an application runs, while a run-time
constant may change each time. Compile-time constants are required for cases such as array bounds, case expressions, or
enumerator initializers.
See Also
Tasks
How to: Declare A Constant
Reference
Const Statement (Visual Basic)
Public (Visual Basic)
Concepts
Constant and Literal Data Types
Constants Declared by Visual Basic
Other Resources
Constants and Enumerations (Visual Basic)
Constants in Visual Basic
Visual Basic Language Concepts
DE A Boolean value that can be set in the Project Properties dialog box. By default, the Debug configuration for a project de
BU fines DEBUG. When DEBUG is defined, Debug class methods generate output to the Output window. When it is not defin
G ed, Debug class methods are not compiled and no Debug output is generated.
TA A string representing the output type for the project or the setting of the command-line /target option. The possible value
RG s of TARGET are:
ET
"winexe" for a Windows application.
"exe" for a console application.
"library" for a class library.
"module" for a module.
The /target option may be set in the Visual Studio integrated development environment. For more information, see
/target (Visual Basic).
TR A Boolean value that can be set in the Project Properties dialog box. By default, all configurations for a project define TR
AC ACE. When TRACE is defined, Trace class methods generate output to the Output window. When it is not defined, Trace c
E lass methods are not compiled and no Trace output is generated.
VB A number representing the Visual Basic version, in major.minor format. The version number for Visual Basic 2005 is 8.0.
C_
VE
R
vbObjectError Error number. User-defined error numbers should be greater than this value. For example:
Err.Raise(Number) = vbObjectError + 1000
See Also
Tasks
How to: Declare A Constant
Concepts
Enumerations Declared by Visual Basic
Constants Overview
User-Defined Constants
Constant and Literal Data Types
Visual Basic Language Concepts
To declare a constant
Write a declaration that includes an access specifier, the Const keyword, and an expression, as in the following examples:
VB
Public Const DaysInYear = 365
Private Const WorkDays = 250
When Option Strict is On, you must declare a constant explicitly by specifying a data type (Boolean, Byte, Char,
DateTime, Decimal, Double, Integer, Long, Short, Single, or String). When Option Strict is Off, the constant is
assigned a data type by the compiler. For more information, see Constant and Literal Data Types.
To declare a constant with Option Strict On
With Option Strict On, write a declaration that includes the As keyword and an explicit data type, as in the following
examples:
VB
Public Const MyInteger As Integer = 42
Private Const DaysInWeek As Short = 7
Protected Friend Const Funday As String = "Sunday"
You can declare multiple constants on a single line, although your code is more readable if you declare only a single
constant per line. If you declare multiple constants on a single line, they must all have the same access level (Public,
Private, Friend, Protected, or Protected Friend).
To declare multiple constants on a single line
Separate the declarations with a comma and a space, as in the following example:
See Also
Tasks
How to: Declare Enumerations
Reference
Const Statement (Visual Basic)
Option Strict Statement
Concepts
Constant and Literal Data Types
Enumerations Overview
Constants Overview
Enumerations and Name Qualification
Intrinsic Constants and Enumerations
Other Resources
Constants and Enumerations in Visual Basic
Visual Basic Language Concepts
User-Defined Constants
A constant is a meaningful name that takes the place of a number or string that does not change. Constants store values that,
as the name implies, remain constant throughout the execution of an application. You can use constants that are defined by the
controls or components you work with, or you can create your own. Constants you create yourself are described as user-
defined.
You declare a constant with the Const statement, using the same guidelines you would for creating a variable name. If Option
Strict is On, you must explicitly declare the constant type.
Const Statement Usage
A Const statement can represent a mathematical or date/time quantity:
VB
Const conPi = 3.14159265358979
Public Const conMaxPlanets As Integer = 9
Const conReleaseDate = #1/1/1995#
The expression on the right side of the equal sign ( = ) is often a number or literal string, but it also can be an expression that
results in a number or string (although that expression cannot contain calls to functions). You can even define constants in
terms of previously defined constants:
VB
Const conPi2 = conPi * 2
Option Strict On
Public Const MyByte As Byte = 2
Explicitly declaring data types is unambiguous, and typed code is easier to read and maintain than untyped code. When
Option Strict is Off, however, the compiler uses the type of the expression used to initialize the constant. A numeric integer
literal is cast by default to the Integer data type. The default data type for floating-point numbers is Double, and the keywords
True and False specify a Boolean constant.
Literals and Type Coercion
In some cases, you might want to force a literal to a particular data type; for example, when assigning a particularly large
integral literal value to a variable of type Decimal. The following example produces an error:
The error results from the representation of the literal. The Decimal data type can hold a value this large, but the literal is
implicitly represented as a Long, which cannot.
You can coerce a literal to a particular data type in two ways: by appending a type character to it, or by placing it within
enclosing characters. A type character or enclosing characters must immediately precede and/or follow the literal, with no
intervening space or characters of any kind.
To make the previous example work, you can append the D type character to the literal, which causes it to be represented as a
Decimal:
MyDecimal = 100000000000000000000D
The following example demonstrates correct usage of type characters and enclosing characters:
The following table shows the enclosing characters and type characters available in Visual Basic.
Data type Enclosing character Appended type character
Boolean (none) (none)
Char " C
Date # (none)
Decimal (none) D or @
Double (none) R or #
Integer (none) I or %
Short (none) S
Single (none) F or !
See Also
Tasks
How to: Declare A Constant
How to: Declare Enumerations
Reference
Option Strict Statement
Option Explicit Statement (Visual Basic)
Data Type Summary (Visual Basic)
Concepts
User-Defined Constants
Constants Overview
Enumerations Overview
Enumerations and Name Qualification
Intrinsic Constants and Enumerations
Visual Basic Language Concepts
2. Define the constants in the enumeration. This example creates the Public enumeration temperatureValues and assigns
its values.
VB
Public Enum temperatureValues
Scorching
Hot
Lukewarm
Cool
Cold
End Enum
See Also
Tasks
How to: Refer to an Enumeration Member
Concepts
Enumerations and Name Qualification
When to Use an Enumeration
Intrinsic Constants and Enumerations
Constants Overview
Constant and Literal Data Types
Visual Basic Language Concepts
Enumerations Overview
Enumerations provide a convenient way to work with sets of related constants and to associate constant values with names.
For example, you can declare an enumeration for a set of integer constants associated with the days of the week, and then use
the names of the days rather than their integer values in your code.
Tasks involving Enumerations
The following table lists common tasks involving enumerations.
To do this See
Find a pre-defined enumeration Enumerations Declared by Visual Basic
Iterate through an enumeration How to: Iterate Through An Enumeration in Visual Basic
Determine the string associated with an enumeration How to: Determine the String Associated with an Enumeration Value
See Also
Tasks
How to: Declare A Constant
Reference
Enum Statement (Visual Basic)
Concepts
Constants Overview
User-Defined Constants
Constant and Literal Data Types
Intrinsic Constants and Enumerations
Visual Basic Language Concepts
AudioPlayMode Enumeration Indicates how to play sounds when calling audio methods.
BuiltInRole Enumeration Indicates the type of role to check when calling the My.User.IsInRole Method.
CallType Enumeration Indicates the type of the type of procedure being invoked when calling the CallByName f
unction.
CompareMethod Enumeration Indicates how to compare strings when calling comparison functions.
DateFormat Enumeration Indicates how to display dates when calling the FormatDateTime function.
DateInterval Enumeration Indicates how to determine and format date intervals when calling date-related functions.
DeleteDirectoryOption Enumeration Specifies what should be done when a directory that is to be deleted contains files or dire
ctories.
DueDate Enumeration Indicates when payments are due when calling financial methods.
FileAttribute Enumeration Indicates the file attributes to use when calling file-access functions.
FirstDayOfWeek Enumeration Indicates the first day of the week to use when calling date-related functions.
FirstWeekOfYear Enumeration Indicates the first week of the year to use when calling date-related functions.
MsgBoxResult Enumeration Indicates which button was pressed on a message box, returned by the MsgBox function.
MsgBoxStyle Enumeration Indicates which buttons to display when calling the MsgBox function.
OpenMode Enumeration Indicates mode that should be used when calling file-access functions.
OpenShare Enumeration Indicates whether a file can be used by other processes when calling file-access functions.
RecycleOption Enumeration Specifies whether a file should be deleted permanently or placed in the Recycle Bin.
SearchOption Enumeration Specifies whether to search all or only top level directories.
TriState Enumeration Indicates either a Boolean value or that the default should be used when calling number-
formatting functions.
UICancelOption Enumeration Specifies what should be done if the user clicks Cancel during an operation.
UIOption Enumeration Specifies whether or not to show a progress dialog box when copying, deleting, or movin
g files or directories.
VariantType Enumeration Indicates the type of a variant object, returned by the VarType function.
VbStrConv Enumeration Indicates which type of conversion to perform when calling the StrConv function.
DueDate Enumeration Indicates when payments are due when calling financial methods.
See Also
Tasks
How to: Declare Enumerations
How to: Refer to an Enumeration Member
How to: Iterate Through An Enumeration in Visual Basic
How to: Determine the String Associated with an Enumeration Value
Concepts
Enumerations and Name Qualification
When to Use an Enumeration
Visual Basic Language Concepts
2. Define the constants in the enumeration. By default, the first constant in an enumeration is initialized to 0, and
subsequent constants are initialized to a value of one more than the previous constant. For example, the following
enumeration, Days, contains a constant named Sunday with the value 0, a constant named Monday with the value 1, a
constant named Tuesday with the value of 2, and so on.
VB
Public Enum Days
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
End Enum
3. You can explicitly assign values to constants in an enumeration by using an assignment statement. You can assign any
integer value, including negative numbers. For example, you may want constants with values less than zero to represent
error conditions. In the following enumeration, the constant Invalid is explicitly assigned the value –1, and the constant
Sunday is assigned the value 0. Because it is the first constant in the enumeration, Saturday is also initialized to the value
0. The value of Monday is 1 (one more than the value of Sunday); the value of Tuesday is 2, and so on.
VB
Public Enum WorkDays
Saturday
Sunday = 0
Monday
Tuesday
Wednesday
Thursday
Friday
Invalid = -1
End Enum
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
To declare an enumeration explicitly
Write a declaration using the following syntax.
VB
Public Enum MyEnum As Byte
Zero
One
Two
End Enum
See Also
Tasks
How to: Refer to an Enumeration Member
How to: Iterate Through An Enumeration in Visual Basic
How to: Determine the String Associated with an Enumeration Value
Concepts
Enumerations and Name Qualification
When to Use an Enumeration
Intrinsic Constants and Enumerations
Constant and Literal Data Types
Other Resources
Constants in Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Declare Enumerations
How to: Iterate Through An Enumeration in Visual Basic
How to: Determine the String Associated with an Enumeration Value
Concepts
Enumerations Declared by Visual Basic
Enumerations and Name Qualification
When to Use an Enumeration
Visual Basic Language Concepts
An Imports statement imports namespace names from referenced projects and assemblies and from within the same project
as the module in which the statement appears. Once this statement is added, you can refer to your enumeration members
without qualification, as in the following example:
VB
X = Sunday
By organizing sets of related constants in enumerations, you can use the same constant names in different contexts. For
example, you can use the same names for the weekday constants in the Days and WorkDays enumerations. If you use the
Imports statement with your enumerations, you must be careful to avoid ambiguous references. Consider the following
example:
VB
Imports WindowsApplication1.Form1.Days
Imports WindowsApplication1.Form1.WorkDays
VB
Public Sub New()
' Insert code to implement constructor.
X = Monday
End Sub
Assuming that Monday is a member of both the Days enumeration and the Workdays enumeration, this code generates a
compiler error. To avoid ambiguous references when referring to an individual constant, qualify the constant name with its
enumeration. The following code refers to the Saturday constants in the Days and WorkDays enumerations.
VB
X = Days.Saturday
Y = WorkDays.Saturday
See Also
Tasks
How to: Declare Enumerations
How to: Refer to an Enumeration Member
How to: Iterate Through An Enumeration in Visual Basic
How to: Determine the String Associated with an Enumeration Value
Reference
Enum Statement (Visual Basic)
Imports Statement
Data Type Summary (Visual Basic)
Concepts
Enumerations Declared by Visual Basic
When to Use an Enumeration
Constant and Literal Data Types
Visual Basic Language Concepts
See Also
Tasks
How to: Declare Enumerations
How to: Determine the String Associated with an Enumeration Value
How to: Refer to an Enumeration Member
How to: Pass an Array to a Procedure or Property
Concepts
Enumerations Overview
When to Use an Enumeration
Enumerations and Name Qualification
Enumerations Declared by Visual Basic
Overview of Arrays in Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Declare Enumerations
How to: Refer to an Enumeration Member
How to: Iterate Through An Enumeration in Visual Basic
Reference
Enum Statement (Visual Basic)
GetValues
GetNames
Enum
Concepts
Enumerations Declared by Visual Basic
Enumerations and Name Qualification
When to Use an Enumeration
Visual Basic Language Concepts
AudioPlayMode Enumeration Indicates how to play sounds when calling audio methods.
BuiltInRole Enumeration Indicates the type of role to check when calling the My.User.IsInRole Method.
CallType Enumeration Indicates the type of procedure being invoked when calling the CallByName function.
CompareMethod Enumeration Indicates how to compare strings when calling comparison functions.
DateFormat Enumeration Indicates how to display dates when calling the FormatDateTime function.
DateInterval Enumeration Indicates how to determine and format date intervals when calling date-related functions.
DeleteDirectoryOption Enumeration Specifies what should be done when a directory that is to be deleted contains files or dire
ctories.
DueDate Enumeration Indicates when payments are due when calling financial methods.
FileAttribute Enumeration Indicates the file attributes to use when calling file-access functions.
FirstDayOfWeek Enumeration Indicates the first day of the week to use when calling date-related functions.
FirstWeekOfYear Enumeration Indicates the first week of the year to use when calling date-related functions.
MsgBoxResult Enumeration Indicates which button was pressed on a message box, returned by the MsgBox function.
MsgBoxStyle Enumeration Indicates which buttons to display when calling the MsgBox function.
OpenAccess Enumeration Identifies whether a file can be read from, written to, or both.
OpenMode Enumeration Indicates what access mode should be used when accessing a file.
OpenShare Enumeration Specifies whether other processes can access an open file.
RecycleOption Enumeration Specifies whether a file should be deleted permanently or placed in the Recycle Bin.
SearchOption Enumeration Specifies whether to search all or only top-level directories.
TriState Enumeration Indicates a Boolean value or if the default should be used when calling number-formattin
g functions.
UICancelOption Enumeration Specifies what should be done if the user clicks Cancel during an operation.
UIOption Enumeration Specifies whether or not to show a progress dialog box when copying, deleting, or movin
g files or directories.
VariantType Enumeration Indicates the type of a variant object, returned by the VarType function.
VbStrConv Enumeration Indicates which type of conversion to perform when calling the StrConv function.
See Also
Tasks
How to: Declare A Constant
Reference
Enum Statement (Visual Basic)
Object Browser
Concepts
Constants Overview
Constant and Literal Data Types
Enumerations Overview
User-Defined Constants
Other Resources
Constants and Enumerations (Visual Basic)
Visual Basic Language Concepts
Several operators can perform actions in a single expression or statement, as the following example illustrates.
VB
x = 45 + y * z ^ 2
In the preceding example, Visual Basic performs the operations in the expression on the right side of the assignment operator
(=), then assigns the resulting value to the variable x on the left. There is no practical limit to the number of operators that can
be combined into an expression, but an understanding of Operator Precedence in Visual Basic is necessary to ensure that you
get the results you expect.
See Also
Concepts
Efficient Combination of Operators
Other Resources
Operators (Visual Basic)
Statements in Visual Basic
Visual Basic Language Concepts
Find the quotient of one numeric value divided by another (without the remainder) \ Operator
Find the remainder of one numeric value divided by another (without the quotient) Mod Operator (Visual Basic)
Raise one numeric value to the power of another ^ Operator (Visual Basic)
Shift the bit pattern of a numeric value to the left << Operator (Visual Basic)
Shift the bit pattern of a numeric value to the right >> Operator (Visual Basic)
Comparison Tasks
The following table summarizes the available comparison operations.
To See
Determine whether two values are equal = Operator (Comparison Operators in Visual Basic)
Determine whether two values are unequal <> Operator (Comparison Operators in Visual Basic
)
Determine whether one value is less than another < Operator (Comparison Operators in Visual Basic)
Determine whether one value is greater than another > Operator (Comparison Operators in Visual Basic)
Determine whether one value is less than or equal to another <= Operator (Comparison Operators in Visual Basic
)
Determine whether one value is greater than or equal to another >= Operator (Comparison Operators in Visual Basic
)
Determine whether two object variables refer to the same object instance Is Operator (Visual Basic)
Determine whether two object variables refer to different object instance IsNot Operator
s
Determine whether an object is of a specific type TypeOf Operator (Visual Basic)
Concatenation Tasks
The following table summarizes the available concatenation operations.
To See
Join multiple strings into a single string & Operator (Concatenation Operators in Visual Basic)
Join numeric values with string values + Operator (Concatenation Operators in Visual Basic)
Perform logical conjunction on two Boolean values And Operator (Visual Basic)
Perform inclusive logical disjunction on two Boolean values Or Operator (Visual Basic)
Perform exclusive logical disjunction on two Boolean values Xor Operator (Visual Basic)
Perform short-circuited inclusive logical disjunction on two Boolean values OrElse Operator
Perform bit-by-bit logical conjunction on two integral values And Operator (Visual Basic)
Perform bit-by-bit inclusive logical disjunction on two integral values Or Operator (Visual Basic)
Perform bit-by-bit exclusive logical disjunction on two integral values Xor Operator (Visual Basic)
Perform bit-by-bit logical negation on an integral value Not Operator (Visual Basic)
See Also
Reference
Operators Listed by Functionality
Concepts
Operators and Expressions in Visual Basic
Visual Basic Language Concepts
Negation also uses the - Operator (Visual Basic), but with only one operand, as the following example demonstrates.
VB
Dim x As Integer = 65
Dim y As Integer
y = -x
Multiplication and division use the * Operator (Visual Basic) and / Operator (Visual Basic), respectively, as the following
example demonstrates.
VB
Dim y As Double
y = 45 * 55.23
y = 32 / 23
Exponentiation uses the ^ Operator (Visual Basic), as the following example demonstrates.
VB
Dim z As Double
z = 23 ^ 3
' The preceding statement sets z to 12167 (the cube of 23).
Integer division is carried out using the \ Operator. Integer division returns the quotient, that is, the integer that represents the
number of times the divisor can divide into the dividend without consideration of any remainder. Both the divisor and the
dividend must be integral types (SByte, Byte, Short, UShort, Integer, UInteger, Long, and ULong) for this operator. All other
types must be converted to an integral type first. The following example demonstrates integer division.
VB
Dim k As Integer
k = 23 \ 5
' The preceding statement sets k to 4.
Modulus arithmetic is performed using the Mod Operator (Visual Basic). This operator returns the remainder after dividing the
divisor into the dividend an integral number of times. If both divisor and dividend are integral types, the returned value is
integral. If divisor and dividend are floating-point types, the returned value is also floating-point. The following example
demonstrates this behavior.
VB
Dim x As Integer = 100
Dim y As Integer = 6
Dim z As Integer
z = x Mod y
' The preceding statement sets z to 4.
VB
Dim a As Double = 100.3
Dim b As Double = 4.13
Dim c As Double
c = a Mod b
' The preceding statement sets c to 1.18.
When you catch a DivideByZeroException exception, you can use its members to help you handle it. For example, the
Message property holds the message text for the exception. For more information, see
Structured Exception Handling Overview for Visual Basic.
Bit-Shift Operations
A bit-shift operation performs an arithmetic shift on a bit pattern. The pattern is contained in the operand on the left, while the
operand on the right specifies the number of positions to shift the pattern. You can shift the pattern to the right with the
>> Operator (Visual Basic) or to the left with the << Operator (Visual Basic).
The data type of the pattern operand must be SByte, Byte, Short, UShort, Integer, UInteger, Long, or ULong. The data type
of the shift amount operand must be Integer or must widen to Integer.
Arithmetic shifts are not circular, which means the bits shifted off one end of the result are not reintroduced at the other end.
The bit positions vacated by a shift are set as follows:
0 for an arithmetic left shift
0 for an arithmetic right shift of a positive number
0 for an arithmetic right shift of an unsigned data type (Byte, UShort, UInteger, ULong)
1 for an arithmetic right shift of a negative number (SByte, Short, Integer, or Long)
The following example shifts an Integer value both left and right.
VB
Dim lResult, rResult As Integer
Dim pattern As Integer = 12
' The low-order bits of pattern are 0000 1100.
lResult = pattern << 3
' A left shift of 3 bits produces a value of 96.
rResult = pattern >> 2
' A right shift of 2 bits produces value of 3.
<> (Inequality) Is the value of the first expression unequal to the value of the second? 23 <> 33 ' True
23 <> 23 ' Fals
e
23 <> 12 ' True
< (Less than) Is the value of the first expression less than the value of the second? 23 < 33 ' True
23 < 23 ' False
23 < 12 ' False
> (Greater than) Is the value of the first expression greater than the value of the second? 23 > 33 ' False
23 > 23 ' False
23 > 12 ' True
<= (Less than or equal to) Is the value of the first expression less than or equal to the value of the second? 23 <= 33 ' True
23 <= 23 ' True
23 <= 12 ' Fals
e
>= (Greater than or equal t Is the value of the first expression greater than or equal to the value of the seco 23 >= 33 ' Fals
e
o) nd?
23 >= 23 ' True
23 >= 12 ' True
Comparing Strings
Visual Basic compares strings using the Like Operator as well as the numeric comparison operators. The Like operator allows
you to specify a pattern. The string is then compared against the pattern, and if it matches, the result is True. Otherwise, the
result is False. The numeric operators allow you to compare String values based on their sort order, as the following example
shows.
"73" < "9"
' The result of the preceding comparison is True.
The result in the preceding example is True because the first character in the first string sorts before the first character in the
second string. If the first characters were equal, the comparison would continue to the next character in both strings, and so on.
You can also test equality of strings using the equality operator, as the following example shows.
"734" = "734"
' The result of the preceding comparison is True.
If one string is a prefix of another, such as "aa" and "aaa", the longer string is considered to be greater than the shorter string.
The following example illustrates this.
"aaa" > "aa"
' The result of the preceding comparison is True.
The sort order is based on either a binary comparison or a textual comparison depending on the setting of Option Compare.
For more information see Option Compare Statement.
Comparing Objects
Visual Basic compares two object reference variables with the Is Operator (Visual Basic) and the IsNot Operator. You can use
either of these operators to determine if two reference variables refer to the same object instance. The following example
illustrates this.
VB
Dim x As testClass
Dim y As New testClass()
x = y
If x Is y Then
' Insert code to run if x and y point to the same instance.
End If
In the preceding example, x Is y evaluates to True, because both variables refer to the same instance. Contrast this result with
the following example.
VB
Dim x As New customer()
Dim y As New customer()
If x Is y Then
' Insert code to run if x and y point to the same instance.
End If
In the preceding example, x Is y evaluates to False, because although the variables refer to objects of the same type, they
refer to different instances of that type.
When you want to test for two objects not pointing to the same instance, the IsNot operator lets you avoid a grammatically
clumsy combination of Not and Is. The following example illustrates this.
VB
Dim a As New classA()
Dim b As New classB()
If a IsNot b Then
' Insert code to run if a and b point to different instances.
End If
When typename specifies an interface type, then the TypeOf...Is expression returns True if the object implements the interface
type. When typename is a class type, then the expression returns True if the object is an instance of the specified class or of a
class that derives from the specified class. The following example illustrates this.
VB
Dim x As System.Windows.Forms.Button
x = New System.Windows.Forms.Button()
If TypeOf x Is System.Windows.Forms.Control Then
' Insert code to run if x is of type System.Windows.Forms.Control.
End If
In the preceding example, the TypeOf x Is Control expression evaluates to True because the type of x is Button, which
inherits from Control.
For more information, see TypeOf Operator (Visual Basic).
See Also
Reference
Comparison Operators (Visual Basic)
Concepts
Value Comparisons
Arithmetic Operators in Visual Basic
Concatenation Operators in Visual Basic
Logical and Bitwise Operators in Visual Basic
Other Resources
Operators (Visual Basic)
Visual Basic Language Concepts
You might want to take a certain action depending on whether two objects refer to the same instance. The preceding example
compares control c against the active control on form f. If there is no active control, or if there is one but it is not the same
control instance as c, then the If statement fails and the procedure returns without further processing.
Whether you use Is or IsNot is a matter of personal convenience to you. One might be easier to read than the other in a given
expression.
See Also
Concepts
Comparison Operators in Visual Basic
Visual Basic Language Concepts
VB
Dim sMatch As Boolean = myString Like "?[ACE]"
VB
Dim sMatch As Boolean = myString Like "num[i-m]"
Note that this match is case-sensitive.
Matching Empty Strings
Like treats the sequence [] as a zero-length string (""). You can use [] to test whether the entire string expression is empty,
but you cannot use it to test if a particular position in the string expression is empty. If an empty position is one of the options
you need to test for, you can use Like more than once.
To match a character in the string expression against a list of characters or no character
1. Call the Like operator twice on the same string expression, and connect the two calls with either the
Or Operator (Visual Basic) or the OrElse Operator.
2. In the pattern string for the first Like clause, include the character list, enclosed in brackets ([ ]).
3. In the pattern string for the second Like clause, do not put any character at the position in question.
The following example tests the seven-digit telephone number phoneNum for exactly three numeric digits, followed by a
space, a hyphen (–), a period (.), or no character at all, followed by exactly four numeric digits.
VB
Dim sMatch As Boolean = _
(phoneNum Like "###[ -.]####") OrElse (phoneNum Like "#######")
See Also
Reference
Comparison Operators (Visual Basic)
Like Operator
String Data Type (Visual Basic)
Concepts
Operators and Expressions in Visual Basic
Visual Basic Language Concepts
These operators can also concatenate String variables, as the following example shows.
VB
Dim a As String = "abc"
Dim d As String = "def"
Dim z As String = a & d
Dim w As String = a + d
' The preceding statements set both z and w to "abcdef".
c = 23 > 14 Or 8 > 11
d = 23 > 67 Or 8 > 11
' The preceding statements set c to True and d to False.
e = 23 > 67 Xor 11 > 8
f = 23 > 14 Xor 11 > 8
g = 14 > 23 Xor 8 > 11
' The preceding statements set e to True, f to False, and g to False.
VB
If amount > highestAllowed And checkIfValid(amount) Then
' The preceding statement calls checkIfValid().
End If
If amount > highestAllowed AndAlso checkIfValid(amount) Then
' The preceding statement does not call checkIfValid().
End If
If amount < highestAllowed Or checkIfValid(amount) Then
' The preceding statement calls checkIfValid().
End If
If amount < highestAllowed OrElse checkIfValid(amount) Then
' The preceding statement does not call checkIfValid().
End If
VB
Function checkIfValid(ByVal checkValue As Integer) As Boolean
If checkValue > 15 Then
MsgBox(CStr(checkValue) & " is not a valid value.")
' The MsgBox warning is not displayed if the call to
' checkIfValid() is part of a short-circuited expression.
Return False
Else
grandTotal += checkValue
' The grandTotal value is not updated if the call to
' checkIfValid() is part of a short-circuited expression.
Return True
End If
End Function
In the preceding example, note that some important code inside checkIfValid() does not run when the call is short-circuited.
The first If statement calls checkIfValid() even though 12 > 45 returns False, because And does not short-circuit. The second
If statement does not call checkIfValid(), because when 12 > 45 returns False, AndAlso short-circuits the second
expression. The third If statement calls checkIfValid() even though 12 < 45 returns True, because Or does not short-circuit.
The fourth If statement does not call checkIfValid(), because when 12 < 45 returns True, OrElse short-circuits the second
expression.
Bitwise Operations
Bitwise operations evaluate two integral values in binary (base 2) form. They compare the bits at corresponding positions and
then assign values based on the comparison. The following example illustrates the And operator.
Dim x As Integer
x = 3 And 5
The preceding example sets the value of x to 1. This happens for the following reasons:
The values are treated as binary:
3 in binary form = 011
5 in binary form = 101
The And operator compares the binary representations, one binary position (bit) at a time. If both bits at a given position
are 1, then a 1 is placed in that position in the result. If either bit is 0, then a 0 is placed in that position in the result. In the
preceding example this works out as follows:
011 (3 in binary form)
101 (5 in binary form)
001 (The result, in binary form)
The result is treated as decimal. The value 001 is the binary representation of 1, so x = 1.
The bitwise Or operation is similar, except that a 1 is assigned to the result bit if either or both of the compared bits is 1. Xor
assigns a 1 to the result bit if exactly one of the compared bits (not both) is 1. Not takes a single operand and inverts all the
bits, including the sign bit, and assigns that value to the result. This means that for signed positive numbers, Not always
returns a negative value, and for negative numbers, Not always returns a positive or zero value.
The AndAlso and OrElse operators do not support bitwise operations.
Note
Bitwise operations can be performed on integral types only. Floating-point values must be converted to integral types before
bitwise operation can proceed.
See Also
Reference
Logical/Bitwise Operators
Concepts
Boolean Expressions
Arithmetic Operators in Visual Basic
Comparison Operators in Visual Basic
Concatenation Operators in Visual Basic
Efficient Combination of Operators
Visual Basic Language Concepts
Creating complex expressions such as the one in the preceding example requires a thorough understanding of the rules of
operator precedence. For more information, see Operator Precedence in Visual Basic.
Parenthetical Expressions
Often you want operations to proceed in a different order from that determined by operator precedence. Consider the
following example.
x = z * y + 4
The preceding example multiplies z by y, then adds the result to 4. But if you want to add y and 4 before multiplying the result
by z, you can override normal operator precedence by using parentheses. By enclosing an expression in parentheses, you force
that expression to be evaluated first, regardless of operator precedence. To force the preceding example to do the addition first,
you could rewrite it as in the following example.
x = z * (y + 4)
In the preceding example, z + 2 is evaluated first, then the other parenthetical expressions. Exponentiation, which normally has
higher precedence than addition or multiplication, is evaluated last in this example because the other expressions are enclosed
in parentheses.
See Also
Tasks
How to: Calculate Numeric Values
Reference
Logical/Bitwise Operators
Operator Precedence in Visual Basic
Concepts
Arithmetic Operators in Visual Basic
Comparison Operators in Visual Basic
Logical and Bitwise Operators in Visual Basic
Boolean Expressions
Value Comparisons
Visual Basic Language Concepts
System.Math.PI
counter
4 * (67 + i)
The first three lines show a literal, a constant, and a variable. Each one forms a valid numeric expression by itself. The final
line shows a combination of a variable with two literals.
Note that a numeric expression does not form a complete Visual Basic statement by itself. You must use the expression
as part of a complete statement.
To store a numeric value
You can use an assignment statement to assign the value represented by a numeric expression to a variable, as the
following example demonstrates.
VB
Dim i As Integer = 2
Dim j As Integer
j = 4 * (67 + i)
In the preceding example, the value of the expression on the right side of the equal operator (=) is assigned to the
variable j on the left side of the operator, so j evaluates to 276.
For more information, see Assignment Statements.
Multiple Operators
If the numeric expression contains more than one operator, the order in which they are evaluated is determined by the rules of
operator precedence. To override the rules of operator precedence, you enclose expressions in parentheses, as in the above
example; the enclosed expressions are evaluated first.
To override normal operator precedence
Use parentheses to enclose the operations you want to be performed first. The following example shows two different
results with the same operands and operators.
VB
Dim i As Integer = 2
Dim j, k As Integer
j = 4 * (67 + i)
k = 4 * 67 + i
In the preceding example, the calculation for j performs the addition operator (+) first because the parentheses around
(67 + i) override normal precedence, and the value assigned to j is 276 (4 times 69). The calculation for k performs the
operators in their normal precedence (* before +), and the value assigned to k is 270 (268 plus 2).
For more information, see Operator Precedence in Visual Basic.
See Also
Reference
Operator Precedence in Visual Basic
Arithmetic Operators (Visual Basic)
Concepts
Operators and Expressions in Visual Basic
Value Comparisons
Assignment Statements
Efficient Combination of Operators
Visual Basic Language Concepts
Value Comparisons
Comparison operators can be used to construct expressions that compare the values of numeric variables. These expressions
return a Boolean value based on whether the comparison is true or false. Examples of such an expression are as follows.
45 > 26
26 > 45
The first expression evaluates to True, because 45 is greater than 26. The second example evaluates to False, because 26 is not
greater than 45.
You can also compare numeric expressions in this fashion. The expressions you compare can themselves be complex
expressions, as in the following example.
x / 45 * (y +17) >= System.Math.Sqrt(z) / (p - (x * 16))
The preceding complex expression includes literals, variables, and function calls. The expressions on both sides of the
comparison operator are evaluated, and the resulting values are then compared using the >= comparison operator. If the
value of the expression on the left side is greater than or equal to the value of the expression on the right, the entire expression
evaluates to True; otherwise, it evaluates to False.
Expressions that compare values are most commonly used in If...Then constructions, as in the following example.
VB
If x > 50 Then
' Insert code to run if x is greater than 50.
Else
' Insert code to run if x is less than or equal to 50.
End If
The = sign is a comparison operator as well as an assignment operator. When used as a comparison operator, it evaluates
whether the value on the left is equal to the value on the right, as shown in the following example.
VB
If x = 50 Then
' Insert code to continue program.
End If
You can also use a comparison expression anywhere a Boolean value is needed, such as in an If, While, Loop, or ElseIf
statement, or when assigning to or passing a value to a Boolean variable. In the following example, the value returned by the
comparison expression is assigned to a Boolean variable.
VB
Dim x As Boolean
x = 50 < 30
' The preceding statement assigns False to x.
See Also
Tasks
How to: Calculate Numeric Values
Reference
Operator Precedence in Visual Basic
Concepts
Boolean Expressions
Operators and Expressions in Visual Basic
Comparison Operators in Visual Basic
Visual Basic Language Concepts
Boolean Expressions
A Boolean expression is an expression that evaluates to a value of the Boolean Data Type. Boolean expressions can take
several forms. The simplest is the direct comparison of the value of a Boolean variable to a Boolean literal, as shown in the
following example.
VB
If newCustomer = True Then
' Insert code to execute if newCustomer = True.
Else
' Insert code to execute if newCustomer = False.
End If
Because 42 is less than 81, the Boolean expression in the preceding example evaluates to True. For more information on this
kind of expression, see Value Comparisons.
Comparison Operators Combined with Logical Operators
Comparison expressions can be combined using logical operators to produce more complex Boolean expressions. The
following example demonstrates the use of comparison operators in conjunction with a logical operator.
x > y And x < 1000
In the preceding example, the value of the overall expression depends on the values of the expressions on each side of the And
operator. If both expressions are True, then the overall expression evaluates to True. If either expression is False, then the
entire expression evaluates to False.
Short-Circuiting Operators
The logical operators AndAlso and OrElse exhibit behavior known as short-circuiting. A short-circuiting operator evaluates the
left operand first. If the left operand determines the value of the entire expression, then program execution proceeds without
evaluating the right expression. The following example illustrates this.
VB
If 45 < 12 AndAlso testFunction(3) = 81 Then
' Add code to continue execution.
End If
In the preceding example, the operator evaluates the left expression, 45 < 12. Because the left expression evaluates to False,
the entire logical expression must evaluate to False. Program execution thus skips execution of the code within the If block
without evaluating the right expression, testFunction(3). This example does not call testFunction() because the left
expression falsifies the entire expression.
Similarly, if the left expression in a logical expression using OrElse evaluates to True, execution proceeds to the next line of
code without evaluating the right expression, because the left expression has already validated the entire expression.
Comparison with Non-Short-Circuiting Operators
By contrast, both sides of the logical operator are evaluated when the logical operators And and Or are used. The following
example illustrates this.
VB
If 45 < 12 And testFunction(3) = 81 Then
' Add code to continue execution.
End If
The preceding example calls testFunction() even though the left expression evaluates to False.
Parenthetical Expressions
You can use parentheses to control the order of evaluation of Boolean expressions. Expressions enclosed by parentheses
evaluate first. For multiple levels of nesting, precedence is granted to the most deeply-nested expressions. Within parentheses,
evaluation proceeds according to the rules of operator precedence. For more information, see
Operator Precedence in Visual Basic.
See Also
Reference
Comparison Operators (Visual Basic)
Operator Precedence in Visual Basic
Boolean Data Type (Visual Basic)
Concepts
Logical and Bitwise Operators in Visual Basic
Value Comparisons
Assignment Statements
Efficient Combination of Operators
Visual Basic Language Concepts
Statements Overview
A statement in Visual Basic is a complete instruction. It can contain keywords, operators, variables, constants, and expressions.
Each statement belongs to one of the following categories:
Declaration Statements, which name a variable, constant, or procedure, and can also specify a data type.
Executable Statements, which initiate actions. These statements can call a method or function, and they can loop or
branch through blocks of code. Executable statements include Assignment Statements, which assign a value or
expression to a variable or constant.
Putting Multiple Statements on One Line
You can have multiple statements on a single line separated by the colon (:) character. The following example illustrates this.
VB
Dim sampleString As String = "Hello World" : MsgBox(sampleString)
Though occasionally convenient, this form of syntax makes your code hard to read and maintain. Thus, it is recommended that
you keep one statement to a line.
Continuing a Statement over Multiple Lines
A statement usually fits on one line, but when it is too long, you can continue it onto the next line using a line-continuation
sequence, which consists of a space followed by an underscore character (_) followed by a carriage return. In the following
example, the MsgBox executable statement is continued over two lines.
VB
Public Sub demoBox()
Dim nameVar As String
nameVar = "John"
MsgBox("Hello " & nameVar & _
". How are you?")
End Sub
Adding Comments
Source code is not always self-explanatory, even to the programmer who wrote it. To help document their code, therefore,
most programmers make liberal use of embedded comments. Comments in code can explain a procedure or a particular
instruction to anyone reading or working with it later. Visual Basic ignores comments during compilation, and they do not
affect the compiled code.
Comment lines begin with an apostrophe (') or REM followed by a space. They can be added anywhere in code, except within a
string. To append a comment to a statement, insert an apostrophe or REM after the statement, followed by the comment.
Comments can also go on their own separate line. The following example demonstrates these possibilities.
VB
' This is a comment on a separate code line.
REM This is another comment on a separate code line.
x += a(i) * b(i) ' Add this amount to total.
MsgBox(statusMessage) REM Inform operator of status.
Assignment Statements
Assignment statements carry out assignment operations, which consist of taking the value on the right side of the assignment
operator (=) and storing it in the element on the left, as in the following example.
VB
v = 42
In the preceding example, the assignment statement stores the literal value 42 in the variable v.
Eligible Programming Elements
The programming element on the left side of the assignment operator must be able to accept and store a value. This means it
must be a variable or property that is not ReadOnly (Visual Basic), or it must be an array element. In the context of an
assignment statement, such an element is sometimes called an lvalue, for "left value."
The value on the right side of the assignment operator is generated by an expression, which can consist of any combination of
literals, constants, variables, properties, array elements, other expressions, or function calls. The following example illustrates
this.
VB
x = y + z + findResult(3)
The preceding example adds the value held in variable y to the value held in variable z, and then adds the value returned by the
call to function findResult. The total value of this expression is then stored in variable x.
Data Types in Assignment Statements
In addition to numeric values, the assignment operator can also assign String values, as the following example illustrates.
VB
Dim a, b As String
a = "String variable assignment"
b = "Con" & "cat" & "enation"
' The preceding statement assigns the value "Concatenation" to b.
You can also assign Boolean values, using either a Boolean literal or a Boolean expression, as the following example
illustrates.
VB
Dim r, s, t As Boolean
r = True
s = 45 > 1003
t = 45 > 1003 Or 45 > 17
' The preceding statements assign False to s and True to t.
Similarly, you can assign appropriate values to programming elements of the Char, Date, or Object data type. You can also
assign an object instance to an element declared to be of the class from which that instance is created.
Compound Assignment Statements
Compound assignment statements first perform an operation on an expression before assigning it to a programming element.
The following example illustrates one of these operators, +=, which increments the value of the variable on the left side of the
operator by the value of the expression on the right.
VB
n += 1
The preceding example adds 1 to the value of n, and then stores that new value in n. It is a shorthand equivalent of the
following statement:
VB
n = n + 1
A variety of compound assignment operations can be performed using operators of this type. For a list of these operators and
more information about them, see Assignment Operators.
The concatenation assignment operator (&=) is useful for adding a string to the end of already existing strings, as the
following example illustrates.
VB
Dim q As String = "Sample "
q &= "String"
' q now contains "Sample String".
The first declaration is the Sub statement. Together with its matching End Sub statement, it declares a procedure named
applyFormat. It also specifies that applyFormat is Public, which means that any code that can refer to it can call it.
The second declaration is the Const statement, which declares the constant limit, specifying the Integer data type and a value
of 33.
The third declaration is the Dim statement, which declares the variable thisWidget. The data type is a specific object, namely
an object created from the Widget class. You can declare a variable to be of any elementary data type or of any object type that
is exposed in the application you are using.
Initial Values
When the code containing a declaration statement runs, Visual Basic reserves the memory required for the declared element. If
the element holds a value, Visual Basic initializes it to the default value for its data type. For more information, see "Behavior" in
Dim Statement (Visual Basic).
You can assign an initial value to a variable as part of its declaration, as the following example illustrates.
VB
Dim m As Integer = 45
' The preceding declaration creates m and assigns the value 45 to it.
If a variable is an object variable, you can explicitly create an instance of its class when you declare it by using the
New (Visual Basic) keyword, as the following example illustrates.
VB
Dim f As New System.Windows.Forms.Form()
Note that the initial value you specify in a declaration statement is not assigned to a variable until execution reaches its
declaration statement. Until that time, the variable contains the default value for its data type.
See Also
Tasks
How to: Declare A Constant
Concepts
Statements Overview
Assignment Statements
Executable Statements
Visual Basic Language Concepts
Executable Statements
An executable statement performs an action. It can call a procedure, branch to another place in the code, loop through several
statements, or evaluate an expression. An assignment statement is a special case of an executable statement.
The following example uses an If...Then...Else control structure to run different blocks of code based on the value of a variable.
Within each block of code, a For...Next loop runs a specified number of times.
VB
Public Sub startWidget(ByVal aWidget As widget, _
ByVal clockwise As Boolean, ByVal revolutions As Integer)
Dim counter As Integer
If clockwise = True Then
For counter = 1 To revolutions
aWidget.spinClockwise()
Next counter
Else
For counter = 1 To revolutions
aWidget.spinCounterClockwise()
Next counter
End If
End Sub
The If statement in the preceding example checks the value of the parameter clockwise. If the value is True, it calls the
spinClockwise method of aWidget. If the value is False, it calls the spinCounterClockwise method of aWidget. The
If...Then...Else control structure ends with End If.
The For...Next loop within each block calls the appropriate method a number of times equal to the value of the revolutions
parameter.
See Also
Concepts
Statements Overview
Assignment Statements
Declaration Statements in Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Break Large Pieces of Code into Smaller Pieces
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Recursive Procedures
Procedure Overloading
Other Resources
Object-Oriented Programming in Visual Basic
Visual Basic Language Concepts
Sub Procedures
A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements. The Sub procedure
performs a task and then returns control to the calling code, but it does not return a value to the calling code.
Each time the procedure is called, its statements are executed, starting with the first executable statement after the Sub
statement and ending with the first End Sub, Exit Sub, or Return statement encountered.
You can define a Sub procedure in modules, classes, and structures. It is Public by default, which means you can call it from
anywhere in your application that has access to the module, class, or structure in which you defined it. The term, method,
describes a Sub or Function procedure that is accessed from outside its defining module, class, or structure. For more
information, see Class Methods.
A Sub procedure can take arguments, such as constants, variables, or expressions, which are passed to it by the calling code.
Declaration Syntax
The syntax for declaring a Sub procedure is as follows:
[ modifiers ] Sub subname [( parameterlist )]
' Statements of the Sub procedure.
End Sub
The modifiers can specify access level and information regarding overloading, overriding, sharing, and shadowing. For more
information, see Sub Statement (Visual Basic).
Parameter Declaration
You declare each procedure parameter similarly to how you declare a variable, specifying the parameter name and data type.
You can also specify the passing mechanism, and whether the parameter is optional or a parameter array.
The syntax for each parameter in the parameter list is as follows:
[Optional] [ByVal | ByRef] [ParamArray] parametername As datatype
If the parameter is optional, you must also supply a default value as part of its declaration. The syntax for specifying a default
value is as follows:
Optional [ByVal | ByRef] parametername As datatype = defaultvalue
Parameters as Local Variables
When control passes to the procedure, each parameter is treated as a local variable. This means that its lifetime is the same as
that of the procedure, and its scope is the entire procedure.
Calling Syntax
You invoke a Sub procedure explicitly with a stand-alone calling statement. You cannot call it by using its name within an
expression. You must provide values for all arguments that are not optional, and you must enclose the argument list in
parentheses. If no arguments are supplied, you can optionally omit the parentheses. The use of the Call keyword is optional
but not recommended.
The syntax for a call to a Sub procedure is as follows:
[Call] subname [( argumentlist )]
You can call a Sub method from outside the class that defines it. First, you need to use the New keyword to create an instance
of the class, or call a method that returns an instance of the class. For more information, see How to: Use the New Keyword.
Then, you can use the following syntax to call the Sub method on the instance object:
Object.methodname[(argumentlist)]
For more information, see How to: Perform Actions with Methods.
Illustration of Declaration and Call
The following Sub procedure tells the computer operator which task the application is about to perform, and also displays a
time stamp. Instead of duplicating this code at the beginning of every task, the application simply calls tellOperator from
various places. Each call passes a string in the task argument that identifies the task being started.
VB
Sub tellOperator(ByVal task As String)
Dim stamp As Date
stamp = TimeOfDay()
MsgBox("Starting " & task & " at " & CStr(stamp))
End Sub
VB
Call tellOperator("file update")
See Also
Tasks
How to: Call a Procedure that Does Not Return a Value
How to: Call an Event Handler in Visual Basic
Reference
Sub Statement (Visual Basic)
Concepts
Procedures in Visual Basic
Function Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts
See Also
Tasks
How to: Create a Procedure
How to: Call a Procedure that Returns a Value
How to: Call an Event Handler in Visual Basic
Reference
Sub Statement (Visual Basic)
Shell Function
ArgumentException
Concepts
Procedures in Visual Basic
Sub Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts
You can dissociate an event handler from an event by executing the RemoveHandler Statement.
See Also
Tasks
How to: Create a Procedure
How to: Call a Procedure that Does Not Return a Value
Reference
Sub Statement (Visual Basic)
AddressOf Operator
Concepts
Procedures in Visual Basic
Sub Procedures
Visual Basic Language Concepts
Function Procedures
A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. The
Function procedure performs a task and then returns control to the calling code. When it returns control, it also returns a
value to the calling code.
Each time the procedure is called, its statements run, starting with the first executable statement after the Function statement
and ending with the first End Function, Exit Function, or Return statement encountered.
You can define a Function procedure in a module, class, or structure. It is Public by default, which means you can call it from
anywhere in your application that has access to the module, class, or structure in which you defined it.
A Function procedure can take arguments, such as constants, variables, or expressions, which are passed to it by the calling
code.
Declaration Syntax
The syntax for declaring a Function procedure is as follows:
[ modifiers ] Function functionname [( parameterlist )] As returntype
' Statements of the Function procedure.
End Function
The modifiers can specify access level and information regarding overloading, overriding, sharing, and shadowing. For more
information, see Function Statement (Visual Basic).
You declare each parameter the same way you do for Sub Procedures.
Data Type
Every Function procedure has a data type, just as every variable does. This data type is specified by the As clause in the
Function statement, and it determines the data type of the value the function returns to the calling code. The following sample
declarations illustrate this.
functionname = expression
' When control returns to the calling code, expression is the return value.
End Function
It uses the Return statement to specify the return value, and returns control immediately to the calling program. The
following example illustrates this.
Function functionname [( parameterlist )] As returntype
' The following statement immediately transfers control back to the calling code and returns the value
of expression .
Return expression
End Function
The advantage of assigning the return value to the function name is that control does not return from the procedure until it
encounters an Exit Function or End Function statement. This allows you to assign a preliminary value and adjust it later if
necessary.
For more information, see "Return Value" in Function Statement (Visual Basic).
Returning Arrays
If the Function procedure returns an array data type, you cannot access the individual elements of the array within the
function. If you attempt to do this, the compiler interprets it as a recursive call to the procedure. The following example
illustrates this.
Function allOnes(ByVal n As Integer) As Integer()
For i As Integer = 1 To n - 1
' The following statement generates a COMPILER ERROR .
allOnes(i) = 1
Next i
' The following statement generates a COMPILER ERROR .
Return allOnes()
End Function
In the preceding example, the compiler interprets the attempted assignment allOnes(i) = 1 as a call to allOnes on the left
side of an assignment statement. It interprets the attempted Return allOnes() as a call with no argument. Both statements
generate compiler errors.
Calling Syntax
You invoke a Function procedure by including its name and arguments either on the right side of an assignment statement or
in an expression. You must provide values for all arguments that are not optional, and you must enclose the argument list in
parentheses. If no arguments are supplied, you can optionally omit the parentheses.
The syntax for a call to a Function procedure is as follows:
lvalue = functionname [( argumentlist )]
If (( functionname [( argumentlist )] / 3) <= expression ) Then
When you call a Function procedure, you do not have to use its return value. If you do not, all the actions of the function are
performed, but the return value is ignored. MsgBox is often called in this manner.
Illustration of Declaration and Call
The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, given the values for the other
two sides.
VB
Function hypotenuse(ByVal side1 As Single, ByVal side2 As Single) As Single
Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
End Function
VB
Dim testLength, testHypotenuse As Single
testHypotenuse = hypotenuse(testLength, 10.7)
See Also
Tasks
How to: Return a Value from a Procedure
How to: Call a Procedure that Returns a Value
Reference
Function Statement (Visual Basic)
Concepts
Procedures in Visual Basic
Sub Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts
The following example shows a typical call to hypotenuse, which stores the returned value.
VB
Dim testLength, testHypotenuse As Single
testHypotenuse = hypotenuse(testLength, 10.7)
See Also
Tasks
How to: Create a Procedure that Returns a Value
How to: Return a Value from a Procedure
How to: Call a Procedure that Does Not Return a Value
Reference
Function Statement (Visual Basic)
Concepts
Function Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts
Property Procedures
A property procedure is a series of Visual Basic statements that manipulate a custom property on a module, class, or structure.
Property procedures are also known as property accessors.
Visual Basic provides for the following property procedures:
A Get procedure returns the value of a property. It is called when you access the property in an expression.
A Set procedure sets a property to a value, including an object reference. It is called when you assign a value to the
property.
You usually define property procedures in pairs, using the Get and Set statements, but you can define either procedure alone if
the property is read-only (Get Statement) or write-only (Set Statement (Visual Basic)).
You can define properties in classes, structures, and modules. Properties are Public by default, which means you can call them
from anywhere in your application that can access the property's container.
For a comparison of properties and variables, see Differences Between Properties and Variables in Visual Basic.
Declaration Syntax
A property itself is defined by a block of code enclosed within the Property Statement and the End Property statement. Inside
this block, each property procedure appears as an internal block enclosed within a declaration statement (Get or Set) and the
matching End declaration.
The syntax for declaring a property and its procedures is as follows:
[Default] [modifiers] Property propertyname[(parameterlist)] As datatype
[accesslevel] Get
' Statements of the Get procedure.
' The following statement returns expression as the property's value.
Return expression
End Get
[accesslevel] Set[(ByVal newvalue As datatype)]
' Statements of the Set procedure.
' The following statement assigns newvalue as the property's value.
lvalue = newvalue
End Set
End Property
The modifiers can specify access level and information regarding overloading, overriding, sharing, and shadowing, as well as
whether the property is read-only or write-only. The access level on the Get or Set procedure can be any level that is more
restrictive than the access level specified for the property itself. For more information, see Property Statement.
Data Type
A property's data type and principal access level are defined in the Property statement, not in the property procedures. A
property can have only one data type. For example, you cannot define a property to store a Decimal value but retrieve a
Double value.
Access Level
However, you can define a principal access level for a property and further restrict the access level in one of its property
procedures. For example, you can define a Public property and then define a Private Set procedure. The Get procedure
remains Public. You can change the access level in only one of a property's procedures, and you can only make it more
restrictive than the principal access level. For more information, see How to: Declare a Property with Mixed Access Levels.
Parameter Declaration
You declare each parameter the same way you do for Sub Procedures, except that the passing mechanism must be ByVal.
The syntax for each parameter in the parameter list is as follows:
[Optional] ByVal [ParamArray] parametername As datatype
If the parameter is optional, you must also supply a default value as part of its declaration. The syntax for specifying a default
value is as follows:
Optional ByVal parametername As datatype = defaultvalue
Property Value
In a Get procedure, the return value is supplied to the calling expression as the value of the property.
In a Set procedure, the new property value is passed to the parameter of the Set statement. If you explicitly declare a
parameter, you must declare it with the same data type as the property. If you do not declare a parameter, the compiler uses
the implicit parameter Value to represent the new value to be assigned to the property.
Calling Syntax
You invoke a property procedure implicitly by making reference to the property. You use the name of the property the same
way you would use the name of a variable, except that you must provide values for all arguments that are not optional, and
you must enclose the argument list in parentheses. If no arguments are supplied, you can optionally omit the parentheses.
The syntax for an implicit call to a Set procedure is as follows:
propertyname[(argumentlist)] = expression
End Get
Set(ByVal Value As String)
Dim space As Integer = Value.IndexOf(" ")
If space < 0 Then
firstName = Value
lastName = ""
Else
firstName = Value.Substring(0, space)
lastName = Value.Substring(space + 1)
End If
End Set
End Property
The following example shows typical calls to the property procedures of fullName.
VB
fullName = "MyFirstName MyLastName"
MsgBox(fullName)
See Also
Tasks
How to: Create a Property
How to: Call a Property Procedure
How to: Declare and Call a Default Property in Visual Basic
How to: Put a Value in a Property
How to: Get a Value from a Property
Concepts
Procedures in Visual Basic
Function Procedures
Operator Procedures
Procedure Parameters and Arguments
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts
Storage Directly associated with v Typically has internal storage not available outside the prope
ariable's value rty's containing class or module
Property's value might or might not exist as a stored elemen
t1
Custom actions (in addition to acceptin Not possible Can be performed as part of setting or retrieving property v
g or returning value) alue
1 Unlike a variable, the value of a property might not correspond directly to a single item of storage. The storage might be split
into pieces for convenience or security, or the value might be stored in an encrypted form. In these cases the Get procedure
would assemble the pieces or decrypt the stored value, and the Set procedure would encrypt the new value or split it into the
constituent storage. A property value might be ephemeral, like time of day, in which case the Get procedure would calculate it
on the fly each time you access the property.
See Also
Tasks
How to: Create a Property
How to: Declare a Property with Mixed Access Levels
How to: Call a Property Procedure
How to: Declare and Call a Default Property in Visual Basic
How to: Put a Value in a Property
How to: Get a Value from a Property
Reference
Property Statement
Dim Statement (Visual Basic)
Concepts
Property Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts
End Get
Set(ByVal Value As String)
Dim space As Integer = Value.IndexOf(" ")
If space < 0 Then
firstName = Value
lastName = ""
Else
firstName = Value.Substring(0, space)
lastName = Value.Substring(space + 1)
End If
End Set
End Property
The following example shows typical calls to the property procedures of fullName. The first call sets the property value and the
second call retrieves it.
VB
fullName = "MyFirstName MyLastName"
MsgBox(fullName)
See Also
Tasks
How to: Declare a Property with Mixed Access Levels
How to: Call a Property Procedure
How to: Declare and Call a Default Property in Visual Basic
How to: Put a Value in a Property
How to: Get a Value from a Property
Concepts
Procedures in Visual Basic
Property Procedures
Procedure Parameters and Arguments
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts
In the preceding example, the Get procedure has the same Protected access as the property itself, while the Set
procedure has Private access. A class derived from employee can read the salary value, but only the employee class can
set it.
See Also
Tasks
How to: Create a Property
How to: Call a Property Procedure
How to: Declare and Call a Default Property in Visual Basic
How to: Put a Value in a Property
How to: Get a Value from a Property
Reference
Property Statement
Concepts
Procedures in Visual Basic
Property Procedures
Procedure Parameters and Arguments
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts
2. If the property takes arguments, follow the property name with parentheses to enclose the argument list. If there are no
arguments, you can optionally omit the parentheses.
3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the
arguments in the same order that the property defines the corresponding parameters.
The value of the property participates in the expression just as a variable or constant would, or it is stored in the variable or
property on the left side of the assignment statement.
To call a property's Set procedure
1. Use the property name on the left side of an assignment statement.
The following example sets the value of the TimeOfDay Property, implicitly calling the Set procedure.
VB
' The following statement calls the Set procedure of the Visual Basic TimeOfDay proper
ty.
TimeOfDay = #12:00:00 PM#
2. If the property takes arguments, follow the property name with parentheses to enclose the argument list. If there are no
arguments, you can optionally omit the parentheses.
3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the
arguments in the same order that the property defines the corresponding parameters.
The value generated on the right side of the assignment statement is stored in the property.
See Also
Tasks
How to: Create a Property
How to: Declare a Property with Mixed Access Levels
How to: Declare and Call a Default Property in Visual Basic
How to: Put a Value in a Property
How to: Get a Value from a Property
Reference
Property Statement
Get Statement
Set Statement (Visual Basic)
Concepts
Property Procedures
Procedure Parameters and Arguments
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts
2. Use the variable name alone in an expression where you would normally include the property name.
VB
MsgBox(x)
3. Follow the variable name with an argument list in parentheses. A default property must take at least one argument.
VB
MsgBox(x(1))
4. To retrieve the default property value, use the variable name, with an argument list, in an expression or following the
equal (=) sign in an assignment statement.
VB
MsgBox(x(1) & x(2) & x(3))
5. To set the default property value, use the variable name, with an argument list, on the left side of an assignment
statement.
VB
x(1) = "Hello"
x(2) = " "
x(3) = "World"
6. You can always specify the default property name together with the variable name, just as you would do to access any
other property.
VB
x.myProperty(1) = "Hello"
x.myProperty(2) = " "
x.myProperty(3) = "World"
Example
The following example declares a default property on a class.
VB
Public Class class1
Private myStrings() As String
Sub New(ByVal size As Integer)
ReDim myStrings(size)
End Sub
Default Property myProperty(ByVal index As Integer) As String
Get
' The Get property procedure is called when the value
' of the property is retrieved.
Return myStrings(index)
End Get
Set(ByVal Value As String)
' The Set property procedure is called when the value
' of the property is modified.
' The value to be assigned is passed in the argument
' to Set.
myStrings(index) = Value
End Set
End Property
End Class
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
The following example demonstrates how to call the default property myProperty on class class1. The three assignment
statements store values in myProperty, and the MsgBox call reads the values.
VB
Sub Test()
Dim x As New class1(3)
x(1) = "Hello"
x(2) = " "
x(3) = "World"
MsgBox(x(1) & x(2) & x(3))
End Sub
The most common use of a default property is the Item Property (Collection Object) on various collection classes.
Robust Programming
Default properties can result in a small reduction in source code-characters, but they can make your code more difficult to
read. If the calling code is not familiar with your class or structure, when it makes a reference to the class or structure name it
cannot be certain whether that reference accesses the class or structure itself, or a default property. This can lead to compiler
errors or subtle run-time logic errors.
You can somewhat reduce the chance of default property errors by always using the Option Strict Statement to set compiler
type checking to On.
If you are planning to use a predefined class or structure in your code, you must determine whether it has a default property,
and if so, what its name is.
Because of these disadvantages, you should consider not defining default properties. For code readability, you should also
consider always referring to all properties explicitly, even default properties.
See Also
Tasks
How to: Create a Property
How to: Declare a Property with Mixed Access Levels
How to: Call a Property Procedure
How to: Put a Value in a Property
How to: Get a Value from a Property
Reference
Property Statement
Default (Visual Basic)
Concepts
Property Procedures
Procedure Parameters and Arguments
Default Property Changes for Visual Basic 6.0 Users
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts
2. If the property takes arguments, follow the property name with parentheses to enclose the argument list. If there are no
arguments, you can optionally omit the parentheses.
3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the
arguments in the same order that the property defines the corresponding parameters.
4. The value generated on the right side of the assignment statement is stored in the property.
See Also
Tasks
How to: Create a Property
How to: Declare a Property with Mixed Access Levels
How to: Call a Property Procedure
How to: Declare and Call a Default Property in Visual Basic
How to: Get a Value from a Property
Reference
Property Statement
TimeOfDay Property
Concepts
Property Procedures
Procedure Parameters and Arguments
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts
2. If the property takes arguments, follow the property name with parentheses to enclose the argument list. If there are no
arguments, you can optionally omit the parentheses.
3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the
arguments in the same order that the property defines the corresponding parameters.
The value of the property participates in the expression just as a variable or constant would, or it is stored in the variable or
property on the left side of the assignment statement.
See Also
Tasks
How to: Create a Property
How to: Declare a Property with Mixed Access Levels
How to: Call a Property Procedure
How to: Declare and Call a Default Property in Visual Basic
How to: Put a Value in a Property
Reference
Property Statement
Concepts
Procedures in Visual Basic
Property Procedures
Procedure Parameters and Arguments
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts
Operator Procedures
An operator procedure is a series of Visual Basic statements that define the behavior of a standard operator (such as *, <>, or
And) on a class or structure you have defined. This is also called operator overloading.
When to Define Operator Procedures
When you have defined a class or structure, you can declare variables to be of the type of that class or structure. Sometimes
such a variable needs to participate in an operation as part of an expression. To do this, it must be an operand of an operator.
Visual Basic defines operators only on its fundamental data types. You can define the behavior of an operator when one or
both of the operands are of the type of your class or structure.
For more information, see Operator Statement.
Types of Operator Procedure
An operator procedure can be one of the following types:
A definition of a unary operator where the argument is of the type of your class or structure.
A definition of a binary operator where at least one of the arguments is of the type of your class or structure.
A definition of a conversion operator where the argument is of the type of your class or structure.
A definition of a conversion operator that returns the type of your class or structure.
Conversion operators are always unary, and you always use CType as the operator you are defining.
Declaration Syntax
The syntax for declaring an operator procedure is as follows:
Public Shared [Widening | Narrowing] Operator operatorsymbol ( operand1 [, operand2 ]) As datatype
' Statements of the operator procedure.
End Operator
You use the Widening or Narrowing keyword only on a type conversion operator. The operator symbol is always
CType Function for a type conversion operator.
You declare two operands to define a binary operator, and you declare one operand to define a unary operator, including a
type conversion operator. All operands must be declared ByVal.
You declare each operand the same way you declare parameters for Sub Procedures.
Data Type
Because you are defining an operator on a class or structure you have defined, at least one of the operands must be of the data
type of that class or structure. For a type conversion operator, either the operand or the return type must be of the data type of
the class or structure.
For more details, see Operator Statement.
Calling Syntax
You invoke an operator procedure implicitly by using the operator symbol in an expression. You supply the operands the same
way you do for predefined operators.
The syntax for an implicit call to an operator procedure is as follows:
Dim testStruct As structurename
Dim testNewStruct As structurename = testStruct operatorsymbol 10
Illustration of Declaration and Call
The following structure stores a signed 128-bit integer value as the constituent high-order and low-order parts. It defines the +
operator to add two veryLong values and generate a resulting veryLong value.
VB
Public Structure veryLong
Dim highOrder As Long
Dim lowOrder As Long
Public Shared Operator +(ByVal v As veryLong, _
ByVal w As veryLong) As veryLong
Dim sum As New veryLong
sum = v
Try
sum.lowOrder += w.lowOrder
Catch ex As System.OverflowException
sum.lowOrder -= (Long.MaxValue - w.lowOrder + 1)
sum.highOrder += 1
End Try
sum.highOrder += w.highOrder
Return sum
End Operator
End Structure
The following example shows a typical call to the + operator defined on veryLong.
VB
Dim v1, v2, v3 As veryLong
v1.highOrder = 1
v1.lowOrder = Long.MaxValue
v2.highOrder = 0
v2.lowOrder = 4
v3 = v1 + v2
See Also
Tasks
How to: Define an Operator
How to: Define a Conversion Operator
How to: Call an Operator Procedure
How to: Use a Class that Defines Operators
Reference
Operator Statement
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Property Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts
You can test the structure height with the following code.
VB
Public Sub consumeHeight()
Dim p1 As New height(3, 10)
Dim p2 As New height(4, 8)
Dim p3 As height = p1 + p2
Dim s As String = p1.ToString() & " + " & p2.ToString() _
& " = " & p3.ToString() & " (= 8' 6"" ?)"
Dim p4 As New height(2, 14)
s &= vbCrLf & "2' 14"" = " & p4.ToString() & " (= 3' 2"" ?)"
Dim p5 As New height(4, 24)
s &= vbCrLf & "4' 24"" = " & p5.ToString() & " (= 6' 0"" ?)"
MsgBox(s)
End Sub
See Also
Tasks
How to: Define a Conversion Operator
How to: Call an Operator Procedure
How to: Use a Class that Defines Operators
How to: Declare a Structure
Reference
Operator Statement
Structure Statement
Concepts
Operator Procedures
Visual Basic Language Concepts
You can test the structure digit with the following code.
VB
Public Sub consumeDigit()
Dim d1 As New digit(4)
Dim d2 As New digit(7)
Dim d3 As digit = CType(CByte(3), digit)
Dim s As String = "Initial 4 generates " & CStr(CType(d1, Byte)) _
& vbCrLf & "Initial 7 generates " & CStr(CType(d2, Byte)) _
& vbCrLf & "Converted 3 generates " & CStr(CType(d3, Byte))
Try
Dim d4 As digit
d4 = CType(CType(d1, Byte) + CType(d2, Byte), digit)
Catch e4 As System.Exception
s &= vbCrLf & "4 + 7 generates " & """" & e4.Message & """"
End Try
Try
Dim d5 As digit = CType(CByte(10), digit)
Catch e5 As System.Exception
s &= vbCrLf & "Initial 10 generates " & """" & e5.Message & """"
End Try
MsgBox(s)
End Sub
See Also
Tasks
How to: Define an Operator
How to: Call an Operator Procedure
How to: Use a Class that Defines Operators
How to: Declare a Structure
Reference
Operator Statement
Structure Statement
Concepts
Operator Procedures
Implicit and Explicit Conversions
Widening and Narrowing Conversions
Visual Basic Language Concepts
Because TimeSpan overloads the standard + operator, the preceding example calls an operator procedure when it calculates
the value of combinedSpan.
For an example of calling a conversation operator procedure, see How to: Use a Class that Defines Operators.
Compiling the Code
Be sure the class or structure you are using defines the operator you want to use.
See Also
Tasks
How to: Define an Operator
How to: Define a Conversion Operator
How to: Declare a Structure
Reference
Operator Statement
Widening
Narrowing
Structure Statement
Concepts
Operator Procedures
Implicit and Explicit Conversions
Widening and Narrowing Conversions
Visual Basic Language Concepts
VB
Public Sub setJobString(ByVal g As Integer)
Dim title As String
Dim jobTitle As System.Data.SqlTypes.SqlString
Select Case g
Case 1
title = "President"
Case 2
title = "Vice President"
Case 3
title = "Director"
Case 4
title = "Manager"
Case Else
title = "Worker"
End Select
jobTitle = CType(title, SqlString)
MsgBox("Group " & CStr(g) & " generates title """ _
& CType(jobTitle, String) & """")
End Sub
The SqlString structure defines a conversion operator (CType Function) from String to SqlString and another from SqlString
to String. The statement that assigns title to jobTitle makes use of the first operator, and the
MsgBox Function (Visual Basic) call uses the second.
Compiling the Code
Be sure the class or structure you are using defines the operator you want to use. Do not assume that the class or structure has
defined every operator available for overloading. For a list of available operators, see Operator Statement.
Include the appropriate Imports statement for the SQL string at the beginning of your source file (in this case
System.Data.SqlTypes).
Your project must have references to System.Data and System.XML. If you need to add them, see
How to: Add and Remove References in Visual Studio (C#, J#).
See Also
Tasks
How to: Define an Operator
How to: Define a Conversion Operator
How to: Call an Operator Procedure
How to: Declare a Structure
Reference
Widening
Narrowing
Structure Statement
Concepts
Operator Procedures
Implicit and Explicit Conversions
Widening and Narrowing Conversions
Visual Basic Language Concepts
If the type checking switch (Option Strict Statement) is Off, the As clause is optional, except that if any one parameter uses it,
all parameters must use it. If type checking is On, the As clause is required for all procedure parameters.
If the calling code expects to supply an argument with a data type different from that of its corresponding parameter, such as
Byte to a String parameter, it must do one of the following:
Supply only arguments with data types that widen to the parameter data type;
Set Option Strict Off to allow implicit narrowing conversions; or
Use a conversion keyword to explicitly convert the data type.
Type Parameters
A generic procedure also defines one or more type parameters in addition to its normal parameters. A generic procedure
allows the calling code to pass different data types each time it calls the procedure, so it can tailor the data types to the
requirements of each individual call. See Generic Procedures in Visual Basic.
See Also
Tasks
How to: Define a Parameter for a Procedure
How to: Pass Arguments to a Procedure
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Property Procedures
Operator Procedures
Argument Passing By Value and By Reference
Procedure Overloading
Other Resources
Type Conversions in Visual Basic
Visual Basic Language Concepts
The first parameter accepts a customer object, and updateCustomer can directly update the variable passed to c because
the argument is passed ByRef. The procedure cannot change the values of the last two arguments because they are
passed ByVal.
If the calling code does not supply a value for the level parameter, Visual Basic sets it to the default value of 0.
If the type checking switch (Option Strict Statement) is Off, the As clause is optional when you define a parameter.
However, if any one parameter uses an As clause, all of them must use it. If the type checking switch is On, the As clause
is required for every parameter definition.
Specifying data types for all your programming elements is known as strong typing. When you set Option Strict On,
Visual Basic enforces strong typing. This is strongly recommended, for the following reasons:
It enables IntelliSense support for your variables and parameters. This allows you to see their properties and other
members as you type in your code.
It allows the compiler to perform type checking. This helps catch statements that can fail at run time due to errors
such as overflow. It also catches calls to methods on objects that do not support them.
It results in faster execution of your code. One reason for this is that if you do not specify a data type for a
programming element, the Visual Basic compiler assigns it the Object type. Your compiled code might have to
convert back and forth between Object and other data types, which reduces performance.
See Also
Tasks
How to: Pass Arguments to a Procedure
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Argument Passing By Value and By Reference
Recursive Procedures
Procedure Overloading
Other Resources
Object-Oriented Programming in Visual Basic
Visual Basic Language Concepts
The preceding example supplies the required first argument, which is the message string to be displayed. It omits an
argument for the optional second parameter, which specifies the buttons to be displayed on the message box. Because
the call does not supply a value, MsgBox uses the default value, MsgBoxStyle.OKOnly, which displays only an OK
button.
The second comma in the argument list marks the place of the omitted second argument, and the last string is passed to
the optional third parameter of MsgBox, which is the text to be displayed in the title bar.
See Also
Tasks
How to: Define a Parameter for a Procedure
Concepts
Sub Procedures
Function Procedures
Property Procedures
Operator Procedures
Argument Passing By Value and By Reference
Recursive Procedures
Procedure Overloading
Other Resources
Object-Oriented Programming in Visual Basic
Visual Basic Language Concepts
Fields (member variables of modules, classes, and structures), except for read-onl Constants and literals
y
Reference type (contains a point The procedure cannot change the variable but can The procedure can change the variable an
er to a class or structure instanc change members of the instance to which it point d members of the instance to which it poin
e) s. ts.
See Also
Tasks
How to: Pass Arguments to a Procedure
How to: Change the Value of a Procedure Argument
How to: Protect a Procedure Argument Against Value Changes
How to: Force an Argument to Be Passed by Value
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Differences Between Modifiable and Nonmodifiable Arguments
Argument Passing by Position and by Name
Value Types and Reference Types
Visual Basic Language Concepts
VB
Public Sub replace(ByRef a() As Long)
Dim k() As Long = {100, 200, 300}
a = k
For j As Integer = 0 To UBound(a)
a(j) = a(j) + 1
Next j
End Sub
VB
Dim n() As Long = {10, 20, 30, 40}
Call increase(n)
MsgBox("After increase(n): " & CStr(n(0)) & ", " & _
CStr(n(1)) & ", " & CStr(n(2)) & ", " & CStr(n(3)))
Call replace(n)
MsgBox("After replace(n): " & CStr(n(0)) & ", " & _
CStr(n(1)) & ", " & CStr(n(2)) & ", " & CStr(n(3)))
The first MsgBox call displays "After increase(n): 11, 21, 31, 41". Because the array n is a reference type, replace can change
its members, even though the passing mechanism is ByVal.
The second MsgBox call displays "After replace(n): 101, 201, 301". Because n is passed ByRef, replace can modify the
variable n in the calling code and assign a new array to it. Because n is a reference type, replace can also change its
members.
You can prevent the procedure from modifying the variable itself in the calling code. See
How to: Protect a Procedure Argument Against Value Changes.
Compiling the Code
When you pass a variable by reference, you must use the ByRef keyword to specify this mechanism.
The default in Visual Basic is to pass arguments by value. However, it is good programming practice to include either the ByVal
or ByRef keyword with every declared parameter. This makes your code easier to read.
Security
There is always a potential risk in allowing a procedure to change the value underlying an argument in the calling code. Make
sure you expect this value to be changed, and be prepared to check it for validity before using it.
See Also
Tasks
How to: Pass Arguments to a Procedure
How to: Protect a Procedure Argument Against Value Changes
How to: Force an Argument to Be Passed by Value
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Differences Between Modifiable and Nonmodifiable Arguments
Differences Between Passing an Argument By Value and By Reference
Argument Passing by Position and by Name
Value Types and Reference Types
Visual Basic Language Concepts
VB
Public Sub replace(ByVal a() As Long)
Dim k() As Long = {100, 200, 300}
a = k
For j As Integer = 0 To UBound(a)
a(j) = a(j) + 1
Next j
End Sub
VB
Dim n() As Long = {10, 20, 30, 40}
Call increase(n)
MsgBox("After increase(n): " & CStr(n(0)) & ", " & _
CStr(n(1)) & ", " & CStr(n(2)) & ", " & CStr(n(3)))
Call replace(n)
MsgBox("After replace(n): " & CStr(n(0)) & ", " & _
CStr(n(1)) & ", " & CStr(n(2)) & ", " & CStr(n(3)))
The first MsgBox call displays "After increase(n): 11, 21, 31, 41". Because the array n is a reference type, replace can change
its members, even though the passing mechanism is ByVal.
The second MsgBox call displays "After replace(n): 11, 21, 31, 41". Because n is passed ByVal, replace cannot modify the
variable n in the calling code by assigning a new array to it. When replace creates the new array instance k and assigns it to
the local variable a, it loses the reference to n passed in by the calling code. When it changes the members of a, only the local
array k is affected. Therefore, replace does not increment the values of array n in the calling code.
Compiling the Code
The default in Visual Basic is to pass arguments by value. However, it is good programming practice to include either the ByVal
or ByRef keyword with every declared parameter. This makes your code easier to read.
See Also
Tasks
How to: Pass Arguments to a Procedure
How to: Change the Value of a Procedure Argument
How to: Force an Argument to Be Passed by Value
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Differences Between Modifiable and Nonmodifiable Arguments
Differences Between Passing an Argument By Value and By Reference
Argument Passing by Position and by Name
Value Types and Reference Types
Visual Basic Language Concepts
VB
Dim str As String = "Cannot be replaced if passed ByVal"
' The following call passes str ByVal even though it is declared ByRef.
Call setNewString((str))
' The parentheses around str protect it from change.
MsgBox(str)
' The following call allows str to be passed ByRef as declared.
Call setNewString(str)
' Variable str is not protected from change.
MsgBox(str)
When str is enclosed in extra parentheses within the argument list, the setNewString procedure cannot change its value in the
calling code, and MsgBox displays "Cannot be replaced if passed ByVal". When str is not enclosed in extra parentheses, the
procedure can change it, and MsgBox displays "This is a new value for the inString argument."
Compiling the Code
When you pass a variable by reference, you must use the ByRef keyword to specify this mechanism.
The default in Visual Basic is to pass arguments by value. However, it is good programming practice to include either the ByVal
or ByRef keyword with every declared parameter. This makes your code easier to read.
Robust Programming
If a procedure declares a parameter ByRef, the correct execution of the code might depend on being able to change the
underlying element in the calling code. If the calling code overrides this calling mechanism by enclosing the argument in
parentheses, or if it passes a nonmodifiable argument, the procedure cannot change the underlying element. This might
produce unexpected results in the calling code.
Security
There is always a potential risk in allowing a procedure to change the value underlying an argument in the calling code. Make
sure you expect this value to be changed, and be prepared to check it for validity before using it.
See Also
Tasks
How to: Pass Arguments to a Procedure
How to: Change the Value of a Procedure Argument
How to: Protect a Procedure Argument Against Value Changes
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Differences Between Modifiable and Nonmodifiable Arguments
Differences Between Passing an Argument By Value and By Reference
Argument Passing by Position and by Name
Value Types and Reference Types
Visual Basic Language Concepts
When you call this procedure, you can supply the arguments by position, by name, or by using a mixture of both.
Passing Arguments by Position
You can call the procedure studentInfo with its arguments passed by position and delimited by commas, as shown in the
following example:
VB
Call studentInfo("Mary", 19, #9/21/1981#)
If you omit an optional argument in a positional argument list, you must hold its place with a comma. The following example
calls studentInfo without the age argument:
VB
Call studentInfo("Mary", , #9/21/1981#)
In the preceding example, no extra comma is necessary to hold the place of the omitted age argument, since birth is passed
by name.
When you supply arguments by a mixture of position and name, the positional arguments must all come first. Once you supply
an argument by name, the remaining arguments must all be by name.
Supplying Optional Arguments by Name
Passing arguments by name is especially useful when you call a procedure that has more than one optional argument. If you
supply arguments by name, you do not have to use consecutive commas to denote missing positional arguments. Passing
arguments by name also makes it easier to keep track of which arguments you are passing and which ones you are omitting.
Restrictions on Supplying Arguments by Name
You cannot pass arguments by name to avoid entering required arguments. You can omit only the optional arguments.
You cannot pass a parameter array by name. This is because when you call the procedure, you supply an indefinite number of
comma-separated arguments for the parameter array, and the compiler cannot associate more than one argument with a
single name.
See Also
Tasks
How to: Pass Arguments to a Procedure
How to: Pass Arguments to a Procedure by Name
Reference
Optional (Visual Basic)
ParamArray
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Optional Parameters
Parameter Arrays
Visual Basic Language Concepts
VB
Call studentInfo(age:=19, birth:=#9/21/1981#, name:="Mary")
When you pass arguments by name, you do not have to supply them in the same order as the procedure declares them.
Compiling the Code
Make sure the parameter name in the argument list exactly matches the name declared by the procedure.
See Also
Tasks
How to: Pass Arguments to a Procedure
Reference
Optional (Visual Basic)
ParamArray
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Parameter Arrays
Visual Basic Language Concepts
Optional Parameters
You can specify that a procedure parameter is optional and no argument has to be supplied for it when the procedure is called.
Optional parameters are indicated by the Optional keyword in the procedure definition. The following rules apply:
Every optional parameter in the procedure definition must specify a default value.
The default value for an optional parameter must be a constant expression.
Every parameter following an optional parameter in the procedure definition must also be optional.
The following syntax shows a procedure declaration with an optional parameter:
Sub sub name(ByVal parameter 1 As data type 1, Optional ByVal parameter 2 As data type 2 =
default value)
If the optional parameter is a reference type such as a String, you can use Nothing as the default value, provided this is not an
expected value for the argument.
Optional Parameters and Overloading
Another way to define a procedure with optional parameters is to use overloading. If you have one optional parameter, you
can define two overloaded versions of the procedure, one accepting the parameter and one without it. This approach becomes
more complicated as the number of optional parameters increases. However, its advantage is that you can be absolutely sure
whether the calling program supplied each optional argument.
See Also
Tasks
How to: Define Optional Parameters for a Procedure
How to: Call a Procedure that Takes Optional Parameters
How to: Determine Whether an Optional Parameter Was Supplied
Reference
Optional (Visual Basic)
ParamArray
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Parameter Arrays
Procedure Overloading
Visual Basic Language Concepts
If the calling code does not supply a value for office in the argument list, Visual Basic supplies the default value of "QJZ".
Compiling the Code
You must specify a default value for every optional parameter in the procedure declaration. Be sure that each default value is a
constant that the compiler can evaluate at compile time.
See Also
Tasks
How to: Call a Procedure that Takes Optional Parameters
How to: Determine Whether an Optional Parameter Was Supplied
Reference
Optional (Visual Basic)
ParamArray
Concepts
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Parameter Arrays
Procedure Overloading
Visual Basic Language Concepts
Example
The following example makes several calls to the MsgBox function. MsgBox has one required parameter and two optional
parameters.
VB
MsgBox("Important message", MsgBoxStyle.Critical, "MsgBox Example")
MsgBox("Just display this message.")
MsgBox("Test message", , "Title bar text")
MsgBox(Title:="Title bar text", Prompt:="Test message")
The first call to MsgBox supplies all three arguments in the order MsgBox defines them. The second call supplies only the
required argument. The third and fourth calls supply the first and third arguments. The third call does this by position, and the
fourth call does it by name.
Compiling the Code
Before you omit an argument from the argument list, be sure the corresponding parameter is optional, and also be sure you
want the procedure to use the default value for that parameter.
If you supply an argument by name, be sure the name in the argument list exactly matches the declared parameter name.
See Also
Tasks
How to: Define Optional Parameters for a Procedure
How to: Determine Whether an Optional Parameter Was Supplied
Reference
Optional (Visual Basic)
ParamArray
Concepts
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Parameter Arrays
Procedure Overloading
Visual Basic Language Concepts
If the calling code does not supply a value for office in the argument list, Visual Basic supplies the default value of "QJZ".
If the optional parameter is a reference type such as a String, you can use Nothing (Visual Basic) as the default value, provided
this is not an expected value for the argument.
For an example of using overloads to determine whether an optional parameter was passed, see
How to: Overload a Procedure that Takes Optional Parameters.
See Also
Tasks
How to: Define Optional Parameters for a Procedure
How to: Call a Procedure that Takes Optional Parameters
Reference
Optional (Visual Basic)
ParamArray
Concepts
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Parameter Arrays
Procedure Overloading
Visual Basic Language Concepts
Parameter Arrays
Usually, you cannot call a procedure with more arguments than the procedure declaration specifies. When you need an
indefinite number of arguments, you can declare a parameter array, which allows a procedure to accept an array of values for
a parameter. You do not have to know the number of elements in the parameter array when you define the procedure. The
array size is determined individually by each call to the procedure.
Declaring a ParamArray
You use the ParamArray keyword to denote a parameter array in the parameter list. The following rules apply:
A procedure can define only one parameter array, and it must be the last parameter in the procedure definition.
The parameter array must be passed by value. It is good programming practice to explicitly include the ByVal keyword in
the procedure definition.
The parameter array is automatically optional. Its default value is an empty one-dimensional array of the parameter
array's element type.
All parameters preceding the parameter array must be required. The parameter array must be the only optional
parameter.
For more information, see How to: Define a Procedure with an Indefinite Number of Parameters.
Calling a ParamArray
When you call a procedure that defines a parameter array, you can supply the argument in any one of the following ways:
Nothing — that is, you can omit the ParamArray argument. In this case, an empty array is passed to the procedure. You
can also pass the Nothing (Visual Basic) keyword, with the same effect.
A list of an arbitrary number of arguments, separated by commas. The data type of each argument must be implicitly
convertible to the ParamArray element type.
An array with the same element type as the parameter array's element type.
In all cases, the code within the procedure treats the parameter array as a one-dimensional array with elements of the same
data type as the ParamArray data type.
For more information, see How to: Call a Procedure that Takes an Indefinite Number of Parameters.
Security Note
Whenever you deal with an array which can be indefinitely large, there is a risk of overrunning some internal capacity of you
r application. If you accept a parameter array, you should test for the size of the array that the calling code passed to it. Take a
ppropriate steps if it is too large for your application. For more information, see How to: Determine the Size of an Array.
See Also
Reference
Optional (Visual Basic)
UBound Function (Visual Basic)
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Procedure Overloading
Type Checking in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
Example
The following example defines a procedure with a parameter array, and outputs the values of all the array elements passed to
the parameter array.
VB
Sub studentScores(ByVal name As String, ByVal ParamArray scores() As String)
Debug.WriteLine("Scores for " & name & ":" & vbCrLf)
' Use UBound to determine largest subscript of the array.
For i As Integer = 0 To UBound(scores, 1)
Debug.WriteLine("Score " & i & ": " & scores(i))
Next i
End Sub
The first call omits the parameter array altogether and supplies only the required first argument. The studentScores
procedure treats this call as passing an empty array.
The second and third calls supply argument lists of different lengths to the parameter array. Each such list is passed as an array
of values.
The fourth call passes an array to the parameter array.
See Also
Reference
Optional (Visual Basic)
ParamArray
ByVal
UBound Function (Visual Basic)
Concepts
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Procedure Overloading
Type Checking in Visual Basic
Visual Basic Language Concepts
Recursive Procedures
A recursive procedure is one that calls itself. In general, this is not the most effective way to write Visual Basic code.
The following procedure uses recursion to calculate the factorial of its original argument.
VB
Function factorial(ByVal n As Integer) As Integer
If n <= 1 Then
Return 1
Else
Return factorial(n - 1) * n
End If
End Function
Procedure Overloading
Overloading a procedure means defining it in multiple versions, using the same name but different parameter lists. The
purpose of overloading is to define several closely related versions of a procedure without having to differentiate them by
name. You do this by varying the parameter list.
Overloading Rules
When you overload a procedure, the following rules apply:
Same Name. Each overloaded version must use the same procedure name.
Different Signature. Each overloaded version must differ from all other overloaded versions in at least one of the
following respects:
Number of parameters
Order of the parameters
Data types of the parameters
Number of type parameters (for a generic procedure)
Return type (only for a conversion operator)
Together with the procedure name, the preceding items are collectively called the signature of the procedure. When you
call an overloaded procedure, the compiler uses the signature to check that the call correctly matches the definition.
Items Not Part of Signature. You cannot overload a procedure without varying the signature. In particular, you cannot
overload a procedure by varying only one or more of the following items:
Procedure modifier keywords, such as Public, Shared, and Static
Parameter or type parameter names
Type parameter constraints (for a generic procedure)
Parameter modifier keywords, such as ByRef and Optional
Whether it returns a value
The data type of the return value (except for a conversion operator)
The items in the preceding list are not part of the signature. Although you cannot use them to differentiate between
overloaded versions, you can vary them among overloaded versions that are properly differentiated by their signatures.
Late-Bound Arguments. If you intend to pass a late bound object variable to an overloaded version, you must declare
the appropriate parameter as Object.
Multiple Versions of a Procedure
Suppose you are writing a Sub procedure to post a transaction against a customer's balance, and you want to be able to refer
to the customer either by name or by account number. To accommodate this, you can define two different Sub procedures, as
in the following example:
VB
Sub postName(ByVal custName As String, ByVal amount As Single)
' Insert code to access customer record by customer name.
End Sub
Sub postAcct(ByVal custAcct As Integer, ByVal amount As Single)
' Insert code to access customer record by account number.
End Sub
Overloaded Versions
An alternative is to overload a single procedure name. You can use the Overloads keyword to define a version of the procedure
for each parameter list, as follows:
VB
Overloads Sub post(ByVal custName As String, ByVal amount As Single)
' Insert code to access customer record by customer name.
End Sub
Overloads Sub post(ByVal custAcct As Integer, ByVal amount As Single)
' Insert code to access customer record by account number.
End Sub
Additional Overloads
If you also wanted to accept a transaction amount in either Decimal or Single, you could further overload post to allow for
this variation. If you did this to each of the overloads in the preceding example, you would have four Sub procedures, all with
the same name but with four different signatures.
Advantages of Overloading
The advantage of overloading a procedure is in the flexibility of the call. To use the post procedure declared in the preceding
example, the calling code can obtain the customer identification as either a String or an Integer, and then call the same
procedure in either case. The following example illustrates this:
VB
Imports MSVB = Microsoft.VisualBasic
VB
Dim customer As String
Dim accountNum As Integer
Dim amount As Single
customer = MSVB.Interaction.InputBox("Enter customer name or number")
amount = MSVB.Interaction.InputBox("Enter transaction amount")
Try
accountNum = CInt(customer)
Call post(accountNum, amount)
Catch
Call post(customer, amount)
End Try
See Also
Tasks
How to: Define Multiple Versions of a Procedure
How to: Call an Overloaded Procedure
How to: Overload a Procedure that Takes Optional Parameters
How to: Overload a Procedure that Takes an Indefinite Number of Parameters
Reference
Overloads
Concepts
Procedures in Visual Basic
Considerations in Overloading Procedures
Overload Resolution
Generic Types in Visual Basic
Visual Basic Language Concepts
The calling code can obtain the customer identification as either a String or an Integer, and then use the same calling
statement in either case.
For information on how to call these versions of the post procedure, see How to: Call an Overloaded Procedure.
Compiling the Code
Make sure each of your overloaded versions has the same procedure name but a different parameter list.
See Also
Tasks
Troubleshooting Procedures
How to: Overload a Procedure that Takes Optional Parameters
How to: Overload a Procedure that Takes an Indefinite Number of Parameters
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Considerations in Overloading Procedures
Overload Resolution
Visual Basic Language Concepts
VB
Dim customer As String
Dim accountNum As Integer
Dim amount As Single
customer = MSVB.Interaction.InputBox("Enter customer name or number")
amount = MSVB.Interaction.InputBox("Enter transaction amount")
Try
accountNum = CInt(customer)
Call post(accountNum, amount)
Catch
Call post(customer, amount)
End Try
See Also
Tasks
Troubleshooting Procedures
How to: Define Multiple Versions of a Procedure
How to: Overload a Procedure that Takes Optional Parameters
How to: Overload a Procedure that Takes an Indefinite Number of Parameters
Reference
Overloads
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Procedure Overloading
Considerations in Overloading Procedures
Overload Resolution
Visual Basic Language Concepts
VB
' The preceding definition is equivalent to the following two overloads.
' Overloads Sub q(ByVal b As Byte)
' Overloads Sub q(ByVal b As Byte, ByVal j As Long)
VB
' Therefore, the following overload is not valid because the signature is already in u
se.
' Overloads Sub q(ByVal c As Byte, ByVal k As Long)
' The following overload uses a different signature and is valid.
Overloads Sub q(ByVal b As Byte, ByVal j As Long, ByVal s As Single)
VB
' The preceding definition is equivalent to the following overloads.
' Overloads Sub p(ByVal d As Date)
' Overloads Sub p(ByVal d As Date, ByVal c() As Char)
' Overloads Sub p(ByVal d As Date, ByVal c1 As Char)
' Overloads Sub p(ByVal d As Date, ByVal c1 As Char, ByVal c2 As Char)
' And so on, with an additional Char argument in each successive overload.
You cannot overload such a procedure with a parameter list that takes a one-dimensional array for the parameter array.
However, you can use the signatures of the other implicit overloads. The following declarations illustrate this.
VB
' The following overload is not valid because it takes an array for the parameter array.
' Overloads Sub p(ByVal x As Date, ByVal y() As Char)
' The following overload takes a single value for the parameter array and is valid.
Overloads Sub p(ByVal z As Date, ByVal w As Char)
The code in the overloaded versions does not have to test whether the calling code supplied one or more values for the
ParamArray parameter, or if so, how many. Visual Basic passes control to the version matching the calling argument list.
Compiling the Code
Because a procedure with a ParamArray parameter is equivalent to a set of overloaded versions, you cannot overload such a
procedure with a parameter list corresponding to any of these implicit overloads. For more information, see
Considerations in Overloading Procedures.
Security
Whenever you deal with an array which can be indefinitely large, there is a risk of overrunning some internal capacity of your
application. If you accept a parameter array, you should test for the length of the array the calling code passed to it, and take
appropriate steps if it is too large for your application.
See Also
Tasks
Troubleshooting Procedures
How to: Define Multiple Versions of a Procedure
How to: Call an Overloaded Procedure
How to: Overload a Procedure that Takes Optional Parameters
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Optional Parameters
Parameter Arrays
Procedure Overloading
Overload Resolution
Visual Basic Language Concepts
VB
' The preceding definition is equivalent to the following two overloads.
' Overloads Sub q(ByVal b As Byte)
' Overloads Sub q(ByVal b As Byte, ByVal j As Long)
VB
' Therefore, the following overload is not valid because the signature is already in use.
' Overloads Sub q(ByVal c As Byte, ByVal k As Long)
' The following overload uses a different signature and is valid.
Overloads Sub q(ByVal b As Byte, ByVal j As Long, ByVal s As Single)
For a procedure with more than one optional parameter, there is a set of implicit overloads, arrived at by logic similar to that in
the preceding example.
Implicit Overloads for a ParamArray Parameter
The compiler considers a procedure with a ParamArray parameter to have an infinite number of overloads, differing from each
other in what the calling code passes to the parameter array, as follows:
One overload for when the calling code does not supply an argument to the ParamArray
One overload for when the calling code supplies a one-dimensional array of the ParamArray element type
For every positive integer, one overload for when the calling code supplies that number of arguments, each of the
ParamArray element type
The following declarations illustrate these implicit overloads.
VB
Overloads Sub p(ByVal d As Date, ByVal ParamArray c() As Char)
VB
' The preceding definition is equivalent to the following overloads.
' Overloads Sub p(ByVal d As Date)
' Overloads Sub p(ByVal d As Date, ByVal c() As Char)
' Overloads Sub p(ByVal d As Date, ByVal c1 As Char)
' Overloads Sub p(ByVal d As Date, ByVal c1 As Char, ByVal c2 As Char)
' And so on, with an additional Char argument in each successive overload.
You cannot overload such a procedure with a parameter list that takes a one-dimensional array for the parameter array.
However, you can use the signatures of the other implicit overloads. The following declarations illustrate this.
VB
' The following overload is not valid because it takes an array for the parameter array.
' Overloads Sub p(ByVal x As Date, ByVal y() As Char)
' The following overload takes a single value for the parameter array and is valid.
Overloads Sub p(ByVal z As Date, ByVal w As Char)
See Also
Tasks
Troubleshooting Procedures
How to: Define Multiple Versions of a Procedure
How to: Call an Overloaded Procedure
How to: Overload a Procedure that Takes Optional Parameters
How to: Overload a Procedure that Takes an Indefinite Number of Parameters
Reference
Overloads
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Overload Resolution
Visual Basic Language Concepts
Overload Resolution
When the Visual Basic compiler encounters a call to a procedure that is defined in several overloaded versions, the compiler
must decide which of the overloads to call. It does this by performing the following steps:
1. Accessibility. It eliminates any overload with an access level that prevents the calling code from calling it.
2. Number of Parameters. It eliminates any overload that defines a different number of parameters than are supplied in
the call.
3. Parameter Data Types. It eliminates any overload for which the data types of the calling arguments cannot be
converted to the parameter types defined in the overload.
4. Narrowing Conversions. It eliminates any overload that requires a narrowing conversion from the calling argument
types to the defined parameter types. This is true whether the type checking switch (Option Strict Statement) is On or
Off.
5. Least Widening. It considers the remaining overloads in pairs. For each pair, it compares the data types of the defined
parameters. If the types in one of the overloads all widen to the corresponding types in the other, the compiler eliminates
the latter. That is, it retains the overload that calls for the least amount of widening.
6. Single Candidate. It continues considering overloads in pairs until only one overload remains, and it resolves the call to
that overload. If the compiler cannot reduce the overloads to a single candidate, it generates an error.
The following illustration shows the process that determines which of a set of overloaded versions to call.
Resolving among overloaded versions
VB
Dim r, s As Short
Call z(r, s)
Dim p As Byte, q As Short
' The following statement causes an overload resolution error.
Call z(p, q)
In the first call, the compiler eliminates the first overload because the type of the first argument (Short) narrows to the type of
the corresponding parameter (Byte). It then eliminates the third overload because each argument type in the second overload
(Short and Single) widens to the corresponding type in the third overload (Integer and Single). The second overload requires
less widening, so the compiler uses it for the call.
In the second call, the compiler cannot eliminate any of the overloads on the basis of narrowing. It eliminates the third
overload for the same reason as in the first call, because it can call the second overload with less widening of the argument
types. However, the compiler cannot resolve between the first and second overloads. Each has one defined parameter type that
widens to the corresponding type in the other (Byte to Short, but Single to Double). The compiler therefore generates an
overload resolution error.
Overloaded Optional and ParamArray Arguments
If two overloads of a procedure have identical signatures except that the last parameter is declared Optional (Visual Basic) in
one and ParamArray in the other, the compiler resolves a call to that procedure as follows:
If the call supplies the last argument as The compiler resolves the call to the overload declaring the last argume
nt as
No value (argument omitted) Optional
See Also
Tasks
Troubleshooting Procedures
How to: Define Multiple Versions of a Procedure
How to: Call an Overloaded Procedure
How to: Overload a Procedure that Takes Optional Parameters
How to: Overload a Procedure that Takes an Indefinite Number of Parameters
Reference
Overloads
Concepts
Optional Parameters
Parameter Arrays
Procedure Overloading
Considerations in Overloading Procedures
Visual Basic Language Concepts
Troubleshooting Procedures
This page lists some common problems that can occur when working with procedures.
Returning an Array Type from a Function Procedure
If a Function procedure returns an array data type, you cannot use the Function name to store values in the elements of the
array. If you attempt to do this, the compiler interprets it as a call to the Function. The following example generates compiler
errors.
Function allOnes(ByVal n As Integer) As Integer()
For i As Integer = 1 To n - 1
' The following statement generates a COMPILER ERROR .
allOnes(i) = 1
Next i
' The following statement generates a COMPILER ERROR .
Return allOnes()
End Function
The statement allOnes(i) = 1 generates a compiler error because it appears to call allOnes with an argument of the wrong
data type (a singleton Integer instead of an Integer array). The statement Return allOnes() generates a compiler error
because it appears to call allOnes with no argument.
Correct Approach: To be able to modify the elements of an array that is to be returned, define an internal array as a local
variable. The following example compiles without error.
VB
Function allOnes(ByVal n As Integer) As Integer()
Dim i As Integer, iArray(n) As Integer
For i = 0 To n - 1
iArray(i) = 1
Next i
Return iArray
End Function
VB
Public Sub replace(ByVal a() As Long)
Dim k() As Long = {100, 200, 300}
a = k
For j As Integer = 0 To UBound(a)
a(j) = a(j) + 1
Next j
End Sub
The first MsgBox call displays "After increase(n): 11, 21, 31, 41". Because n is a reference type, increase can change its
members, even though it is passed ByVal.
The second MsgBox call displays "After replace(n): 11, 21, 31, 41". Because n is passed ByVal, replace cannot modify the
variable n by assigning a new array to it. When replace creates the new array instance k and assigns it to the local variable a, it
loses the reference to n passed in by the calling code. When it increments the members of a, only the local array k is affected.
Correct Approach: To be able to modify an underlying variable element itself, pass it by reference. The following example
shows the change in the declaration of replace that allows it to replace one array with another in the calling code.
VB
Public Sub replace(ByRef a() As Long)
VB
Dim r, s As Short
Call z(r, s)
Dim p As Byte, q As Short
' The following statement causes an overload resolution error.
Call z(p, q)
In the first call, the compiler eliminates the first overload because the type of the first argument (Short) narrows to the type of
the corresponding parameter (Byte). It then eliminates the third overload because each argument type in the second overload
(Short and Single) widens to the corresponding type in the third overload (Integer and Single). The second overload requires
less widening, so the compiler uses it for the call.
In the second call, the compiler cannot eliminate any of the overloads on the basis of narrowing. It eliminates the third
overload for the same reason as in the first call, because it can call the second overload with less widening of the argument
types. However, the compiler cannot resolve between the first and second overloads. Each has one defined parameter type that
widens to the corresponding type in the other (Byte to Short, but Single to Double). The compiler therefore generates an
overload resolution error.
Correct Approach: To be able to call an overloaded procedure without ambiguity, use CType Function to match the argument
data types to the parameter types. The following example shows a call to z that forces resolution to the second overload.
VB
Call z(CType(p, Short), CType(q, Single))
Overload Resolution with Optional and ParamArray Arguments
If two overloads of a procedure have identical signatures except that the last parameter is declared Optional (Visual Basic) in
one and ParamArray in the other, the compiler resolves a call to that procedure according to the closest match. For more
information, see Overload Resolution.
See Also
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Procedure Overloading
Considerations in Overloading Procedures
Overload Resolution
Visual Basic Language Concepts
Decision Structures
Visual Basic allows you to test conditions and perform different operations depending on the results of that test. You can test
for a condition being true or false, for various values of an expression, or for various exceptions generated when you execute a
series of statements.
The following illustration shows a decision structure that tests for a condition being true and takes different actions depending
on whether it is true or false.
Taking different actions when a condition is true and when it is false
If...Then...Else Construction
If...Then...Else constructions allow you to test for one or more conditions and run one or more statements depending on each
condition. You can test conditions and take actions in the following ways:
Run one or more statements if a condition is True
Run one or more statements if a condition is False
Run some statements if a condition is True and others if it is False
Test an additional condition if a prior condition is False
The control structure that offers all these possibilities is the If...Then...Else Statement (Visual Basic). You can use a single-line
version if you have just one test and one statement to run. If you have a more complex set of conditions and actions, you can
use the multiple-line version.
Select...Case Construction
The Select...Case construction allows you to evaluate an expression once and run different sets of statements based on
different possible values. For more information, see Select...Case Statement (Visual Basic).
Try...Catch...Finally Construction
Try...Catch...Finally constructions allow you to run a set of statements under an environment that retains control if any of
your statements causes an exception. You can take different actions for different exceptions. You can optionally specify a block
of code that is to run before you exit the entire Try...Catch...Finally construction, no matter what happens. For more
information, see Try...Catch...Finally Statement (Visual Basic).
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Statements Depending on One or More Conditions
How to: Test for Several Values of an Expression
How to: Retain Control When an Error Occurs
Concepts
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
Sub fixDate()
Dim myDate As Date = #2/13/1973#
If myDate < Now Then myDate = Now
End Sub
-or-
To execute more than one line of code when the condition is True, use the multiple-line syntax, which includes the End If
statement. If you have no code to run when the condition is False, you omit the Else statement. The following example
illustrates this.
Visual Basic tests the conditions in the order they appear in the If...Then...Else statements. When it encounters a True
condition or an Else statement, it runs the corresponding statement block. Control then passes to the statement
following the End If statement.
You can have any number of ElseIf statements, or none at all. You can include or omit one Else statement regardless of
whether you have any ElseIf statements.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Test for Several Values of an Expression
How to: Retain Control When an Error Occurs
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
Visual Basic compares the value of the expression to the values in the Case statements in the order they appear in the
Select...Case construction. If it finds a match or a Case Else statement, it runs the corresponding statement block. In any
case, it then branches to the statement following the End Select statement.
You can have any number of Case statements, and you can include or omit one Case Else statement regardless of
whether you have any Case statements.
A code example for the Select...Case construction is also available as an IntelliSense code snippet. In the code snippet picker, it
is located in Visual Basic Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Statements Depending on One or More Conditions
How to: Retain Control When an Error Occurs
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
The first three Catch blocks handle the exceptions that you can anticipate from the DateAdd Function (Visual Basic). You
can deal with any unexpected exception in the last Catch block.
No matter what happens, the Finally block is always the last code to be run before leaving the Try...Catch...Finally
construction. If you create or open resources such as objects or database connections in a Try or Catch block, you can
use the Finally block to close them and dispose of them, if appropriate.
If the exception variable thisExcep does not appear in a declaration statement such as Dim, the Catch statement with
the As clause serves as a declaration.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Statements Depending on One or More Conditions
How to: Test for Several Values of an Expression
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
Loop Structures
Visual Basic loop structures allow you to run one or more lines of code repetitively. You can repeat the statements in a loop
structure until a condition is True, until a condition is False, a specified number of times, or once for each element in a
collection.
The following illustration shows a loop structure that runs a set of statements until a condition becomes true.
Running a set of statements until a condition becomes true
While Loops
The While...End While construction runs a set of statements as long as the condition specified in the While statement is True.
For more information, see While...End While Statement (Visual Basic).
Do Loops
The Do...Loop construction allows you to test a condition at either the beginning or the end of a loop structure. You can also
specify whether to repeat the loop while the condition remains True or until it becomes True. For more information, see
Do...Loop Statement (Visual Basic).
For Loops
The For...Next construction performs the loop a set number of times. It uses a loop control variable, also called a counter, to
keep track of the repetitions. You specify the starting and ending values for this counter, and you can optionally specify the
amount by which it increases from one repetition to the next. For more information, see For...Next Statement (Visual Basic).
For Each Loops
The For Each...Next construction runs a set of statements once for each element in a collection. You specify the loop control
variable, but you do not have to determine starting or ending values for it. For more information, see
For Each...Next Statement (Visual Basic).
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Several Statements Repeatedly
How to: Run Several Statements for Each Element in a Collection or Array
How to: Improve the Performance of a Loop
How to: Skip to the Next Iteration of a Loop
Concepts
Decision Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
Sub checkWhile()
Dim counter As Integer = 0
Dim number As Integer = 10
While number > 6
number -= 1
counter += 1
End While
MsgBox("The loop ran " & counter & " times.")
End Sub
The While statement always checks the condition before it begins the loop. If number had been initialized to 6 instead of
10, the statements inside the loop would never run.
To run a group of statements while a condition remains True
Use the Do...Loop Statement (Visual Basic) and specify the testing condition at either the beginning or the end of the loop.
The placement of the While (Visual Basic) keyword determines where the condition is tested. The following example
illustrates this.
Sub checkWhileFirst()
Dim counter As Integer = 0
Dim number As Integer = 10
Do While number > 6
number -= 1
counter += 1
Loop
MsgBox("The loop ran " & counter & " times.")
End Sub
Sub checkWhileLast()
Dim counter As Integer = 0
Dim number As Integer = 5
Do
number -= 1
counter += 1
Loop While number > 6
MsgBox("The loop ran " & counter & " times.")
End Sub
In the preceding example, the first Do loop runs four times and the second Do loop runs one time.
To run a group of statements until a condition becomes True
Use the Do...Loop construction with the Until keyword instead of While. As with While, the placement of the keyword
determines where the condition is tested. The following example illustrates this.
Sub checkUntilFirst()
Dim counter As Integer = 0
Dim number As Integer = 20
Do Until number = 15
number -= 1
counter += 1
Loop
MsgBox("The loop ran " & counter & " times.")
End Sub
Sub checkUntilLast()
Dim counter As Integer = 0
Dim number As Integer = 20
Do
number -= 1
counter += 1
Loop Until number = 15
MsgBox("The loop ran " & counter & " times.")
End Sub
For i As Integer = 1 To 10
If the control variable is not declared outside the loop, you can use the As clause to declare it as part of the For statement.
2. Use the Step keyword to indicate the amount the control variable should increase for each iteration. It increases by 1
unless you specify otherwise. Use a negative value to cause the control variable to decrease.
3. Complete the For...Next construction with a Next statement following the last statement to be repeated. You can specify
the control variable in the Next statement.
The preceding example returns the sum of all the whole numbers from 1 through the value passed to the parameter
highest.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Several Statements for Each Element in a Collection or Array
How to: Improve the Performance of a Loop
How to: Skip to the Next Iteration of a Loop
Reference
For Each...Next Statement (Visual Basic)
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
If the element variable is not declared outside the loop, you can use the As clause to declare it as part of the For Each
statement.
Visual Basic automatically substitutes a different element of the collection for each iteration.
2. Complete the For Each...Next construction with a Next statement following the last statement to be repeated. You can
specify the element variable in the Next statement.
You can read the elements of the collection, but you cannot make any changes to the collection itself, such as adding,
deleting, or replacing any element. However, if an element is a reference type, you can access and set its members.
Because each Control element is a reference type, the code in the preceding example can change its BackColor property.
Repeating a Statement Block for an Array
You can also iterate through an array with a For Each...Next loop. However, as with collections, you can only read the array
elements, not change them.
To run a group of statements for each element of an array
1. Use the For Each statement to specify both the element variable and the array. Do not follow the array name with
parentheses.
Visual Basic treats the array the same way it treats a collection.
2. Follow the statement block with a Next statement. You can specify the element variable in the Next statement.
The following procedure is intended to find the sum of the elements of an array and reset each element to zero.
The summation works as intended because it relies only on reading the elements. However, the resetting to zero does
not work as intended, because only the local copy of each element is reset to zero, while the original element is left
unchanged in the original array.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Several Statements Repeatedly
How to: Improve the Performance of a Loop
How to: Skip to the Next Iteration of a Loop
Reference
For...Next Statement (Visual Basic)
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
The first case takes slightly less time to run than the second case. However, Integer can handle values only up to
2,147,483,647, and UInteger only up to 4,294,967,295. The second and third cases can handle larger values, because
both Long and Decimal accept a wider range of integers, but they run more slowly. You might have to make a design
decision between speed and capacity of the data types you use.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Several Statements Repeatedly
How to: Run Several Statements for Each Element in a Collection or Array
How to: Skip to the Next Iteration of a Loop
Reference
For...Next Statement (Visual Basic)
Concepts
Loop Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Several Statements Repeatedly
How to: Run Several Statements for Each Element in a Collection or Array
How to: Improve the Performance of a Loop
Reference
While...End While Statement (Visual Basic)
Do...Loop Statement (Visual Basic)
For...Next Statement (Visual Basic)
Concepts
Loop Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
' Insert the following line at the beginning of your source file.
Imports System.Data.SqlClient
Public Sub AccessSql(ByVal s As String)
Using sqc As New System.Data.SqlClient.SqlConnection(s)
MsgBox("Connected with string """ & sqc.ConnectionString & """")
End Using
End Sub
The system disposes of the resource no matter how you exit the block, including the case of an unhandled exception.
Note that you cannot access sqc from outside the Using block, because its scope is limited to the block.
You can use this same technique on a system resource such as a file handle or a COM wrapper. You use a Using block
when you want to be sure to leave the resource available for other components after you have exited the Using block.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Perform Multiple Actions on an Object
Reference
Using Statement (Visual Basic)
SqlConnection
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
Note the use of the Or Operator (Visual Basic) to combine font styles. This specifies the desired combination of bit flags. The
And Operator (Visual Basic) would have produced 0 because all the FontStyle enumeration members use different bits.
Note also the use of the Imports Statement to establish the import alias draw, which makes each reference to System.Drawing
members shorter and easier to read.
You can also nest With...End With statements by placing one inside another, as in the following code:
VB
Sub setupForm()
Dim anotherForm As New System.Windows.Forms.Form
Dim button1 As New System.Windows.Forms.Button
With anotherForm
.Show()
.Top = 250
.Left = 250
.ForeColor = System.Drawing.Color.LightBlue
.BackColor = System.Drawing.Color.DarkBlue
.Controls.Add(button1)
With .Controls.Item(1)
.BackColor = System.Drawing.Color.Thistle
.Text = "Text on button1"
End With
End With
End Sub
Within the nested With statement, however, the syntax refers to the nested object; properties of the object in the outer With
statement are not set.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Dispose of a System Resource
How to: Speed Up Access to an Object with a Long Qualification Path
Reference
With...End With Statement (Visual Basic)
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
In the preceding example, the first Next statement closes the inner For loop and the last Next statement closes the outer For
loop.
Likewise, in nested If statements, the End If statements automatically apply to the nearest prior If statement. Nested Do loops
work in a similar fashion, with the innermost Loop statement matching the innermost Do statement.
Nesting Different Kinds of Control Structures
You can nest one kind of control structure within another kind. The following example uses a With block inside a For Each
loop and nested If blocks inside the With block.
The Visual Basic compiler detects such overlapping control structures and signals a compile-time error.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
Concepts
Decision Structures
Loop Structures
Other Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
In the preceding example, the Exit For statement is located in the inner For loop, so it passes control to the statement
following that loop and continues with the outer For loop.
See Also
Tasks
How to: Label Statements
Reference
Exit Statement (Visual Basic)
GoTo Statement
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts
Understanding Classes
Classes are important in object-oriented programming because they allow you to group related items as a unit, as well as
control their visibility and accessibility to other procedures. Classes can also inherit and reuse code defined in other classes.
In This Section
Classes: Blueprints for Objects
Provides an overview of encapsulation, inheritance, and shared members.
Walkthrough: Defining Classes
Steps through the process of creating a class.
Classes vs. Modules
Explains the differences between classes and standard modules.
Object Lifetime: How Objects Are Created and Destroyed
Discusses creating and disposing of class instances.
How to: Implement the Dispose Finalize Pattern (Visual Basic)
Explains how to ensure that an object's resources are released when they are no longer needed.
Using Constructors and Destructors
Discusses how to initialize new instances of classes and dispose of resources when they are no longer needed.
Class Properties, Fields, and Methods
Explains the fields, properties, and methods that make up a class.
Related Sections
Creating and Using Objects
Demonstrates how to create and use instances of classes.
Interfaces in Visual Basic
Describes what interfaces are and how to use them in your applications.
Inheritance in Visual Basic
Describes how to define classes that serve as the basis for other classes.
Visual Basic Language Concepts
To define a class
1. Create a project by clicking New Project on the File menu. The New Project dialog box appears.
2. Select Windows Application from the list of Visual Basic project templates to display the new project.
3. Add a new class to the project by clicking Add Class on the Project menu. The Add New Item dialog box appears.
4. Select the Class template.
5. Name the new class UserNameInfo.vb, and then click Add to display the code for the new class.
VB
Public Class UserNameInfo
End Class
Note
You can use the Visual Basic Code Editor to add a class to your startup form by typing the Class keyword followed by
the name of the new class. The Code Editor provides a corresponding End Class statement for you.
6. Define a private field for the class by placing the following code between the Class and End Class statements:
VB
Private userNameValue As String
Declaring the field as Private means it can be used only within the class. You can make fields accessible from outside a
class by using access modifiers such as Public that provide greater access. For more information, see
Access Levels in Visual Basic.
7. Define a property for the class by adding the following code:
VB
Public Property UserName() As String
Get
' Gets the property value.
Return userNameValue
End Get
Set(ByVal Value As String)
' Sets the property value.
userNameValue = Value
End Set
End Property
8. Define a method for the class by adding the following code:
VB
Public Sub Capitalize()
' Capitalize the value of the property.
userNameValue = UCase(userNameValue)
End Sub
9. Define a parameterized constructor for the new class by adding a procedure named Sub New:
VB
Public Sub New(ByVal UserName As String)
' Set the property value.
Me.UserName = UserName
End Sub
The Sub New constructor is called automatically when an object based on this class is created. This constructor sets the
value of the field that holds the user name.
Classes and modules also use different scopes for their members. Members defined within a class are scoped within a specific
instance of the class and exist only for the lifetime of the object. To access class members from outside a class, you must use
fully qualified names in the format of Object.Member.
On the other hand, members declared within a module are publicly accessible by default, and can be accessed by any code that
can access the module. This means that variables in a standard module are effectively global variables because they are visible
from anywhere in your project, and they exist for the life of the program.
See Also
Reference
Shared (Visual Basic)
Concepts
Structures and Classes
Shared Members in Visual Basic
Other Resources
Understanding Classes
Visual Basic Language Concepts
The Finalize destructor is a protected method that can be called only from the class it belongs to, or from derived classes. The
system calls Finalize automatically when an object is destroyed, so you should not explicitly call Finalize from outside of a
derived class's Finalize implementation.
Unlike Class_Terminate, which executes as soon as an object is set to nothing, there is usually a delay between when an object
loses scope and when Visual Basic 2005 calls the Finalize destructor. Visual Basic 2005 allows for a second kind of destructor,
Dispose, which can be explicitly called at any time to immediately release resources.
Note
A Finalize destructor should not throw exceptions, because they cannot be handled by the application and can cause the app
lication to terminate.
IDisposable Interface
Class instances often control resources not managed by the CLR, such as Windows handles and database connections. These
resources must be disposed of in the Finalize method of the class, so that they will be released when the object is destroyed
by the garbage collector. However, the garbage collector destroys objects only when the CLR requires more free memory. This
means that the resources may not be released until long after the object goes out of scope.
To supplement garbage collection, your classes can provide a mechanism to actively manage system resources if they
implement the IDisposable interface. IDisposable has one method, Dispose, which clients should call when they finish using
an object. You can use the Dispose method to immediately release resources and perform tasks such as closing files and
database connections. Unlike the Finalize destructor, the Dispose method is not called automatically. Clients of a class must
explicitly call Dispose when you want to immediately release resources.
Implementing IDisposable
A class that implements the IDisposable interface should include these sections of code:
A field for keeping track of whether the object has been disposed:
Protected disposed As Boolean = False
An overload of the Dispose that frees the class's resources. This method should be called by the Dispose and Finalize
methods of the base class:
An override of the Finalize method that contains only the following code:
A derived class should not override the base class's Dispose and Finalize methods. When those methods are called from an
instance of the derived class, the base class's implementation of those methods call the derived class's override of the
Dispose(disposing) method.
Visualization
The following diagram shows which methods are inherited and which methods are overridden in the derived class.
When this Dispose Finalize pattern is followed, the resources of the derived class and base class are correctly disposed. The
following diagram shows which methods get called when the classes are disposed and finalized.
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
Access to the members of the System and System.ComponentModel namespaces. Add an Imports statement if you are
not fully qualifying member names in your code. For more information, see Imports Statement.
These changes must be made in the code:
Replace ResourceClass with the name of the class that implements IDisposable.
Use the test in AnyOtherMethods in any methods using resources that may have been disposed of.
Replace the managedResource declaration with declarations of any managed objects in your class that need to be
disposed of. If a class implements IDisposable or has a Close method, it probably needs to be disposed of. In the
Dispose method, close or dispose of these objects.
Replace the unManagedResource declaration with declarations of unmanaged objects in your class that need to be
disposed of. The method for disposing of these objects depends on how the object is defined. For details, consult the
documentation on the object.
Robust Programming
Once the Dispose method has been called, contained objects in your collection will not be valid. You should test the disposed
field before performing any operations on your object. For an example, see the AnyOtherMethods method in the code example.
See Also
Reference
IDisposable
Concepts
Implementing a Dispose Method
Other Resources
Garbage Collection
Visual Basic Language Concepts
When you define a class derived from another class, the first line of a constructor must be a call to the constructor of the base
class, unless the base class has an accessible constructor that takes no parameters. A call to the base class containing the above
constructor, for example, would be MyBase.New(s). Otherwise, MyBase.New is optional, and the Visual Basic runtime calls it
implicitly.
After writing code to call the parent object's constructor, you can add any additional initialization code to the Sub New
procedure. Sub New can accept arguments when called as a parameterized constructor. These parameters are passed from
the procedure calling the constructor, for example, Dim AnObject As New ThisClass(X).
Destructors
The following code shows how to use Dispose and Finalize to release resources in a base class.
Note
You should follow the guidelines for implementing IDisposable set out in
Object Lifetime: How Objects Are Created and Destroyed.
VB
' Design pattern for a base class.
Public Class Base
Implements IDisposable
' Keep track of when the object is disposed.
Protected disposed As Boolean = False
The following code shows how to use Dispose and Finalize to release resources in a derived class.
VB
' Design pattern for a derived class.
Public Class Derived
Inherits Base
' This method disposes the derived object's resources.
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposed Then
If disposing Then
' Insert code to free unmanaged resources.
End If
' Insert code to free shared resources.
End If
MyBase.Dispose(disposing)
End Sub
The following code shows a common design pattern for the Dispose destructor, using a Using block and an equivalent
Try...Finally block.
VB
Sub DemonstrateUsing()
Using d As New Derived
' Code to use the Derived object goes here.
End Using
End Sub
Sub DemonstrateTry()
Dim d As Derived = Nothing
Try
d = New Derived
' Code to use the Derived object goes here.
Finally
' Call the Dispose method when done, even if there is an exception.
If Not d Is Nothing Then
d.Dispose()
End If
End Try
End Sub
The next example creates an object using a parameterized constructor, and then calls destructors when the object is no longer
needed.
Note
Although this example uses Collect to demonstrate which methods the garbage collector calls to dispose methods, in general
you should let the common language runtime (CLR) manage garbage collection.
VB
Sub TestConstructorsAndDestructors()
' Demonstrate how the Using statement calls the Dispose method.
Using AnObject As New ThisClass(6)
' Place statements here that use the object.
MsgBox("The value of ThisProperty after being initialized " & _
" by the constructor is " & AnObject.ThisProperty & ".")
End Using
' Demonstrate how the garbage collector calls the Finalize method.
Dim AnObject2 As New ThisClass(6)
AnObject2 = Nothing
GC.Collect()
End Sub
End Class
When you run this example, the class ThisClass calls the Sub New constructor of the class BaseClass. After the constructor in
the base class is finished, the class ThisClass runs the remaining statements in Sub New that initialize a value for the property
ThisProperty.
When the class is no longer needed, the Dispose destructor is called in ThisClass.
This example displays the following:
BaseClass is initializing with Sub New.
ThisClass is initializing with Sub New.
The value of ThisProperty after being initialized by the constructor is 6.
ThisClass is shutting down with Sub Dispose.
ThisClass is shutting down with the Sub Dispose overload.
BaseClass is shutting down with Sub Finalize.
BaseClass is initializing with Sub New.
ThisClass is initializing with Sub New.
ThisClass is shutting down with Sub Finalize.
ThisClass is shutting down with the Sub Dispose overload.
BaseClass is shutting down with Sub Finalize.
See Also
Reference
Dispose
Concepts
Object Lifetime: How Objects Are Created and Destroyed
Finalize Methods and Destructors
How New and Finalize Methods Work in a Class Hierarchy
Visual Basic Language Concepts
See Also
Tasks
How to: Add Events to a Class
Reference
Property Statement
Public (Visual Basic)
Shared (Visual Basic)
Concepts
Properties and Property Procedures
Visual Basic Language Concepts
' The attempt to set the field to a value greater than 10 will silently fail.
NewClass.ThisProperty = 36
' The next statement will print the old value of 0 instead.
MsgBox("ThisProperty = " & NewClass.ThisProperty)
End Sub
The procedure TestFieldsAndProperties creates an instance of the class and sets and retrieves the values of the fields and
properties. For the sake of this example, it is assumed that the only valid values are numbers less than 10. Because there is no
way to validate values assigned to fields, setting the field to value 36 is allowed. The property, however, only performs
assignment for numbers less than 10, so the attempt to set it to 36 is ignored.
Read-Only and Write-Only Properties
Most properties have both Get and Set property procedures you can use to read and modify the value stored inside. However,
you can use the ReadOnly or WriteOnly modifiers to restrict properties from being modified or read.
Read-only properties cannot have Set property procedures; such properties are useful for items that you want to expose, but
not allow to be modified. For example, you could use a read-only property to provide the processor speed of a computer.
Write-only properties cannot have Get property procedures and are useful for configuring objects with data that should not or
cannot be stored in the object. For example, a write-only property could be used to take a password and change the object's
state without storing the password.
Note
Previous versions of Visual Basic support Let property procedures for use when assigning objects to properties. Visual Basic
eliminates the need for Let property procedures because object assignment is handled like any other kind of assignment.
See Also
Reference
Get Statement
Set Statement (Visual Basic)
ReadOnly (Visual Basic)
WriteOnly
Concepts
Property Procedures
Property Procedures vs. Fields
Visual Basic Language Concepts
Class Methods
The methods of a class are just Sub or Function procedures declared within the class. For example, to create a Withdrawal
method for a class named Account, you could add this Public function to the class module:
VB
Public Function WithDrawal(ByVal Amount As Decimal, _
ByVal TransactionCode As Byte) As Double
' Add code here to perform the withdrawal,
' return a transaction code,
' or to raise an overdraft error.
End Function
Shared Methods
Shared methods can be invoked directly from the class without first creating an instance of the class. Shared methods are
useful when you do not want a method to be associated with a specific instance of a class. Shared methods cannot be declared
using the Overridable, NotOverridable, or MustOverride modifiers. Methods declared in modules are implicitly shared and
cannot explicitly use the Shared modifier.
Example
VB
Class ShareClass
Shared Sub SharedSub()
MsgBox("Shared method.")
End Sub
End Class
Sub Test()
' Call the method.
ShareClass.SharedSub()
End Sub
Default Properties
A property that accepts arguments can be declared as the default property for a class. A default property is the property that
Visual Basic will use when no specific property has been named for an object. Default properties are useful because they allow
you to make your source code more compact by omitting frequently used property names.
The best candidates for default properties are those properties that accept parameters and that you think will be used the most
often. For example, the Item property is a good choice for the default property of a collection class because it is used
frequently.
The following rules apply to default properties:
A type can have only one default property, including properties inherited from a base class. There is one exception to this
rule. A default property defined in a base class can be shadowed by another default property in a derived class.
If a default property from a base class is shadowed by a non-default property in a derived class, the default property is
still accessible using default property syntax.
A default property may not be Shared or Private.
If an overloaded property is a default property, all overloaded properties with that same name must also specify Default.
Default properties must accept at least one argument.
Example
The following example declares a property that contains an array of strings as the default property for a class:
VB
Class Class2
' Define a local variable to store the property value.
Private PropertyValues As String()
' Define the default property.
Default Public Property Prop1(ByVal Index As Integer) As String
Get
Return PropertyValues(Index)
End Get
Set(ByVal Value As String)
If PropertyValues Is Nothing Then
' The array contains Nothing when first accessed.
ReDim PropertyValues(0)
Else
' Re-dimension the array to hold the new element.
ReDim Preserve PropertyValues(UBound(PropertyValues) + 1)
End If
PropertyValues(Index) = Value
End Set
End Property
End Class
See Also
Reference
Default (Visual Basic)
Concepts
Upgrade Recommendation: Resolve Parameterless Default Properties
Default Property Changes for Visual Basic 6.0 Users
Visual Basic Language Concepts
Without overloading, you would need to create distinct names for each procedure, even though they do the same thing, as
shown next:
VB
Sub DisplayChar(ByVal theChar As Char)
' Add code that displays Char data.
End Sub
Sub DisplayInt(ByVal theInteger As Integer)
' Add code that displays Integer data.
End Sub
Sub DisplayDouble(ByVal theDouble As Double)
' Add code that displays Double data.
End Sub
Overloading makes it easier to use properties or methods because it provides a choice of data types that can be used. For
example, the overloaded Display method discussed previously can be called with any of the following lines of code:
VB
' Call Display with a literal of type Char.
Display("9"c)
' Call Display with a literal of type Integer.
Display(9)
' Call Display with a literal of type Double.
Display(9.9R)
At run time, Visual Basic calls the correct procedure based on the data types of the parameters you specify.
Note
Overloading, overriding, and shadowing are similar concepts that can be easy to confuse. For more information, see
Introduction to Objects in Visual Basic.
Overloading Rules
You create an overloaded member for a class by adding two or more properties or methods with the same name. Except for
overloaded derived members, each overloaded member must have different parameter lists, and the following items cannot be
used as a differentiating feature when overloading a property or procedure:
Modifiers, such as ByVal or ByRef, that apply to a member, or parameters of the member.
Names of parameters
Return types of procedures
The Overloads keyword is optional when overloading, but if any overloaded member uses the Overloads keyword, then all
other overloaded members with the same name must also specify this keyword.
Derived classes can overload inherited members with members that have identical parameters and parameter types, a process
known as shadowing by name and signature. If the Overloads keyword is used when shadowing by name and signature, the
derived class's implementation of the member will be used instead of the implementation in the base class, and all other
overloads for that member will be available to instances of the derived class.
If the Overloads keyword is omitted when overloading an inherited member with a member that has identical parameters and
parameter types, then the overloading is called shadowing by name. Shadowing by name replaces the inherited
implementation of a member, and it makes all other overloads unavailable to instances of the derived class and its decedents.
The Overloads and Shadows modifiers cannot both be used with the same property or method.
Example
The following example creates overloaded methods that accept either a String or Decimal representation of a dollar amount
and return a string containing the sales tax.
To use this example to create an overloaded method
1. Open a new project and add a class named TaxClass.
2. Add the following code to the TaxClass class.
VB
Public Class TaxClass
Overloads Function TaxAmount(ByVal decPrice As Decimal, _
ByVal TaxRate As Single) As String
TaxAmount = "Price is a Decimal. Tax is $" & _
(CStr(decPrice * TaxRate))
End Function
4. Add a button to your form and call the ShowTax procedure from the Button1_Click event of the button.
5. Run the project and click the button on the form to test the overloaded ShowTax procedure.
At run time, the compiler chooses the appropriate overloaded function that matches the parameters being used. When you
click the button, the overloaded method is called first with a Price parameter that is a string and the message, "Price is a
String. Tax is $5.12" is displayed. TaxAmount is called with a Decimal value the second time and the message, "Price is a
Decimal. Tax is $5.12" is displayed.
See Also
Reference
Sub Statement (Visual Basic)
Shadows
ByVal
ByRef
Overloads
Shadows
Concepts
Shadowing in Visual Basic
Introduction to Objects in Visual Basic
Overriding Properties and Methods
Visual Basic Language Concepts
Example
Suppose you want to define classes to handle payroll. You could define a generic Payroll class that contains a RunPayroll
method that calculates payroll for a normal week. You could then use Payroll as a base class for a more specialized
BonusPayroll class, which could be used when distributing employee bonuses.
The BonusPayroll class can inherit, and override, the PayEmployee method defined in the base Payroll class.
The following example defines a base class, Payroll, and a derived class, BonusPayroll, which overrides an inherited method,
PayEmployee. A procedure, RunPayroll, creates and then passes a Payroll object and a BonusPayroll object to a function, Pay,
that executes the PayEmployee method of both objects.
VB
Const BonusRate As Decimal = 1.45D
Const PayRate As Decimal = 14.75D
Class Payroll
Overridable Function PayEmployee( _
ByVal HoursWorked As Decimal, _
ByVal PayRate As Decimal) _
As Decimal
Class BonusPayroll
Inherits Payroll
Overrides Function PayEmployee( _
ByVal HoursWorked As Decimal, _
ByVal PayRate As Decimal) _
As Decimal
' The following code calls the original method in the base
' class, and then modifies the returned value.
PayEmployee = MyBase.PayEmployee(HoursWorked, PayRate) * BonusRate
End Function
End Class
Sub RunPayroll()
Dim PayrollItem As Payroll = New Payroll
Dim BonusPayrollItem As New BonusPayroll
Dim HoursWorked As Decimal = 40
See Also
Concepts
Overloaded Properties and Methods
Override Modifiers
Shadowing in Visual Basic
Other Resources
Polymorphism
Visual Basic Language Concepts
Override Modifiers
You can use the NotOverridable and MustOverride modifiers in a base class to control how derived classes override its
properties and methods.
The NotOverridable modifier defines a method of a base class that cannot be overridden in derived classes. All methods are
NotOverridable unless marked with the Overridable modifier. You can use the NotOverridable modifier when you do not
want to allow an overridden method to be overridden again in a derived class.
Methods defined with the MustOverride modifier have no implementation in the base class and must be implemented in
derived classes. Classes that contain MustOverride methods must be marked with the MustInherit modifier.
Example
VB
MustInherit Class BaseClass
Public MustOverride Sub aProcedure()
End Class
Class DerivedClass
Inherits BaseClass
Public NotOverridable Overrides Sub aProcedure()
' Override a procedure inherited from the base class
' and mark it with the NotOverridable modifier so that
' it cannot be overridden in classes derived from this class.
End Sub
End Class
See Also
Concepts
Overloaded Properties and Methods
Visual Basic Language Concepts
Note
You can also set a property by passing it to ByRef parameters, in which case the property is modified by the result retu
rned by the ByRef parameter.
See Also
Tasks
How to: Perform Actions with Methods
Concepts
Objects from Visual Basic and Other Sources
Other Resources
Creating and Using Objects
Visual Basic Language Concepts
Note
Some methods, such as Refresh, do not have arguments and do not return values.
This example uses the value returned from the Len method as an argument to MsgBox.
VB
Dim TestStr As String = "Some String"
' Display the string "String length is : 11".
MsgBox("String length is : " & Len(TestStr))
See Also
Tasks
How to: Set and Retrieve Properties
Concepts
Relationships Among Objects
Other Resources
Creating and Using Objects
Visual Basic Language Concepts
2. Assign the form to an object variable. The object variable references a new instance of the form class.
The following example correctly calls the PrintMyJob procedure:
VB
Dim newForm1 As New Form1
newForm1.PrintMyJob()
In the previous example, the new form is not displayed. It is not necessary to show a form object to use its methods. To
display the new form, you need to add the following code:
VB
newForm1.Show()
See Also
Tasks
How to: Use the New Keyword
Concepts
Property Procedures
Visual Basic Language Concepts
If Form1 does not already exist, Visual Basic creates it for you. You do not have to declare a variable for it.
VB
Public Sub GetSecondInstance()
Dim newForm1 As New Form1
newForm1.BackColor = System.Drawing.Color.YellowGreen
newForm1.Show()
End Sub
If you want to display two or more copies of the same form, you must create the additional copies. The preceding
example creates a second copy of Form1 and paints it a different color. You can then access the original copy using Form1
and the second copy using newForm1.
See Also
Reference
New (Visual Basic)
System.Drawing
Form
Visual Basic Language Concepts
The first statement declares an object variable that can contain a reference to a button object. However, the variable Button1
contains the value Nothing until you assign an object of type Button to it. The second statement also defines a variable that
can contain a button object, but the New keyword creates a button object and assigns it to the variable Button2.
Because forms and controls are actually classes, you can use the New keyword to create new instances of these items as
needed.
To create new instances of a class with New
1. Open a new Windows Application project and place a command button and several other controls on a form named
Form1.
2. Add the following code to the command button's Click event procedure:
VB
Dim f As New Form1
f.Show()
3. Run the application, and click the command button several times.
4. Move the front form aside. Because a form is a class with a visible interface, you can see the additional copies. Each copy
has the same controls, in the same positions as those on the original form at design time.
You can use the New keyword to create objects from within classes. The following procedure provides an example.
To see how New creates instances of a class
1. Open a new project, and place a command button on a form named Form1.
2. From the Project menu, choose Add Class to add a class to the project.
3. Name the new class ShowMe.vb.
4. Add the following procedure to ShowMe:
VB
Public Class ShowMe
Sub ShowFrm()
Dim frmNew As Form1
frmNew = New Form1
frmNew.Show()
frmNew.WindowState = FormWindowState.Minimized
End Sub
End Class
5. Add the following code to handle the Click event of Button1 on your form:
VB
Protected Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim clsNew As New ShowMe
clsNew.ShowFrm()
End Sub
6. To use the example, run the application and click the command button several times. A minimized form icon appears on
your taskbar as each new instance of the ShowMe class is created.
See Also
Other Resources
Creating and Using Objects
Visual Basic Language Concepts
Resource Management
All objects consume system resources such as memory, file handles, and database connections. The Common Language
Runtime (CLR) manages resources automatically, and usually you do not need to worry about releasing unneeded objects.
However, understanding how resource management works can help you design your applications to be more efficient.
Garbage Collection
The CLR uses a system called garbage collection to manage allocated resources. The system garbage collector releases an
object's resources when that object can no longer be reached by any running code in your application. The garbage collection
algorithm is nondeterministic, so you cannot determine when the CLR will release an object's resources. The following sections
describe some of the changes to the way resources are managed in Visual Basic.
Assigning Objects to Nothing
Nothing is a keyword used by Visual Basic to indicate that an object variable does not contain a reference to an object.
Previous versions of Visual Basic encouraged you to assign unused objects to Nothing to disassociate the object variable from
the object and release resources. You can still assign unused objects to Nothing, but because of the way Visual Basic manages
resources, this process does not guarantee that objects will be released immediately. Generally speaking, you should only
assign long-lived objects—such as shared members or global variables—to Nothing.
Dispose
Some objects support a method named Dispose; its purpose is to release system resources more expeditiously. Classes that
support the Dispose method must implement the IDisposable interface. The Dispose method needs to be explicitly called
when you want to release object resources. For example:
ThisObject.Dispose()
Finalize
Another method supported by some classes, Finalize, runs automatically when an object is released and can be used to
perform other cleanup tasks. The Finalize method is similar to the Class_Terminate() method used in previous versions of
Visual Basic. After an object becomes inaccessible, the CLR will eventually call the object's Finalize method. Because the
garbage collection algorithm is nondeterministic, the Finalize method might be called immediately, or it might be called
several hours later.
See Also
Reference
Nothing (Visual Basic)
Dispose
IDisposable
Concepts
Object Lifetime: How Objects Are Created and Destroyed
Initialization and Termination of Components
Visual Basic Language Concepts
You can also pass an object as an argument by reference and then, inside the procedure, set the argument to a new
object.
To pass an object reference to a procedure on another form
1. Open a project and create a form named Form1.
2. Add a second form named Form2.
3. Place a picture box control on each form.
4. Name the picture box on Form1 PictureBox1.
5. Name the picture box on Form2 PictureBox2.
6. Assign a picture to PictureBox2 by clicking the Image property in the Properties window. Any small images will work;
you can find .bmp and .jpg files in your Windows directory.
7. Add the following code to Form2:
VB
Public Sub GetPicture(ByVal x As PictureBox)
Dim objX As PictureBox
' Assign the passed-in picture box to an object variable.
objX = x
' Assign the value of the Picture property to the Form1 picture box.
objX.Image = PictureBox2.Image
End Sub
8. Add the following code to the Form1_Click event on Form1:
VB
Protected Sub Form1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
Dim newForm2 As New Form2
newForm2.GetPicture(PictureBox1)
End Sub
9. Run the application and click Form1. The picture from Form2 appears in the picture box on Form1.
The Form1_Click event procedure calls the GetPicture procedure in Form2, and passes the empty picture box to it. The
GetPicture procedure in Form2 assigns the Image property of the picture box on Form2 to the empty picture box on
Form1, and the image from Form2 is displayed on Form1.
See Also
Concepts
Resource Management
Other Resources
Object-Oriented Programming in Visual Basic
Programming with Components
Visual Basic Language Concepts
Security Note
This example stores data in a binary or SOAP format file. These formats should not be used for sensitive data, such as passw
ords or credit card information.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
You will also need to create a simple application that uses the Loan class.
To create a test application
1. From the File menu, add a Windows Application project to your solution by pointing to Add and then clicking New
Project.
2. In the Add New Project dialog box, enter LoanApp as the name of the project, and click OK to close the dialog box.
3. In Solution Explorer, select the LoanApp project.
4. On the Project menu, click Set as StartUp Project.
5. On the Project menu, click Add Reference.
6. In the Add Reference dialog box, click the Projects tab and select the LoanClass project.
7. Click OK to close the dialog box.
8. In the designer, add four TextBox controls to the form.
9. In the Code Editor, add the following code:
VB
Private TestLoan As New LoanClass.Loan
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
TextBox1.Text = TestLoan.LoanAmount.ToString
TextBox2.Text = TestLoan.InterestRate.ToString
TextBox3.Text = TestLoan.Term.ToString
TextBox4.Text = TestLoan.Customer
End Sub
At this point, you can build and run the application. Note that the default values from the Loan class appear in the text boxes.
Try changing the interest-rate value from 7.5 to 7.1, then close the application and run it again—the value reverts to the default
of 7.5.
In the real world, interest rates change periodically, but not necessarily every time the application is run. Rather than making
the user update the interest rate each time the application is run, it would be better to preserve the most recent interest rate
between instances of the application. In the next step, you will do just that by adding serialization to the Loan class.
Using Serialization to Persist the Object
In order to persist the values for the Loan class, you must first mark the class with the Serializable attribute.
To mark a class as serializable
Change the class declaration for the Loan class as follows:
VB
<Serializable()> Public Class Loan
The Serializable attribute tells the compiler that everything within the class can be persisted to a file. In this case, you want to
persist only the InterestRate member, but you probably do not want to persist the Customer, LoanAmount, or Period
members. The NonSerialized attribute can be used to mark class members that should not be persisted. For simplicity in this
example, everything except the Customer member is persisted.
To prevent a member from being serialized
Change the declaration for the Customer member as follows:
VB
<NonSerialized()> Public Customer As String
The next step is to add the serialization code to the LoanApp application. In order to serialize the class and write it to a file, you
will use the System.IO and System.Xml.Serialization namespaces. To avoid typing the fully qualified names, you can use the
Imports statement.
To add references to namespaces
Add the following Imports statements to the top of the Form1 class:
VB
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
In this case, you are using a binary formatter to save the object in a binary format. Later in this walkthrough, you will
modify the code to save the object in a SOAP format.
The next step is to add code to deserialize the object from the file when the object is created.
To deserialize an object
1. Add a constant to the class for the serialized data's file name.
VB
Const FileName As String = "SavedLoan.bin"
Note that you first need to check that the file exists. If it exists, create a Stream class to read the binary file and a
BinaryFormatter class to translate the file. The CType method is used to convert from the stream to the Loan object type.
Next you need to add code to save the data entered in the text boxes to the Loan class, and then you need to serialize the class
to a file.
To save the data and serialize the class
Add the following code to the Form1_Closing event procedure:
VB
Private Sub Form1_Closing(ByVal sender As System.Object, ByVal e As _
System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
TestLoan.LoanAmount = CType(TextBox1.Text, Double)
TestLoan.InterestRate = CType(TextBox2.Text, Double)
TestLoan.Term = CType(TextBox3.Text, Integer)
TestLoan.Customer = TextBox4.Text
At this point, you can once again build and run the application. Initially the default values appear in the text boxes. Try changing
the values and entering a name in the fourth text box. Close the application and then run it again. Note that the new values
now appear in the text boxes, except for the customer name that was marked as NonSerialized.
Persisting the Object Using a SOAP Format
The example so far has demonstrated how to persist an object to a text file using a binary format. A binary format is fine for
most Windows applications. For Web applications or XML Web services, you may want to persist the object to an XML file
using a SOAP format, which makes the object easy to share.
In order to persist the object to a SOAP format, you must first reference the SoapFormatter class. The SoapFormatter class
resides in its own namespace: System.Runtime.Serialization.Formatters.Soap.
To persist the object using SOAP format
1. In Solution Explorer, select the LoanApp project.
2. On the Project menu, click Add Reference.
3. In the Add Reference dialog box, click the .NET tab and select the System.Runtime.Serialization.Formatters.Soap
component.
4. Click OK to close the dialog box.
5. In the Code Editor, add an Imports statement to the top of the Form1 module:
VB
Imports System.Runtime.Serialization.Formatters.Soap
VB
Dim deserializer As New SoapFormatter
8. In the Form1_Closing event procedure, change the Dim statement from Dim serializer As New BinaryFormatter to:
VB
Dim serializer As New SoapFormatter
At this point, you can build and test the application. When you first run the application, the SavedLoan.xml file is created. You
can view this file by choosing the Show All Files option in Solution Explorer; it will be in the Bin node for the Windows
Application project.
Note
If you are already in Show All Files mode, you need to refresh the view by choosing Refresh from the View menu in order t
o see the file.
Note that the three members of the LoanClass are displayed in XML format. Try changing the InterestRate value in the XML
file, then save it and run the application again. The new interest rate appears in the second text box.
See Also
Concepts
PropertyBag Equivalents for Visual Basic 6.0 Users
Basics of .NET Framework Serialization
Visual Basic Language Concepts
See Also
Tasks
How to: Draw an Outlined Shape
Reference
NotInheritable
Other Resources
Inheritance in Visual Basic
Creating and Using Objects
Visual Basic: Samples
How to: Read Object Data from an XML File in Visual Basic
This example reads object data that was previously written to an XML file using the XmlSerializer class.
Example
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in XML. For more
information, see How to: Insert Snippets Into Your Code (Visual Basic).
VB
Public Class Book
Public Title As String
Public Sub New()
End Sub
End Class
The collections are incompatible because the Controls collection is a .NET Framework collection, while the variable
localControls is a Visual Basic Collection. The two kinds of collections are implemented from different classes. Their
methods are similar but not identical, and their indexing schemes are different.
Zero-Based and One-Based Collections
A collection can be zero-based or one-based, depending on what its starting index is. The former means that the index of the
first item in the collection is 0, and the latter means that it is 1. An example of a zero-based collection is the .NET
Framework Controls collection, discussed earlier on this page. The Visual Basic Collection object is an example of a one-
based collection.
One-based collections can be more intuitive to Visual Basic users, because the index ranges from 1 through the value of the
Count Property (Collection Object), which returns the number of items in a collection. The index of a zero-based collection, by
contrast, ranges from 0 through one less than the value of the Count property. This can be appropriate when the index values
are offsets from a base value or correspond to members of a zero-based enumeration.
.NET Framework collections are zero-based for the purpose of standardization. The Visual Basic Collection class is one-based
for the purpose of compatibility with previous versions.
Index and Key Values
Instances of the Visual Basic Collection class allow you to access an item using either a numeric index or a String key. You can
add items to Visual Basic Collection objects either with or without specifying a key. If you add an item without a key, you must
use its numeric index to access it.
By contrast, collections such as System.Collections.ArrayList allow only a numeric index. You cannot associate keys with the
elements of these collections, unless you construct your own mapping based, for example, on a String array holding the keys.
Adding and Removing Items
Collections also differ in whether or not you can add items to them, and if so, how those items are added. Because the Visual
Basic Collection object is a general-purpose programming tool, it is more flexible than some other collections. It has an
Add Method (Collection Object) for putting items into the collection and a Remove Method (Collection Object) for taking items
out.
Certain specialized collections, on the other hand, do not allow you to add or remove elements using code. For example, the
System.Windows.Forms.CheckedListBox.CheckedItems property returns a collection of references to items by index, but your
code cannot add or remove items from the collection. Only the user can do this — by selecting or clearing the appropriate box
in the user interface. Thus there is no Add or Remove method for this collection.
See Also
Tasks
How to: Create a Collection of Objects
How to: Create an Array of Objects
How to: Add, Delete, and Retrieve Items of a Collection
How to: Define Collections in Your Classes
How to: Iterate through a Collection in Visual Basic
Troubleshooting Collections
Concepts
Managing Groups of Objects
Visual Basic Collection Class
Managing Your Objects with Collections
Visual Basic Language Concepts
In the preceding example, the widgetColl collection organizes and exposes all of the widget objects created through the
makeAWidget procedure. You can retrieve object references to each widget through the index of the collection. The size of the
collection is adjusted automatically as each new widget object is added. You can use the
For Each...Next Statement (Visual Basic) to iterate through the collection. If you want to give the widget object a key by which it
can be retrieved, you can supply a text string as the second parameter of the Add method.
The Visual Basic Collection object stores all its elements as type Object, so you can add an item of any data type. There is no
safeguard against inappropriate data types being added. To avoid this limitation, you can use the generic collections of the
System.Collections.Generic namespace. For more information, see How to: Create a Collection of Objects.
Creating and Destroying a Collection Object
The New (Visual Basic) keyword in the declaration for the variable widgetColl causes a Collection object to be created when
control passes to the declaration statement. Because Collection is a class, rather than a value type, you must create an
instance of it and keep a reference to that instance in a variable. This instance is a Visual Basic Collection Object.
Like any other object, a Collection object is marked for garbage collection (GC) when the last variable that contains a
reference to it is set to Nothing (Visual Basic) or goes out of scope. All the object references it contains are released when it is
reclaimed by garbage collection. For this reason, the variable widgetColl in the preceding example is declared in the parent
class, so that it exists throughout the life of the program.
A collection maintains references to the objects it controls but does not contain the objects themselves. Therefore, destroying a
Collection object does not destroy the objects it controls. Each individual object that had been an element of the collection
continues to exist until it is individually marked for garbage collection.
Working with Elements
The basic services of adding, deleting, and retrieving elements from a collection depend on keys and indexes. A key is a String
value. It could be a name, a driver's license number, a phone number, or simply an integer converted to a string. The Add
method allows you to associate a key with an element, as described in How to: Add, Delete, and Retrieve Items of a Collection.
An index in the Collection class is an integer between 1 and the number of items in the collection. The
Count Property (Collection Object) returns the current number of items. You can control the initial value of an item's index by
using the Before or After parameters when you call Add, but the index value could change as other items are added and
deleted. For more information, see Add Method (Collection Object).
You can remove a single element from a collection by passing either its key or its index to the
Remove Method (Collection Object). You can empty a collection and remove all elements with the
Clear Method (Collection Object).
Accessing Elements
You can pass a key value to the Contains Method (Collection Object) to test whether a collection contains an element with that
key. You can retrieve an element by passing either its key or its index to the Item Property (Collection Object).
You can use index values and the Item property to iterate over the items in a collection, or you can use the
For Each...Next Statement (Visual Basic). The following example shows two ways to give all the employees in a collection of
employee objects a 10 percent raise, assuming that the variable employeesColl contains a reference to a Collection object.
Option Strict On
' The following alternative uses the Count and Item properties.
Dim emp As employee
For counter As Integer = 1 To employeesColl.Count
emp = CType(employeesColl.Item(counter), employee)
emp.payRate *= 1.1
Next counter
' The following alternative uses the For Each...Next statements.
For Each emp As employee In employeesColl
emp.payRate *= 1.1
Next emp
However, if you have added one or more elements to employeesColl that are not of type employee, the For Each loop throws
an ArgumentException exception at run time.
Data Type of Elements
A Visual Basic Collection Object stores each item with data type Object. Therefore, the range of data types you can add to a
Collection object is the same as the range of data types you can store in an Object variable. This includes standard data types,
objects, and arrays, as well as user-defined structures and class instances.
Because the Collection object stores each item as an Object, the Item property returns an Object value. To use the item in
your code, you must typically convert from Object to the run-time data type of the item. The way you do this depends on the
setting of the type checking switch in the Option Strict Statement.
Implicitly Converting from Object
If Option Strict is Off, you can implicitly convert an element of the Collection to its appropriate data type, as shown in the
following example.
Option Strict On
Dim sampleColl As New Microsoft.VisualBasic.Collection()
Dim sampleString As String = "This is a string"
Dim aString As String
sampleColl.Add(sampleString)
' The following statements convert the collection item to a string.
Try
aString = CType(sampleColl.Item(1), String)
Catch ex As Exception
' Insert code to run if the collection item cannot be converted to String.
End Try
Additional Services
The properties and methods of the Collection object provide only the most basic services for collections. For example, the
Add method cannot check the type of an element being added to a collection, which you might want to do to ensure that the
collection contains only one kind of element. If you can ensure this in the Add method, you have a strongly-typed collection,
and you do not have to convert the return from the Item property to its run-time data type. This improves your performance.
You can provide more robust functionality — and additional properties, methods, and events — by creating your own
collection class, as described in How to: Define Collections in Your Classes.
See Also
Reference
Collection Object (Visual Basic)
Concepts
Collections as an Alternative to Arrays
Collections in Visual Basic
Visual Basic Language Concepts
The class widgetRepository now has a public collection to which you can add widget objects. You can then use a
For Each...Next Statement (Visual Basic) to process the collection elements, as the following code demonstrates.
The widgetColl collection defined in the preceding example is not strongly typed, which means you can add any type of
object to it, not just widget objects. This can lead to type safety problems. For example, suppose you add a String to the
collection, as in the following code.
If you do this, the For Each loop in the previous procedure throws an ArgumentException exception at run time because
an element of the collection is not of type widget.
We recommend that you define a generic class when you want to ensure type safety. For more information and an
example, see How to: Define Type-Safe Collections.
See Also
Tasks
How to: Define Type-Safe Collections
Reference
Option Strict Statement
Concepts
Visual Basic Collection Class
Collections in Visual Basic
Generic Types in Visual Basic
Visual Basic Language Concepts
However, this widgetColl collection is not strongly typed. You can add any type of element to it, not just widget objects. When
you retrieve an element, you might have to try to convert it to a widget. This can lead to type safety problems. For example,
suppose you add a String to the collection using the following code.
VB
Dim notWidget As String = "This is not a widget object!"
widgetColl.Add(notWidget)
If you do this, any subsequent attempt to retrieve that element throws an ArgumentException exception at run time because
the element of the collection is not of type widget.
Protecting Against Type Safety Problems
We recommend that you maximize type safety by defining a generic class. This enforces strong typing and also provides
flexibility in the particular data type it works with. For more information, see Generic Types in Visual Basic.
To define a type-safe collection in a class
Use one of the generic classes in the System.Collections.Generic namespace, for example List, for your collection class.
Then you can create a collection that is restricted to widget members only. The following example illustrates how the
declaration in the preceding example could be modified to create a generic collection.
VB
Public widgetColl As New System.Collections.Generic.List(Of widget)
When you do this, the strong typing allows you to add only widget items to the collection, and every element you
retrieve through the Item property is a widget object. Also because of this strong typing, the retrieving code can use all
the properties and methods exposed by widget.
-or-
Create your own collection class without using any predefined classes. Restrict your Add method to accept only widget
objects, and implement your Item property with a return type of widget. For more information, see
How to: Define Type-Safe Collections.
If Item returned elements of type Object, you would have explicit access only to the properties and methods defined on
the Object class. To access the widget members, you would have to either turn Option Strict Off or use the
CType Function to explicitly convert the returned element to widget, as in the following code.
VB
Dim nextWidget As widget
Try
nextWidget = CType(widgetColl.Item(1), widget)
Catch ex As Exception
' Insert code to run if the collection item is not a widget.
End Try
In either case, using Object elements in this way causes Visual Basic to employ late binding, which degrades your
performance.
Note that the Visual Basic Collection class accepts and returns Object elements, so it also has the disadvantages of
weak typing and late binding.
See Also
Reference
Option Strict Statement
System.Collections
System.Collections.Generic
System.Collections.Specialized
Concepts
Visual Basic Collection Class
Collections in Visual Basic
Generic Types in Visual Basic
Visual Basic Language Concepts
Note that when an element is removed from a Visual Basic Collection, the index values are renumbered from 1 through
the value of the Count Property (Collection Object).
To use For Each...Next to process the elements of your Visual Basic collection
1. Declare a variable of the type stored in the collection. For the preceding example, declare a variable of type String, as the
following example shows.
The sampleGenericColl variable holds a type-safe collection that accepts items and keys only of type String.
2. Use the System.Collections.Generic.Dictionary.Add( method to add elements to the collection. The following example
creates four String elements and adds them to the collection. It creates a unique String value as the key for each new
element and passes this value to the Add method.
If Not sampleGenericColl.Remove("thirdkey")
' Insert code to handle "thirdkey" not found in collection.
End If
You can use a For Each...Next statement to loop through and process the elements of a collection, as the following
procedure demonstrates.
2. Use a For Each...Next Statement (Visual Basic) to examine each element of the collection. The following example searches
for a particular string and displays it if found.
See Also
Tasks
How to: Create an Array of Objects
Reference
Collection Object (Visual Basic)
System.Collections
System.Collections.Generic
System.Collections.Specialized
Concepts
Visual Basic Collection Class
Visual Basic Language Concepts
2. Create each element of the array, or assign to each element a reference to an already existing object. The following
example demonstrates this.
Note that you can assign references to the same object to different elements of the array.
See Also
Tasks
How to: Create a Collection of Objects
Concepts
Managing Groups of Objects
Value Types and Reference Types
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts
For example, to add a work order object to a collection of work orders using the work order's ID property as its key, you
can make the following call.
workOrders.Add(woNew, woNew.ID)
The preceding call assumes that the ID property is a string. If it is a number (for example, a Long integer), use its ToString
method to convert it to the String value required for the Key argument.
workOrders.Add(woNew, woNew.ID.ToString())
The use of a key is optional. If you do not want to associate a key with the object in your collection, you may add it
without a key.
workOrders.Add(woNew)
You can use the optional Before and After arguments to maintain an ordered collection of objects. The item to be added
is placed in the collection before or after the item identified by the Before or After argument, respectively. For example,
setting Before equal to 1 inserts an item at the beginning of the collection, because Collection objects are 1-based.
workOrders.Add(woNew, woNew.ID, 1)
Similarly, the After argument adds an item after the specified index. The following example adds an item as the third
element.
workOrders.Add(woNew, woNew.ID,,2)
You can specify a value for either Before or After, but not both.
To delete an item from a collection
Use the Remove Method (Collection Object) and specify the item by either its Index or its Key.
object.Remove({Index | Key})
The Index argument is the position of the item you want to delete. The Key argument is the same string you used to add
the item to the collection. If the key of the third element in a collection is "W017493", you can use either of the following
two statements to delete it.
workOrders.Remove(3)
workOrders.Remove("W017493")
As with the Remove method, the Index argument is the item's position in the collection, and the Key argument is the
string used when the item was added. Using the same example as for the Remove method, either of the following
statements retrieves the third element in the collection.
woCurrent = workOrders.Item(3)
woCurrent = workOrders.Item("W017493")
Note
If you use numbers as keys, you must use their ToString methods to convert them to strings before passing them to th
e Add or Remove method, or to the Item property. A Visual Basic Collection object always assumes that a number is
an index, rather than a key string.
2. If you know the key at compile time, you can alternatively use the dictionary access operator (!) to access an element of
the collection without enclosing the key in quotation marks or parentheses. The preceding call could be written as
follows.
woCurrent = workOrders!W017493
See Also
Reference
Collection Object Members
Add Method (Collection Object)
Remove Method (Collection Object)
Clear Method (Collection Object)
Item Property (Collection Object)
Concepts
Visual Basic Collection Class
Collections as an Alternative to Arrays
Collections in Visual Basic
Visual Basic Language Concepts
See Also
Tasks
How to: Add, Delete, and Retrieve Items of a Collection
Reference
For Each...Next Statement (Visual Basic)
Concepts
Collections in Visual Basic
Visual Basic Language Concepts
Troubleshooting Collections
This page lists some common problems that can occur when working with collections.
Using the Wrong Type of Collection
There are several types of collections available to a Visual Basic developer: the Visual Basic Collection class and the collection
classes furnished by the .NET Framework. These classes are not compatible with each other. This means that if you declare a
variable to be of one type of collection, you cannot assign an object of another type to that variable. Also, you can access only
the methods and properties of the collection type you have declared.
The main differences between the Visual Basic and .NET Framework collection classes include the following:
Index Base. .NET Framework collections are zero-based, while the Visual Basic collection is one-based. This means that
the elements of a Visual Basic collection have index values from 1 through the value of the
Count Property (Collection Object), whereas the elements of a .NET Framework collection have index values from 0
through one less than the value of the collection's Count property.
Element Type. The Visual Basic collection supports elements of type Object, which is not type-safe because you can add
an element of any data type. This usually results in degraded performance because the compiler must box and unbox the
elements to convert them to and from the Object Data Type. Some of the .NET Framework collections also have elements
of type Object, but many others are strongly typed, meaning they support elements of a specific type, which makes them
type-safe and usually results in optimal performance.
Keyed Elements. The Visual Basic collection allows you to specify a key when you add an element to it. The key is a
unique String value which you can use later to access that particular element. The .NET Framework collections vary in
regard to keys. Some support keys and some do not.
The namespaces that contain the various collection class definitions are the following:
Microsoft.VisualBasic — the Visual Basic Collection class
System.Collections — specific collection classes such as lists, queues, bit arrays, hash tables, and dictionaries
System.Collections.Generic — generic collection classes, which allow you to create strongly typed collections and specify
the element data type when you create them
System.Collections.Specialized — specialized and strongly typed collection classes, such as linked-list and hybrid
dictionaries, bit-vector and name-object collections, and string-only collections
Correct Approach
Determine which type of collection is most appropriate for your needs. Declare your collection variable to be of that type, and
be sure to create an object of that same type. Use full qualification to ensure that you are specifying the collection type you
intend to. The following example shows two declarations with full qualification.
VB
Dim customers As New Microsoft.VisualBasic.Collection()
Dim stringQueue As New System.Collections.Generic.Queue(Of String)
Once you have created a collection of a specific type, be sure you use only the methods and properties defined on that type.
Set Option Strict On to catch any incorrect object assignments or member accesses at compile time.
See Also
Reference
Option Strict Statement
Concepts
Collections in Visual Basic
Visual Basic Collection Class
Visual Basic Language Concepts
Raising Events
An event is like a message announcing that something important has occurred. The act of broadcasting the message is called
raising the event. In Visual Basic, you raise events with the RaiseEvent statement, as in the following example:
VB
RaiseEvent AnEvent(EventNumber)
Events must be raised within the scope of the class, module, or structure where they are declared. For example, a derived class
cannot raise events inherited from a base class.
Event Senders
Any object capable of raising an event is an event sender, also known as an event source. Forms, controls, and user-defined
objects are examples of event senders.
Event Handlers
Event handlers are procedures that are called when a corresponding event occurs. You can use any valid subroutine with a
matching signature as an event handler. You cannot use a function as an event handler, however, because it cannot return a
value to the event source.
Visual Basic uses a standard naming convention for event handlers that combines the name of the event sender, an
underscore, and the name of the event. For example, the Click event of a button named button1 would be named Sub
button1_Click.
Note
We recommend that you use this naming convention when defining event handlers for your own events, but it is not require
d; you can use any valid subroutine name.
See Also
Tasks
How to: Write Event Handlers
Reference
Handles
AddHandler Statement
Concepts
AddHandler and RemoveHandler
WithEvents and the Handles Clause
Visual Basic Language Concepts
Class EventClass
Public Event XEvent()
Public Event YEvent()
' RaiseEvents raises both events.
Sub RaiseEvents()
RaiseEvent XEvent()
RaiseEvent YEvent()
End Sub
End Class
The WithEvents statement and the Handles clause are often the best choice for event handlers because the declarative syntax
they use makes event handling easier to code, read and debug. However, be aware of the following limitations on the use of
WithEvents variables:
You cannot use a WithEvents variable as an object variable. That is, you cannot declare it as Object—you must specify
the class name when you declare the variable.
Because shared events are not tied to class instances, you cannot use WithEvents to declaratively handle shared events.
Similarly, you cannot use WithEvents or Handles to handle events from a Structure. In both cases, you can use the
AddHandler statement to handle those events.
You cannot create arrays of WithEvents variables.
WithEvents variables allow a single event handler to handle one or more kind of event, or one or more event handlers
to handle the same kind of event.
See Also
Reference
Handles
WithEvents
AddHandler Statement
Concepts
AddHandler and RemoveHandler
Visual Basic Language Concepts
RemoveHandler, which disconnects an event from an event handler, uses the same syntax as AddHandler. For example:
VB
RemoveHandler Obj.XEvent, AddressOf Me.XEventHandler
See Also
Tasks
How to: Write Event Handlers
Reference
AddHandler Statement
Concepts
Events and Event Handlers
WithEvents and the Handles Clause
Visual Basic Language Concepts
See Also
Tasks
Walkthrough: Declaring and Raising Events
Walkthrough: Handling Events
How to: Write Event Handlers
Reference
RaiseEvent Statement
Handles
AddHandler Statement
Concepts
Events and Event Handlers
Delegates and the AddressOf Operator
AddHandler and RemoveHandler
Other Resources
Polymorphism
Visual Basic Language Concepts
How to: Create Event Handlers in the Visual Basic Code Editor
The Visual Basic Code Editor provides an easy way to create event handlers for your Windows Forms. Although it does not
allow you to connect multiple events to a single event handler (see
How to: Connect Multiple Events to a Single Event Handler in Windows Forms), it does provide a quick and easy way to create
event handlers while working on your form's code without having to display the form in the Windows Forms Designer.
To create an event handler using the Visual Basic Code Editor
1. In the Code Editor, from the Class Name drop-down list, choose the form or control that you want to create an event
handler for.
2. From the Method Name list at the top of the Code Editor, choose the event that you want to create an event handler
for.
Visual Basic creates an event handler and adds it to your form's class.
See Also
Tasks
How to: Create Event Handlers Using the Designer
Troubleshooting Inherited Event Handlers in Visual Basic 2005
Concepts
Event Handlers Overview (Windows Forms)
Other Resources
Creating Event Handlers in Windows Forms
Creating a New Windows Form
Visual Basic Language Concepts
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
Access to the members of the System namespace. Add an Imports statement if you are not fully qualifying member
names in your code. For more information, see Imports Statement.
The Event statement to be at class level and not inside any procedure.
The RaiseEvent statement to be inside some procedure in your application.
See Also
Tasks
How to: Create an Event and Handler (Visual Basic)
Reference
Event Statement
RaiseEvent Statement
Concepts
Events and Event Handlers
Other Resources
Events in Visual Basic
Visual Basic Language Concepts
2. In the class or module that will handle the event, use the WithEvents keyword to declare an object variable for the
source of your events, as in the following example:
VB
Public WithEvents ClassInst As Class1
3. In the Code Editor, choose the WithEvents variable you just declared from the Class Name drop-down list on the left.
4. Choose the event you want to handle from the Method Name drop-down list on the right. The Code Editor creates the
empty event-handler procedure with a Handles clause.
Note
This step is optional. You can create the event-handler procedure manually as long as the procedure you create is a sub
routine, has the correct argument list to match the event being handled, and has a Handles clause that specifies the ev
ent being handled.
5. Add event-handling code to the event-handler procedure using the supplied arguments. The following code provides an
example:
VB
Public Sub ClassInst_AnEvent(ByVal EventNumber As Integer) _
Handles ClassInst.AnEvent
MsgBox("Received event number: " & CStr(EventNumber))
End Sub
2. Declare an object variable of the class that is the source of the events you want to handle. Unlike a WithEvents variable,
this can be a local variable in a procedure. For example:
VB
Public Sub TestAddHandler()
Dim CI As New Class1
End Sub
3. Use the AddHandler statement to specify the name of the event sender, and the AddressOf statement to provide the
name of your event handler. For example, add the following code to the end of the TestAddHandler subroutine:
VB
AddHandler CI.AnEvent, AddressOf EHandler
Any procedure can serve as an event handler as long as it supports the correct arguments for the event being handled.
See Also
Reference
Handles
AddHandler Statement
Concepts
Events and Event Handlers
Delegates and the AddressOf Operator
AddHandler and RemoveHandler
Visual Basic Language Concepts
VB
Public Class Class1
' Declare an event for this class.
Public Event Event1(ByVal EventNumber As Integer)
' Define a method that raises an event.
Sub CauseEvent(ByVal EventNumber As Integer)
RaiseEvent Event1(EventNumber)
End Sub
End Class
See Also
Tasks
How to: Write Event Handlers
Concepts
Events and Event Handlers
Delegates and the AddressOf Operator
AddHandler and RemoveHandler
Visual Basic Language Concepts
4. On the Project menu, choose Add Class to add a class named Widget.vb to the project.
When the calling object receives a PercentDone event, the Percent argument contains the percentage of the task that is
complete. The Cancel argument can be set to True to cancel the method that raised the event.
Note
You can declare event arguments just as you do arguments of procedures, with the following exceptions: Events cannot have
Optional or ParamArray arguments, and events do not have return values.
The PercentDone event is raised by the LongTask method of the Widget class. LongTask takes two arguments: the length of time
the method pretends to be doing work, and the minimum time interval before LongTask pauses to raise the PercentDone event.
To raise the PercentDone event
1. To simplify access to the Timer property used by this class, add an Imports statement to the top of the declarations
section of your class module, above the Class Widget statement.
VB
Imports Microsoft.VisualBasic.DateAndTime
' The Timer property of the DateAndTime object returns the seconds
' and milliseconds that have passed since midnight.
Start = CSng(Timer)
Threshold = MinimumInterval
When your application calls the LongTask method, the Widget class raises the PercentDone event every MinimumInterval
seconds. When the event returns, LongTask checks to see if the Cancel argument was set to True.
A few disclaimers are necessary here. For simplicity, the LongTask procedure assumes you know in advance how long the task
will take. This is almost never the case. Dividing tasks into chunks of even size can be difficult, and often what matters most to
users is simply the amount of time that passes before they get an indication that something is happening.
You may have spotted another flaw in this sample. The Timer property returns the number of seconds that have passed since
midnight; therefore, the application gets stuck if it is started just before midnight. A more careful approach to measuring time
would take boundary conditions such as this into consideration, or avoid them altogether, using properties such as Now.
Now that the Widget class can raise events, you can move to the next walkthrough. Walkthrough: Handling Events
demonstrates how to use WithEvents to associate an event handler with the PercentDone event.
See Also
Tasks
Walkthrough: Handling Events
How to: Write Event Handlers
Reference
Timer Property
WithEvents
Now Property
Event Statement
ByVal
ByRef
Imports Statement
Concepts
Events and Event Handlers
Delegates and the AddressOf Operator
AddHandler and RemoveHandler
Visual Basic Language Concepts
The WithEvents keyword specifies that the variable mWidget is used to handle an object's events. You specify the kind of
object by supplying the name of the class from which the object will be created.
The variable mWidget is declared in Form1 because WithEvents variables must be class-level. This is true regardless of
the type of class you place them in.
The variable mblnCancel is used to cancel the LongTask method.
Writing Code to Handle an Event
As soon as you declare a variable using WithEvents, the variable name appears in the left drop-down list of the class's Code
Editor. When you select mWidget, the Widget class's events appear in the right drop-down list. Selecting an event displays the
corresponding event procedure, with the prefix mWidget and an underscore. All the event procedures associated with a
WithEvents variable are given the variable name as a prefix.
To handle an event
1. Select mWidget from the left drop-down list in the Code Editor.
2. Select the PercentDone event from the right drop-down list. The Code Editor opens the mWidget_PercentDone event
procedure.
Note
The Code Editor is useful, but not required, for inserting new event handlers. In this walkthrough, it is more direct to ju
st copy the event handlers directly into your code.
Whenever the PercentDone event is raised, the event procedure displays the percent complete in a Label control. The
DoEvents method allows the label to repaint, and also gives the user the opportunity to click the Cancel button.
4. Add the following code for the Button2_Click event handler:
VB
Private Sub Button2_Click( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
) Handles Button2.Click
mblnCancel = True
End Sub
If the user clicks the Cancel button while LongTask is running, the Button2_Click event is executed as soon as the DoEvents
statement allows event processing to occur. The class-level variable mblnCancel is set to True, and the mWidget_PercentDone
event then tests it and sets the ByRef Cancel argument to True.
Connecting a WithEvents Variable to an Object
Form1 is now set up to handle a Widget object's events. All that remains is to find a Widget somewhere.
When you declare a variable WithEvents at design time, no object is associated with it. A WithEvents variable is just like any
other object variable. You have to create an object and assign a reference to it with the WithEvents variable.
To create an object and assign a reference to it
1. Select (Form1 Events) from the left drop-down list in the Code Editor.
2. Select the Load event from the right drop-down list. The Code Editor opens the Form1_Load event procedure.
3. Add the following code for the Form1_Load event procedure to create the Widget:
VB
Private Sub Form1_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles MyBase.Load
mWidget = New Widget
End Sub
When this code executes, Visual Basic creates a Widget object and connects its events to the event procedures associated with
mWidget. From that point on, whenever the Widget raises its PercentDone event, the mWidget_PercentDone event procedure is
executed.
To call the LongTask method
Add the following code to the Button1_Click event handler:
VB
Private Sub Button1_Click( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
) Handles Button1.Click
mblnCancel = False
lblPercentDone.Text = "0%"
lblPercentDone.Refresh()
mWidget.LongTask(12.2, 0.33)
If Not mblnCancel Then lblPercentDone.Text = CStr(100) & "%"
End Sub
Before the LongTask method is called, the label that displays the percent complete must be initialized, and the class-level
Boolean flag for canceling the method must be set to False.
LongTask is called with a task duration of 12.2 seconds. The PercentDone event is raised once every one-third of a second. Each
time the event is raised, the mWidget_PercentDone event procedure is executed.
When LongTask is done, mblnCancel is tested to see if LongTask ended normally, or if it stopped because mblnCancel was set to
True. The percent complete is updated only in the former case.
To run the program
1. Press F5 to put the project in run mode.
2. Click the Start Task button. Each time the PercentDone event is raised, the label is updated with the percentage of the
task that is complete.
3. Click the Cancel button to stop the task. Notice that the appearance of the Cancel button does not change immediately
when you click it. The Click event cannot happen until the My.Application.DoEvents statement allows event
processing.
Note
The My.Application.DoEvents method does not process events in exactly the same way as the form does. For exampl
e, in this walkthrough, you must click the Cancel button twice. To allow the form to handle the events directly, you can
use multithreading. For more information, see Multithreading in Visual Basic.
You may find it instructive to run the program with F11 and step through the code a line at a time. You can clearly see how
execution enters LongTask, and then briefly re-enters Form1 each time the PercentDone event is raised.
What would happen if, while execution was back in the code of Form1, the LongTask method were called again? At worst, a
stack overflow might occur if LongTask were called every time the event was raised.
You can cause the variable mWidget to handle events for a different Widget object by assigning a reference to the new Widget
to mWidget. In fact, you can make the code in Button1_Click do this every time you click the button.
To handle events for a different widget
Add the following line of code to the Button1_Click procedure, immediately preceding the line that reads
mWidget.LongTask(12.2, 0.33):
VB
mWidget = New Widget
' Create a new Widget object.
The code above creates a new Widget each time the button is clicked. As soon as the LongTask method completes, the
reference to the Widget is released, and the Widget is destroyed.
A WithEvents variable can contain only one object reference at a time, so if you assign a different Widget object to mWidget,
the previous Widget object's events will no longer be handled. If mWidget is the only object variable containing a reference to
the old Widget, the object is destroyed. If you want to handle events from several Widget objects, use the AddHandler
statement to process events from each object separately.
Note
You can declare as many WithEvents variables as you need, but arrays of WithEvents variables are not supported.
See Also
Tasks
Walkthrough: Declaring and Raising Events
How to: Write Event Handlers
Reference
Handles
WithEvents
Concepts
Events and Event Handlers
Delegates and the AddressOf Operator
AddHandler and RemoveHandler
Other Resources
Polymorphism
Visual Basic Language Concepts
When code raises the Click event, the RaiseEvent accessor invokes all the event handler delegates asynchronously using the
BeginInvoke method. That method invokes each handler on a worker thread and returns immediately, so handlers cannot
block one another.
VB
Public NotInheritable Class ReliabilityOptimizedControl
'Defines a list for storing the delegates
Private EventHandlerList As New ArrayList
See Also
Tasks
How to: Declare Events That Conserve Memory Use
Reference
Event Statement
ArrayList
BeginInvoke
Visual Basic Language Concepts
' Define the Click event to use the same delegate store.
Public Custom Event DoubleClick As EventHandler
AddHandler(ByVal value As EventHandler)
Events.AddHandler("DoubleClickEvent", value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Events.RemoveHandler("DoubleClickEvent", value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
CType(Events("DoubleClickEvent"), EventHandler).Invoke(sender, e)
End RaiseEvent
End Event
' Define additional events to use the same delegate store.
' ...
End Class
See Also
Tasks
How to: Declare Events That Avoid Blocking
Reference
Event Statement
EventHandlerList
Visual Basic Language Concepts
If the inherited method does not have a Handles keyword, verify that your code does not contain an extra
AddHandler Statement or any additional methods that handle the same event.
See Also
Tasks
How to: Write Event Handlers
Concepts
Events and Event Handlers
How to: Handle Events in Visual Basic
Other Resources
Events in Visual Basic
Visual Basic Language Concepts
You can use the shorthand way of creating delegates anywhere the compiler can determine the delegate's type by the context.
Declaring Events that Use an Existing Delegate Type
In some situations, you may want to declare an event to use an existing delegate type as its underlying delegate. The following
syntax demonstrates how:
VB
Delegate Sub DelegateType()
Event AnEvent As DelegateType
This is useful when you want to route multiple events to the same handler.
Delegate Variables and Parameters
You can use delegates for other, non-event related tasks, such as free threading or with procedures that need to call different
versions of functions at compile time.
For example, suppose you have a classified-ad application that includes a list box with the names of cars. The ads are sorted by
title, which is normally the make of the car. A problem you may face occurs when some cars include the year of the car before
the make. The problem is that the built-in sort functionality of the list box sorts only by character codes; it places all the ads
starting with dates first, followed by the ads starting with the make.
To fix this, you can create a sort procedure in a class that uses the standard alphabetic sort on most list boxes, but is able to
switch at run time to the custom sort procedure for car ads. To do this, you pass the custom sort procedure to the sort class at
run time, using delegates.
Each delegate class defines a constructor that takes a specification of an object method. The following syntax provides an
example of a parameter to such a delegate constructor:
AddressOf [expression.]methodname
The compile-time type of expression must be a class or an interface with a method by the specified name whose signature
matches the signature of the delegate class. The method can be either a shared (class) method or an instance method.
See Also
Tasks
How to: Pass Procedures to Another Procedure in Visual Basic
How to: Invoke a Delegate Method
How to: Write Event Handlers
Reference
Delegate Statement
AddressOf Operator
Concepts
Events and Event Handlers
AddHandler and RemoveHandler
Multithreaded Applications
Visual Basic Language Concepts
2. Declare a class that contains a method with the same signature as the delegate.
Class class1
Sub Sub1(ByVal x As Integer)
MsgBox("The value of x is: " & CStr(x))
End Sub
End Class
3. Define a method that creates an instance of the delegate and invokes the method associated with the delegate by calling
the built-in Invoke method.
See Also
Tasks
How to: Write Event Handlers
Reference
Delegate Statement
Concepts
Delegates and the AddressOf Operator
Events and Event Handlers
AddHandler and RemoveHandler
Multithreaded Applications
Visual Basic Language Concepts
2. Create a procedure named AddNumbers with parameters and return value that match those of MathOperator, so that the
signatures match.
VB
Function AddNumbers( _
ByVal x As Double, _
ByVal y As Double _
) As Double
Return x + y
End Function
VB
Sub DelegateTest( _
ByVal x As Double, _
ByVal op As MathOperator, _
ByVal y As Double _
)
Dim ret As Double
ret = op.Invoke(x, y) ' Call the method.
MsgBox(ret)
End Sub
5. Create a procedure named Test that calls DelegateTest once with the delegate for AddNumbers as a parameter, and again
with the delegate for SubtractNumbers as a parameter.
VB
Protected Sub Test()
DelegateTest(5, AddressOf AddNumbers, 3)
DelegateTest(9, AddressOf SubtractNumbers, 3)
End Sub
When Test is called, it first displays the result of AddNumbers acting on 5 and 3, which is 8. Then the result of
SubtractNumbers acting on 9 and 3 is displayed, which is 6.
See Also
Tasks
How to: Invoke a Delegate Method
Reference
AddressOf Operator
Delegate Statement
Other Resources
Delegates in Visual Basic
Visual Basic Language Concepts
Interfaces Overview
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide
implementation. They are implemented by classes, and defined as separate entities from classes.
An interface represents a contract, in that a class that implements an interface must implement every aspect of that interface
exactly as it is defined.
With interfaces, you can define features as small groups of closely related members. You can develop enhanced
implementations for your interfaces without jeopardizing existing code, thus minimizing compatibility problems. You can also
add new features at any time by developing additional interfaces and implementations.
Although interface implementations can evolve, interfaces themselves cannot be changed once published. Changes to a
published interface may break existing code. If you think of an interface as a contract, it is clear that both sides of the contract
have a role to play. The publisher of an interface agrees never to change that interface, and the implementer agrees to
implement the interface exactly as it was designed.
In previous versions of Visual Basic, you could consume interfaces but not create them directly. Now you can define true
interfaces using the Interface statement, and you can implement interfaces with an improved version of the Implements
keyword.
See Also
Tasks
How to: Create and Implement Interfaces
Walkthrough: Creating and Implementing Interfaces
Reference
Interface Statement (Visual Basic)
Concepts
Interface Definition
Implements Keyword and Implements Statement
Interface Implementation Examples in Visual Basic
When to Use Interfaces
Other Resources
Inheritance in Visual Basic
Visual Basic Language Concepts
Interface Definition
Interface definitions are enclosed within the Interface and End Interface statements. Following the Interface statement, you
can add an optional Inherits statement that lists one or more inherited interfaces. The Inherits statements must precede all
other statements in the declaration except comments. The remaining statements in the interface definition should be Event,
Sub, Function, Property, Interface, Class, Structure, and Enum statements. Interfaces cannot contain any implementation
code or statements associated with implementation code, such as End Sub or End Property.
In a namespace, interface statements are Friend by default, but they can also be explicitly declared as Public or Friend.
Interfaces defined within classes, modules, interfaces, and structures are Public by default, but they can also be explicitly
declared as Public, Friend, Protected, or Private.
Note
The Shadows keyword can be applied to all interface members. The Overloads keyword can be applied to Sub, Function, a
nd Property statements declared in an interface definition. In addition, Property statements can have the Default, ReadOnl
y, or WriteOnly modifiers. None of the other modifiers—Public, Private, Friend, Protected, Shared, Overrides, MustOve
rride, or Overridable—are allowed. For more information, see Declaration Contexts and Default Access Levels.
See Also
Tasks
How to: Create and Implement Interfaces
Walkthrough: Creating and Implementing Interfaces
Reference
Interface Statement (Visual Basic)
Inherits Statement
Overloads
Default (Visual Basic)
Concepts
Interfaces Overview
Implements Keyword and Implements Statement
Interface Implementation Examples in Visual Basic
When to Use Interfaces
Other Resources
Inheritance in Visual Basic
Visual Basic Language Concepts
The parameter types and return types of the implementing member must match the interface property or member declaration
in the interface. The most common way to implement an element of an interface is with a member that has the same name as
the interface, as shown in the previous example.
To declare the implementation of an interface method, you can use any attributes that are legal on instance method
declarations, including Overloads, Overrides, Overridable, Public, Private, Protected, Friend, Protected Friend,
MustOverride, Default, and Static. The Shared attribute is not legal since it defines a class rather than an instance method.
Using Implements, you can also write a single method that implements multiple methods defined in an interface, as in the
following example:
VB
Class Class2
Implements I1, I2
You can use a private member to implement an interface member. When a private member implements a member of an
interface, that member becomes available by way of the interface even though it is not available directly on object variables for
the class.
See Also
Tasks
How to: Create and Implement Interfaces
Walkthrough: Creating and Implementing Interfaces
Reference
Implements Statement
Implements (Visual Basic)
Concepts
Interfaces Overview
Interface Definition
Interface Implementation Examples in Visual Basic
When to Use Interfaces
Other Resources
Inheritance in Visual Basic
Visual Basic Language Concepts
The next example implements Interface1, the interface defined in the previous example:
VB
Public Class ImplementationClass1
Implements Interface1
Sub Sub1(ByVal i As Integer) Implements Interface1.sub1
' Insert code here to implement this method.
End Sub
End Class
The final example implements Interface2, including a method inherited from Interface1:
VB
Public Class ImplementationClass2
Implements Interface2
Dim INum As Integer = 0
Sub sub1(ByVal i As Integer) Implements Interface2.sub1
' Insert code here that implements this method.
End Sub
Sub M1(ByVal x As Integer) Implements Interface2.M1
' Insert code here to implement this method.
End Sub
See Also
Tasks
How to: Create and Implement Interfaces
Walkthrough: Creating and Implementing Interfaces
Reference
Interface Statement (Visual Basic)
Implements Statement
Concepts
Interfaces Overview
Interface Definition
Implements Keyword and Implements Statement
When to Use Interfaces
Visual Basic Language Concepts
2. Add statements that define the properties, methods, and events your interface supports. For example, the following code
defines one function, one property, and one event.
VB
Interface IAsset
Event ComittedChange(ByVal Success As Boolean)
Property Division() As String
Function GetID() As Integer
End Interface
To implement an interface
1. If the interface that you are implementing is not part of your project, add a reference to the assembly containing the
interface.
2. Create a new class that implements your interface, and include the Implements keyword in the line following the class
name. For example, to implement the IAsset interface, you could name the implementation class Computer, as in the
following code.
VB
Class Computer
Implements IAsset
End Class
3. Add procedures to implement the properties, methods, and events of the class as in the following code, which builds on
the example in the previous step:
VB
Class Computer
Implements IAsset
Return IDValue
End Function
See Also
Tasks
Walkthrough: Creating and Implementing Interfaces
Reference
Interface Statement (Visual Basic)
Concepts
Interfaces Overview
Interface Definition
Implements Keyword and Implements Statement
Interface Implementation Examples in Visual Basic
When to Use Interfaces
Other Resources
Inheritance in Visual Basic
Visual Basic Language Concepts
To define an interface
1. Open a new Visual Basic Windows Application project.
2. Add a new module to the project by clicking Add Module on the Project menu.
3. Name the new module Module1.vb and click Add. The code for the new module is displayed.
4. Define an interface named TestInterface within Module1 by typing Interface TestInterface between the Module and
End Module statements, and then pressing ENTER. The Code Editor indents the Interface keyword and adds an End
Interface statement to form a code block.
5. Define a property, method, and event for the interface by placing the following code between the Interface and End
Interface statements:
VB
Property Prop1() As Integer
Sub Method1(ByVal X As Integer)
Event Event1()
Implementation
You may notice that the syntax used to declare interface members is different from the syntax used to declare class members.
This difference reflects the fact that interfaces cannot contain implementation code.
To implement the interface
1. Add a class named ImplementationClass by adding the following statement to Module1, after the End Interface
statement but before the End Module statement, and then pressing ENTER:
VB
Class ImplementationClass
If you are working within the integrated development environment, the Code Editor supplies a matching End Class
statement when you press ENTER.
2. Add the following Implements statement to ImplementationClass, which names the interface the class implements:
VB
Implements TestInterface
When listed separately from other items at the top of a class or structure, the Implements statement indicates that the
class or structure implements an interface.
If you are working within the integrated development environment, the Code Editor implements the class members
required by TestInterface when you press ENTER, and you can skip the next step.
3. If you are not working within the integrated development environment, you must implement all the members of the
interface MyInterface. Add the following code to ImplementationClass to implement Event1, Method1, and Prop1:
VB
Event Event1() Implements TestInterface.Event1
The Implements statement names the interface and interface member being implemented.
4. Complete the definition of Prop1 by adding a private field to the class that stored the property value:
VB
' Holds the value of the property.
Private pval As Integer
Return the value of the pval from the property get accessor.
VB
Return pval
By declaring testInstance as WithEvents, the Form1 class can handle its events.
3. Add the following event handler to the Form1 class to handle events raised by testInstance:
VB
Sub EventHandler() Handles testInstance.Event1
MsgBox("The event handler caught the event.")
End Sub
4. Add a subroutine named Test to the Form1 class to test the implementation class:
VB
Sub Test()
' Create an instance of the class.
Dim T As New ImplementationClass
' Assign the class instance to the interface.
' Calls to the interface members are
' executed through the class instance.
testInstance = T
' Set a property.
testInstance.Prop1 = 9
' Read the property.
MsgBox("Prop1 was set to " & testInstance.Prop1)
' Test the method and raise an event.
testInstance.Method1(5)
End Sub
The Test procedure creates an instance of the class that implements MyInterface, assigns that instance to the
testInstance field, sets a property, and runs a method through the interface.
5. Add code to call the Test procedure from the Form1 Load procedure of your startup form:
VB
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Test() ' Test the class.
End Sub
6. Run the Test procedure by pressing F5. The message "Prop1 was set to 9" is displayed. After you click OK, the message
"The X parameter for Method1 is 5" is displayed. Click OK, and the message "The event handler caught the event" is
displayed.
See Also
Tasks
How to: Create and Implement Interfaces
Reference
Implements Statement
Interface Statement (Visual Basic)
Event Statement
Concepts
When to Use Interfaces
Other Resources
Interfaces in Visual Basic
Visual Basic Language Concepts
Inheritance Basics
The Inherits statement is used to declare a new class, called a derived class, based on an existing class, known as a base class.
Derived classes inherit, and can extend, the properties, methods, events, fields, and constants defined in the base class. The
following section describes some of the rules for inheritance, and the modifiers you can use to change the way classes inherit
or are inherited:
All classes are inheritable by default unless marked with the NotInheritable keyword. Classes can inherit from other
classes in your project or from classes in other assemblies that your project references.
Unlike languages that permit multiple inheritance, Visual Basic permits only single inheritance in classes; that is, derived
classes can have only one base class. Although multiple inheritance is not allowed in classes, classes can implement
multiple interfaces, which can effectively accomplish the same ends.
To prevent exposing restricted items in a base class, the access type of a derived class must be equal to or more
restrictive than its base class. For example, a Public class cannot inherit a Friend or a Private class, and a Friend class
cannot inherit a Private class.
Inheritance Modifiers
Visual Basic introduces the following class-level statements and modifiers to support inheritance:
Inherits statement — Specifies the base class.
NotInheritable modifier — Prevents programmers from using the class as a base class.
MustInherit modifier — Specifies that the class is intended for use as a base class only. Instances of MustInherit classes
cannot be created directly; they can only be created as base class instances of a derived class. (Other programming
languages, such as C++ and C#, use the term abstract class to describe such a class.)
Overriding Properties and Methods in Derived Classes
By default, a derived class inherits properties and methods from its base class. If an inherited property or method needs to
behave differently in the derived class it can be overridden; that is, you can define a new implementation of the method in the
derived class. The following modifiers are used to control how properties and methods are overridden:
Overridable — Allows a property or method in a class to be overridden in a derived class.
Overrides — Overrides an Overridable property or method defined in the base class.
NotOverridable — Prevents a property or method from being overridden in an inheriting class. Public methods are
NotOverridable by default.
MustOverride — Requires that a derived class override the property or method. When the MustOverride keyword is
used, the method definition consists of just the Sub, Function, or Property statement. No other statements are allowed,
and specifically there is no End Sub or End Function statement. MustOverride methods must be declared in
MustInherit classes.
For more information about overriding methods, see Overriding Properties and Methods.
The MyBase Keyword
You can use the MyBase keyword to call methods in a base class when overriding methods in a derived class. For example,
suppose you are designing a derived class that overrides a method inherited from the base class. The overridden method can
call the method in the base class and modify the return value as shown in the following code fragment:
VB
Class DerivedClass
Inherits BaseClass
Public Overrides Function CalculateShipping( _
ByVal Dist As Double, _
ByVal Rate As Double) _
As Double
' Call the method in the base class and modify the return value.
Return MyBase.CalculateShipping(Dist, Rate) * 2
End Function
End Class
See Also
Tasks
How to: Create Derived Classes
Reference
Inherits Statement
Concepts
Overriding Properties and Methods
Other Resources
Language Changes for Visual Basic 6.0 Users
Visual Basic Language Concepts
Class Class2
Inherits Class1
Public Field2 As Integer
Overrides Sub Method2()
MsgBox("This is a method in a derived class.")
End Sub
End Class
When you run the procedure TestInheritance, you see the following messages:
This is a method in the base class.
This is another method in the base class.
This is a method in the base class.
This is a method in a derived class.
See Also
Concepts
Overriding Properties and Methods
Override Modifiers
Other Resources
Inheritance in Visual Basic
Class Properties, Fields, and Methods
Visual Basic Language Concepts
Your application may also have a similar list of products the user has added to a shopping cart list, as shown in the following
code fragment:
VB
Class ShoppingCartItem
Protected PreviousItem As ShoppingCartItem
Protected NextItem As ShoppingCartItem
Public ProductCode As Integer
Public Function GetNextItem() As ShoppingCartItem
' Insert code to get the next ShoppingCartItem from the list.
Return NextItem
End Function
End Class
You can see a pattern here: two lists behave the same way (insertions, deletions, and retrievals) but operate on different data
types. Maintaining two code bases to perform essentially the same functions is not efficient. The most efficient solution is to
factor out the list management into its own class, and then inherit from that class for different data types:
VB
Class ListItem
Protected PreviousItem As ListItem
Protected NextItem As ListItem
Public Function GetNextItem() As ListItem
' Insert code to get the next item in the list.
Return NextItem
End Function
Public Sub InsertNextItem()
' Insert code to add a item to the list.
End Sub
The ListItem class needs only to be debugged once. Then you can build classes that use it without ever having to think about
list management again. For example:
VB
Class CustomerInfo
Inherits ListItem
Public ID As Integer
Public FullName As String
End Class
Class ShoppingCartItem
Inherits ListItem
Public ProductCode As Integer
End Class
Although inheritance-based code reuse is powerful tool, it also has associated risks. Even the best-designed systems
sometimes change in ways the designers could not foresee. Changes to an existing class hierarchy can sometimes have
unintended consequences; some examples are discussed in "The Fragile Base Class Problem," in
Base Class Design Changes After Deployment.
Interchangeable Derived Classes
Derived classes in a class hierarchy can sometimes be used interchangeably with their base class, a process called inheritance-
based polymorphism. This approach combines the best features of interface-based polymorphism with the option of reusing
or overriding code from a base class.
An example where this can be useful is in a drawing package. For example, consider the following code fragment, which does
not use inheritance:
VB
Sub Draw(ByVal Shape As DrawingShape, ByVal X As Integer, _
ByVal Y As Integer, ByVal Size As Integer)
Select Case Shape.type
Case shpCircle
' Insert circle drawing code here.
Case shpLine
' Insert line drawing code here.
End Select
End Sub
This approach poses some problems. If someone decides to add an ellipse option later, it will be necessary to alter the source
code; it is possible that your target users will not even have access to your source code. A more subtle problem is that drawing
an ellipse requires another parameter (ellipses have both a major and a minor diameter) that would be irrelevant to the line
case. If someone then wants to add a polyline (multiple connected lines), then another parameter would be added, and it would
be irrelevant to the other cases.
Inheritance solves most of these problems. Well-designed base classes leave the implementation of specific methods up to the
derived classes, so that any kind of shape can be accommodated. Other developers can implement methods in derived classes
by using the documentation for the base class. Other class items (such as the x- and y-coordinates) can be built into the base
class because all descendants use them. For example, Draw could be a MustOverride method:
VB
MustInherit Class Shape
Public X As Integer
Public Y As Integer
MustOverride Sub Draw()
End Class
Then you could add to that class as appropriate for different shapes. For example, a Line class might only need a Length field:
VB
Class Line
Inherits Shape
Public Length As Integer
Overrides Sub Draw()
' Insert code here to implement Draw for this shape.
End Sub
End Class
This approach is useful because other developers, who do not have access to your source code, can extend your base class with
new derived classes as needed. For example, a class named Rectangle could be derived from the Line class:
VB
Class Rectangle
Inherits Line
Public Width As Integer
Overrides Sub Draw()
' Insert code here to implement Draw for the Rectangle shape.
End Sub
End Class
This example shows how you can move from general-purpose classes to very specific classes by adding implementation
details at each level.
At this point it might be good to reevaluate if the derived class truly represents an "is a" relationship, or instead is a "has a"
relationship. If the new rectangle class is just composed of lines, then inheritance is not the best choice. However, if the new
rectangle is a line with a width property, then the "is a" relationship is maintained.
Shallow Class Hierarchies
Inheritance is best suited for relatively shallow class hierarchies. Excessively deep and complex class hierarchies can be difficult
to develop. The decision to use a class hierarchy involves weighing the benefits of using a class hierarchy against complexity.
As a general rule, you should limit hierarchies to six levels or fewer. However, the maximum depth for any particular class
hierarchy depends on a number of factors, including the amount of complexity at each level.
Global Changes to Derived Classes Through the Base Class
One of the most powerful features of inheritance is the ability to make changes in a base class that propagate to derived
classes. When used carefully, you can update the implementation of a single method, and dozens—or even hundreds—of
derived classes can use the new code. However, this can be a dangerous practice because such changes may cause problems
with inherited classes designed by other people. Care must be taken to ensure that the new base class is compatible with
classes that use the original. You should specifically avoid changing the name or type of base class members.
Suppose, for example, that you design a base class with a field of type Integer to store zip code information, and other
developers have created derived classes that use the inherited zip code field. Suppose further that your zip code field stores
five digits, and the post office has expanded zip codes with a hyphen and four more digits. In a worst-case scenario, you could
modify the field in the base class to store a 10-character string, but other developers would need to change and recompile the
derived classes to use the new size and data type.
The safest way to change a base class is to simply add new members. For example, you could add a new field to store the
additional four digits in the zip code example discussed previously. That way, client applications can be updated to use the new
field without breaking existing applications. The ability to extend base classes in an inheritance hierarchy is an important
benefit that does not exist with interfaces.
See Also
Concepts
When to Use Interfaces
Base Class Design Changes After Deployment
Visual Basic Language Concepts
9. Add a function:
Function AddNumbers( _
ByVal SomeNumber As Integer, _
ByVal AnotherNumber As Integer) _
As Integer
Interop Assemblies
In the following procedure, you will create an interop assembly, which acts as a bridge between unmanaged code (such as a
COM object) and the managed code Visual Studio uses. The interop assembly that Visual Basic creates handles many of the
details of working with COM objects, such as interop marshaling, the process of packaging parameters and return values into
equivalent data types as they move to and from COM objects. The reference in the Visual Basic application points to the interop
assembly, not the actual COM object.
To use a COM object with Visual Basic 2005
1. Open a new Visual Basic Windows Application project.
2. On the Project menu, click Add Reference.
The Add Reference dialog box is displayed.
3. On the COM tab, double click ComObject1 in the Component Name list and click OK.
4. On the Project menu, click Add New Item.
The Add New Item dialog box is displayed.
5. In the Templates pane, click Class.
The default file name, Class1.vb, appears in the Name field. Change this field to MathClass.vb and click Add. This
creates a class named MathClass, and displays its code.
6. Add the following code to the top of MathClass to inherit from the COM class.
VB
' The inherited class is called MathFunctions in the base class,
' but the interop assembly appends the word Class to the name.
Inherits ComObject1.MathFunctionsClass
7. Overload the public method of the base class by adding the following code to MathClass:
VB
' This method overloads the method AddNumbers from the base class.
Overloads Function AddNumbers( _
ByVal SomeNumber As Integer, _
ByVal AnotherNumber As Integer) _
As Integer
The new class inherits the properties of the base class in the COM object, overloads a method, and defines a new method to
extend the class.
To test the inherited class
1. Add a button to your startup form, and then double-click it to view its code.
2. In the button's Click event handler procedure, add the following code to create an instance of MathClass and call the
overloaded methods:
VB
Dim Result1 As Short
Dim Result2 As Integer
Dim Result3 As Integer
Dim MathObject As New MathClass
Result1 = MathObject.AddNumbers(4S, 2S) ' Add two Shorts.
Result2 = MathObject.AddNumbers(4, 2) 'Add two Integers.
Result3 = MathObject.SubtractNumbers(2, 4) ' Subtract 2 from 4.
MathObject.Prop1 = 6 ' Set an inherited property.
When an object is no longer needed, the CLR calls the Finalize method for that object before freeing its memory. The Finalize
method is called a destructor because it performs cleanup tasks, such as saving state information, closing files and connections
to databases, and other tasks that must be done before releasing the object.
See Also
Concepts
Object Lifetime: How Objects Are Created and Destroyed
Visual Basic Language Concepts
Polymorphism
Polymorphism refers to the ability to define multiple classes with functionally different, yet identically named methods or
properties that can be used interchangeably by client code at run time.
In This Section
How Visual Basic Provides Polymorphism
Illustrates different approaches to polymorphism.
Inheritance-Based Polymorphism
Discusses using inheritance to achieve polymorphism.
Interface-Based Polymorphism
Discusses using interfaces to achieve polymorphism.
Related Sections
When to Use Interfaces
Discusses when to use interfaces instead of an inheritance hierarchy.
When to Use Inheritance
Provides information about when you should use inheritance instead of interfaces.
Visual Basic Language Concepts
Inheritance-Based Polymorphism
Most object-oriented programming systems provide polymorphism through inheritance. Inheritance-based polymorphism
involves defining methods in a base class and overriding them with new implementations in derived classes.
For example, you could define a class, BaseTax, that provides baseline functionality for computing sales tax in a state. Classes
derived from BaseTax, such as CountyTax or CityTax, could implement methods such as CalculateTax as appropriate.
Polymorphism comes from the fact that you could call the CalculateTax method of an object belonging to any class that
derived from BaseTax, without knowing which class the object belonged to.
The TestPoly procedure in the following example demonstrates inheritance-based polymorphism:
VB
' %5.3 State tax
Const StateRate As Double = 0.053
' %2.8 City tax
Const CityRate As Double = 0.028
Public Class BaseTax
Overridable Function CalculateTax(ByVal Amount As Double) As Double
' Calculate state tax.
Return Amount * StateRate
End Function
End Class
Sub TestPoly()
Dim Item1 As New BaseTax
Dim Item2 As New CityTax
' $22.74 normal purchase.
ShowTax(Item1, 22.74)
' $22.74 city purchase.
ShowTax(Item2, 22.74)
End Sub
In this example, the ShowTax procedure accepts a parameter named Item of type BaseTax, but you can also pass any of the
classes derived from the BaseTax class, such as CityTax. The advantage of this design is that you can add new classes derived
from the BaseTax class without changing the client code in the ShowTax procedure.
See Also
Concepts
Interface-Based Polymorphism
Other Resources
Designing an Inheritance Hierarchy
Visual Basic Language Concepts
Interface-Based Polymorphism
Interfaces provide another way you can accomplish polymorphism in Visual Basic. Interfaces describe properties and methods
like classes, but unlike classes, interfaces cannot provide any implementation. Multiple interfaces have the advantage of
allowing systems of software components to evolve without breaking existing code.
To achieve polymorphism with interfaces, you implement an interface in different ways in several classes. Client applications
can use either the old or the new implementations in exactly the same way. The advantage to interface-based polymorphism is
that you do not need to re-compile existing client applications to get them to work with new interface implementations.
The following example defines an interface named Shape2 that is implemented in a class named RightTriangleClass2 and
RectangleClass2. A procedure named ProcessShape2 calls the CalculateArea method of instances of RightTriangleClass2
or RectangleClass2:
VB
Sub TestInterface()
Dim RectangleObject2 As New RectangleClass2
Dim RightTriangleObject2 As New RightTriangleClass2
ProcessShape2(RightTriangleObject2, 3, 14)
ProcessShape2(RectangleObject2, 3, 5)
End Sub
See Also
Tasks
How to: Create and Implement Interfaces
Concepts
Inheritance-Based Polymorphism
Visual Basic Language Concepts
When you execute the TestShared procedure, two instances of the class are created. The constructor uses the shared field
Count to initialize the instance field SerialNumber, then increments Count. This technique automatically gives each instance a
different serial number.
After creating the two instances, the instance method InstanceMethod is called on both objects, and the shared method
ShareMethod is also called. The output is:
Information in the first object: 1 keyboard
Information in the second object: 2 monitor
Current value of the shared Count field: 3
See Also
Reference
Dim Statement (Visual Basic)
Cos
Concepts
Structures and Classes
Other Resources
Class Properties, Fields, and Methods
Structures: Your Own Data Types
Visual Basic Language Concepts
Because FileStream is a specific object type, the instance assigned to FS is early bound.
By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold
references to any object, but lack many of the advantages of early-bound objects. For example, the following code fragment
declares an object variable to hold an object returned by the CreateObject function:
VB
' To use this example, you must have Microsoft Excel installed on your computer.
' Compile with Option Strict Off to allow late binding.
Sub TestLateBinding()
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
xlApp = CreateObject("Excel.Application")
' Late bind an instance of an Excel workbook.
xlBook = xlApp.Workbooks.Add
' Late bind an instance of an Excel worksheet.
xlSheet = xlBook.Worksheets(1)
xlSheet.Activate()
' Show the application.
xlSheet.Application.Visible = True
' Place some text in the second row of the sheet.
xlSheet.Cells(2, 2) = "This is column B row 2"
End Sub
See Also
Reference
Object Data Type
CreateObject Function (Visual Basic)
Concepts
Object Lifetime: How Objects Are Created and Destroyed
Visual Basic Language Concepts
The TypeOf...Is operator is the best choice for testing an object's type, because it is much faster than an equivalent string
comparison using TypeName. The following code fragment uses TypeOf...Is within an If...Then...Else statement:
VB
If TypeOf Ctrl Is Button Then
MsgBox("The control is a button.")
End If
A word of caution is due here. The TypeOf...Is operator returns True if an object is of a specific type, or is derived from a
specific type. Almost everything you do with Visual Basic involves objects, which include some elements not normally thought
of as objects, such as strings and integers. These objects are derived from and inherit methods from Object. When passed an
Integer and evaluated with Object, the TypeOf...Is operator returns True. The following example reports that the parameter
InParam is both an Object and an Integer:
VB
Sub CheckType(ByVal InParam As Object)
' Both If statements evaluate to True when an
' Integer is passed to this procedure.
If TypeOf InParam Is Object Then
MsgBox("InParam is an Object")
End If
If TypeOf InParam Is Integer Then
MsgBox("InParam is an Integer")
End If
End Sub
The following example uses both TypeOf...Is and TypeName to determine the type of object passed to it in the Ctrl
argument. The TestObject procedure calls ShowType with three different kinds of controls.
To run the example
1. Create a new Windows Application project and add a Button control, a CheckBox control, and a RadioButton control to
the form.
2. From the button on your form, call the TestObject procedure.
3. Add the following code to your form:
VB
Sub ShowType(ByVal Ctrl As Object)
'Use the TypeName function to display the class name as text.
MsgBox(TypeName(Ctrl))
'Use the TypeOf function to determine the object's type.
If TypeOf Ctrl Is Button Then
MsgBox("The control is a button.")
ElseIf TypeOf Ctrl Is CheckBox Then
MsgBox("The control is a check box.")
Else
MsgBox("The object is some other type of control.")
End If
End Sub
See Also
Reference
Object Data Type
TypeName Function (Visual Basic)
If...Then...Else Statement (Visual Basic)
String Data Type (Visual Basic)
Integer Data Type (Visual Basic)
Concepts
Calling a Property or Method Using a String Name
Other Resources
Obtaining Class Information at Run Time
Visual Basic Language Concepts
VB
Class MathClass
Function SquareRoot(ByVal X As Double) As Double
Return Math.Sqrt(X)
End Function
Function InverseSine(ByVal X As Double) As Double
Return Math.Atan(X / Math.Sqrt(-X * X + 1))
End Function
Function Acos(ByVal X As Double) As Double
Return Math.Atan(-X / Math.Sqrt(-X * X + 1)) + 2 * Math.Atan(1)
End Function
End Class
Your application could use text box controls to control which method will be called and its arguments. For example, if TextBox1
contains the expression to be evaluated, and TextBox2 is used to enter the name of the function, you can use the following
code to invoke the SquareRoot function on the expression in TextBox1:
VB
Private Sub CallMath()
Dim Math As New MathClass
Me.TextBox1.Text = CStr(CallByName(Math, Me.TextBox2.Text, _
Microsoft.VisualBasic.CallType.Method, TextBox1.Text))
End Sub
If you enter "64" in TextBox1, "SquareRoot" in TextBox2, and then call the CallMath procedure, the square root of the number
in TextBox1 is evaluated. The code in the example invokes the SquareRoot function (which takes a string containing the
expression to be evaluated as a required argument) and returns "8" in TextBox1 (the square root of 64). Of course, if the user
enters an invalid string in TextBox2, if the string contains the name of a property instead of a method, or if the method had an
additional required argument, a run-time error occurs. You need to add robust error-handling code when you use
CallByName to anticipate these or any other errors.
Note
While the CallByName function may be useful in some situations, you need to weigh its usefulness against the performance
implications — using CallByName to invoke a procedure is slightly slower than a late-bound call. If you are invoking a funct
ion that is called repeatedly, such as inside a loop, CallByName can have a severe effect on performance.
See Also
Tasks
How to: Perform Multiple Actions on an Object
Reference
CallByName Function
Concepts
Determining Object Type
Other Resources
Obtaining Class Information at Run Time
Visual Basic Language Concepts
COM Interop
The Component Object Model (COM) allows an object to expose its functionality to other components and to host applications.
Most of today's software includes COM objects. Although .NET assemblies are the best choice for new applications, you may at
times need to employ COM objects. This section covers some of the issues associated with creating and using COM objects
with Visual Basic.
In This Section
Introduction to COM Interop
Provides an overview of COM interoperability.
How to: Reference COM Objects from Visual Basic
Covers how to add references to COM objects that have type libraries.
How to: Work with ActiveX Controls
Demonstrates how to use existing ActiveX controls to add features to the Visual Studio Toolbox.
Walkthrough: Calling Windows APIs
Steps you through the process of calling the APIs that are part of the Windows operating system.
How to: Call Windows APIs (Visual Basic)
Demonstrates how to define and call the MessageBox function in User32.dll.
Walkthrough: Creating COM Objects with Visual Basic 2005
Steps you through the process of creating COM objects with and without the COM class template.
Troubleshooting Interoperability
Covers some of the problems you may encounter when using COM.
COM Interoperability in .NET Framework Applications
Provides an overview of how to use COM objects and .NET Framework objects in the same application.
Related Sections
Walkthrough: Implementing Inheritance with COM Objects
Demonstrates how to use classes in COM objects as the basis for inheritance in Visual Basic.
Interoperating with Unmanaged Code
Describes interoperability services provided by the common language runtime.
Exposing COM Components to the .NET Framework
Describes the process of calling COM types through COM interop.
Exposing .NET Framework Components to COM
Describes the preparation and use of managed types from COM.
Applying Interop Attributes
Covers attributes you can use when working with unmanaged code.
Visual Basic Language Concepts
You can use Tlbimp to create interop assemblies for type libraries, even for unregistered COM objects. However, the
COM objects referred to by interop assemblies must be properly registered on the computer where they are to be used.
You can register a COM object by using the Regsvr32 utility included with the Windows operating system.
See Also
Tasks
Walkthrough: Implementing Inheritance with COM Objects
Troubleshooting Interoperability
Reference
Type Library Importer (Tlbimp.exe)
Type Library Exporter (Tlbexp.exe)
Imports Statement
Other Resources
COM Interop
Visual Basic Language Concepts
See Also
Tasks
How to: Add ActiveX Controls to Windows Forms
Troubleshooting Interoperability
Reference
Choose Toolbox Items Dialog Box (Visual Studio)
Windows Forms ActiveX Control Importer (Aximp.exe)
Concepts
Considerations When Hosting an ActiveX Control on a Windows Form
Other Resources
COM Interop
Visual Basic Language Concepts
2. Open a new Windows Application project by clicking New on the File menu, and then clicking Project. The New Project
dialog box appears.
3. Select Windows Application from the list of Visual Basic project templates. The new project is displayed.
4. Add the following Declare function either to the class or module in which you want to use the DLL:
VB
Declare Auto Function MBox Lib "user32.dll" Alias "MessageBox" ( _
ByVal hWnd As Integer, _
ByVal txt As String, _
ByVal caption As String, _
ByVal Typ As Integer) _
As Integer
3. Add equivalent Const statements to your class or module to make these constants available to your application. For
example:
VB
Const MB_ICONQUESTION As Integer = &H20
Const MB_YESNO As Integer = &H4
Const IDYES As Integer = 6
Const IDNO As Integer = 7
3. Run the project by pressing F5. The message box is displayed with both Yes and No response buttons. Click either one.
Data Marshaling
Visual Basic automatically converts the data types of parameters and return values for Windows API calls, but you can use the
MarshalAs attribute to explicitly specify unmanaged data types that an API expects. For more information about interop
marshaling, see Interop Marshaling
To use Declare and MarshalAs in an API call
1. Determine the name of the function you want to call, plus its arguments, data types, and return value.
2. To simplify access to the MarshalAs attribute, add an Imports statement to the top of the code for the class or module,
as in the following example:
VB
Imports System.Runtime.InteropServices
3. Add a function prototype for the imported function to the class or module you are using, and apply the MarshalAs
attribute to the parameters or return value. In the following example, an API call that expects the type void* is marshaled
as AsAny:
VB
Declare Sub SetData Lib "..\LIB\UnmgdLib.dll" ( _
ByVal x As Short, _
<MarshalAsAttribute(UnmanagedType.AsAny)> _
ByVal o As Object)
6. Declare an empty function preceding the End Class statement for the form, and name the function MoveFile.
7. Apply the Public and Shared modifiers to the function declaration and set parameters for MoveFile based on the
arguments the Windows API function uses:
VB
Public Shared Function MoveFile( _
ByVal src As String, _
ByVal dst As String) _
As Boolean
' Leave the body of the function empty.
End Function
Your function can have any valid procedure name; the DllImport attribute specifies the name in the DLL. It also handles
interoperability marshaling for the parameters and return values, so you can choose Visual Studio data types that are
similar to the data types the API uses.
8. Apply the DllImport attribute to the empty function. The first parameter is the name and location of the DLL containing
the function you are calling. You do not need to specify the path for files located in the Windows system directories. The
second parameter is a named argument that specifies the name of the function in the Windows API. In this example, the
DllImport attribute forces calls to MoveFile to be forwarded to MoveFileW in KERNEL32.DLL. The MoveFileW method
copies a file from the path src to the path dst.
VB
<DllImport("KERNEL32.DLL", EntryPoint:="MoveFileW", SetLastError:=True, _
CharSet:=CharSet.Unicode, ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function MoveFile( _
ByVal src As String, _
ByVal dst As String) _
As Boolean
' Leave the body of the function empty.
End Function
10. Create a file named Test.txt and place it in the C:\Tmp directory on your hard drive. Create the Tmp directory if necessary.
11. Press F5 to start the application. The main form appears.
12. Click Button2. The message "The file was moved successfully" is displayed if the file can be moved.
See Also
Reference
Declare Statement
Auto
Alias
Lib
DllImportAttribute
MarshalAsAttribute
Concepts
Creating Prototypes in Managed Code
Callback Sample
Other Resources
COM Interop
Visual Basic: Samples
See Also
Tasks
Walkthrough: Calling Windows APIs
Concepts
A Closer Look at Platform Invoke
Platform Invoke Examples
Consuming Unmanaged DLL Functions
Defining a Method with Reflection Emit
Other Resources
COM Interop
Visual Basic Language Concepts
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
4. To obtain a Globally Unique Identifier (GUID), launch Guidgen.exe to start the Guidgen utility. Select Registry Format
from the list of formats provided by the Guidgen application. Click the New GUID button to generate the GUID, and click
the Copy button to copy the GUID to the Clipboard.
5. Replace the empty string for the ClassId with the GUID, removing the leading and trailing braces. For example, if the
GUID provided by Guidgen is "{2C8B0AEE-02C9-486e-B809-C780A11530FE}" then your code should appear as follows.
VB
Public Const ClassId As String = "2C8B0AEE-02C9-486e-B809-C780A11530FE"
6. Repeat the previous steps for the InterfaceId and EventsId constants, as in the following example.
VB
Public Const InterfaceId As String = "3D8B5BA4-FB8C-5ff8-8468-11BF6BD5CF91"
Public Const EventsId As String = "2B691787-6ED7-401e-90A4-B3B9C0360E31"
Note
Make sure that the GUIDs are new and unique; otherwise, your COM component could conflict with other COM compo
nents.
7. Add the ComClass attribute to ComClass1, specifying the GUIDs for the Class ID, Interface ID, and Events ID as in the
following example:
VB
<ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> _
Public Class ComClass1
8. COM classes must have a parameterless Public Sub New() constructor, or the class will not register correctly. Add a
parameterless constructor to the class:
VB
Public Sub New()
MyBase.New()
End Sub
9. Add properties, methods, and events to the class, ending it with an End Class statement. Select Build Solution from the
Build menu. Visual Basic builds the assembly and registers the COM object with the operating system.
Note
The COM objects you generate with Visual Basic 2005 cannot be used by other Visual Basic 2005 applications because
they are not true COM objects. Attempts to add references to such COM objects will raise an error. For details, see
COM Interoperability in .NET Framework Applications.
See Also
Tasks
Walkthrough: Implementing Inheritance with COM Objects
Troubleshooting Interoperability
Reference
ComClassAttribute Class
#Region Directive
Other Resources
COM Interop
COM Interoperability in .NET Framework Applications
Visual Basic Language Concepts
Troubleshooting Interoperability
When interoperating between COM and the managed code of the .NET Framework, you may encounter one or more of the
following common issues.
Interop Marshaling
At times, you may need to use data types that are not part of the .NET Framework. Interop assemblies handle most of the work
for COM objects, but you may need to control the data types used when managed objects are exposed to COM. For example,
structures in class libraries must specify the BStr unmanaged type on strings sent to COM objects created by Visual Basic 6.0
and earlier versions. In such cases, you can use the MarshalAsAttribute attribute to cause managed types to be exposed as
unmanaged types.
Exporting Fixed-Length Strings to Unmanaged Code
In Visual Basic 6.0 and earlier versions, strings are exported to COM objects as sequences of bytes without a null termination
character. For compatibility with other languages, Visual Basic 2005 includes a termination character when exporting strings.
The best way to address this incompatibility is to export strings lacking the termination character as arrays of Byte or Char.
Exporting Inheritance Hierarchies
Managed class hierarchies flatten out when exposed as COM objects. For example, if you define a base class with a member,
and then inherit the base class in a derived class that is exposed as a COM object, clients that use the derived class in the COM
object will not be able to use the inherited members. Base class members are accessible from COM objects only as instances of
a base class, and then only if the base class is also created as a COM object.
Overloaded Methods
Although you can create overloaded methods with Visual Basic, they are not supported by COM. When a class that contains
overloaded methods is exposed as a COM object, new method names are generated for the overloaded methods.
For example, consider a class with two overloads of the Synch method. When the class is exposed as a COM object, the new
generated method names could be Synch and Synch_2.
The renaming can cause two problems for consumers of the COM object.
1. Clients might not expect the generated method names.
2. The generated method names in the class exposed as a COM object can change when new overloads are added to the
class or its base class, which can cause versioning problems.
To solve both problems, give each method a unique name, instead of using overloading, when developing objects that will be
exposed as COM objects.
Use of COM Objects Through Interop Assemblies
You use interop assemblies almost as though they are managed code replacements for the COM objects they represent.
However, because they are wrappers and not actual COM objects, there are some differences between using interop
assemblies and standard assemblies. These areas of difference include the exposure of classes, and data types for parameters
and return values.
Classes Exposed as Both Interfaces and Classes
Unlike classes in standard assemblies, COM classes are exposed in interop assemblies as both an interface and a class that
represents the COM class. The interface's name is identical to that of the COM class. The name of the interop class is the same
as that of the original COM class, but with the word "Class" appended. For example, suppose you have a project with a
reference to an interop assembly for a COM object. If the COM class is named MyComClass, IntelliSense and the Object Browser
show an interface named MyComClass and a class named MyComClassClass.
Creating Instances of a .NET Framework Class
Generally, you create an instance of a .NET Framework class using the New statement with a class name. Having a COM class
represented by an interop assembly is the one case in which you can use the New statement with an interface. Unless you are
using the COM class with an Inherits statement, you can use the interface the same way as you would a class. The following
code demonstrates how to create a Command object in a project that has a reference to the Microsoft ActiveX Data Objects 2.8
Library COM object:
VB
Dim cmd As New ADODB.Command
However, if you are using the COM class as the base for a derived class, you must use the interop class that represents the
COM class, as in the following code:
VB
Class DerivedCommand
Inherits ADODB.CommandClass
End Class
Note
Interop assemblies implicitly implement interfaces that represent COM classes. You should not attempt to use the Impleme
nts statement to implement these interfaces or an error will result.
Dim db As DAO.Database
' Open the database.
Set db = DBEngine.OpenDatabase("C:\nwind.mdb")
' Use the database object.
Visual Basic 2005 requires that you always create instances of COM objects before you can use their methods. To use these
methods in Visual Basic 2005, declare a variable of the desired class and use the new keyword to assign the object to the object
variable. The Shared keyword can be used when you want to make sure that only one instance of the class is created.
VB
' Class level variable.
Shared DBEngine As New DAO.DBEngine
Sub DAOOpenRecordset()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim fld As DAO.Field
' Open the database.
db = DBEngine.OpenDatabase("C:\nwind.mdb")
ADODBConnect()
End Sub
' This is the event handler for the cn_ConnectComplete event raised
' by the ADODB.Connection object when a database is opened.
Dim x As Integer = 6
Dim y As Integer = 0
Try
x = CInt(x / y) ' Attempt to divide by zero.
' This procedure would fail silently without exception handling.
Catch ex As Exception
MsgBox("There was an error: " & ex.Message)
End Try
End Sub
This example raises an error as expected. However, if you try the same example without the Try...Catch...Finally block, the
error is ignored as if you used the OnError Resume Next statement. Without error handling, the division by zero silently fails.
Because such errors never raise unhandled exception errors, it is vital that you use some form of exception handling in event
handlers that handle events from COM objects.
Understanding COM interop errors
Without error handling, interop calls often generate errors that provide little information. Whenever possible, use structured
error handling to provide more information about problems when they occur. This can be particularly helpful when debugging
applications For example:
VB
Try
' Place call to COM object here.
Catch ex As Exception
' Display information about the failed call.
End Try
You can find information such as the error description, HRESULT, and the source of COM errors by examining the contents of
the exception object.
ActiveX Control Issues
Most ActiveX controls that work with Visual Basic 6.0 work with Visual Basic 2005 without trouble. The main exceptions are
container controls, or controls that visually contain other controls. Some examples of older controls that do not work correctly
with Visual Studio are:
Microsoft Forms 2.0 Frame control
Up-Down control, also known as the spin control
Sheridan Tab Control
There are only a few workarounds for unsupported ActiveX control problems. You can migrate existing controls to Visual
Studio if you own the original source code. Otherwise, you can check with software vendors for updated .NET-compatible
versions of controls to replace unsupported ActiveX controls.
Passing ReadOnly Properties of Controls ByRef
Visual Basic 2005 sometimes raises COM errors such as "Error 0x800A017F CTL_E_SETNOTSUPPORTED" when you pass
ReadOnly properties of some older ActiveX controls as ByRef parameters to other procedures. Similar procedure calls from
Visual Basic 6.0 do not raise an error, and the parameters are treated as if you passed them by value. The error message you
see in Visual Basic 2005 is the COM object reporting that you are attempting to change a property that does not have a
property Set procedure.
If you have access to the procedure being called, you can prevent this error by using the ByVal keyword to declare parameters
that accept ReadOnly properties. For example:
VB
Sub ProcessParams(ByVal c As Object)
'Use the arguments here.
End Sub
If you do not have access to the source code for the procedure being called, you can force the property to be passed by value
by adding an extra set of brackets around the calling procedure. For example, in a project that has a reference to the Microsoft
ActiveX Data Objects 2.8 Library COM object, you can use:
VB
Sub PassByVal(ByVal pError As ADODB.Error)
' The extra set of parentheses around the arguments
' forces them to be passed by value.
ProcessParams((pError.Description))
End Sub
Multithreaded Applications
With Visual Basic, you can write applications that perform multiple tasks simultaneously. Tasks with the potential of holding up
other tasks can execute on separate threads, a process known as multithreading or free threading.
Applications that use multithreading are more responsive to user input because the user interface stays active while processor-
intensive tasks execute on separate threads. Multithreading is also useful when creating scalable applications, because you can
add threads as the workload increases.
Using the BackgroundWorker Component
The most reliable way to create a multithreaded application is to use the BackgroundWorker component. This class manages a
separate thread dedicated to processing the method you specify. For an example, see Walkthrough: Multithreading.
To start an operation in the background, create a BackgroundWorker and listen for events that report the progress of your
operation and signal when your operation is finished. You can create the BackgroundWorker object programmatically, or you
can drag it onto your form from the Components tab of the Toolbox. If you create the BackgroundWorker in the Forms
Designer, it appears in the Component Tray, and its properties are displayed in the Properties window.
Setting Up for a Background Operation
To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this
event handler.
To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event.
To receive a notification when the operation is completed, handle the RunWorkerCompleted event.
The methods that handle the ProgressChanged and RunWorkerCompleted events can access the application's user
interface, because those events are raised on the thread that called the RunWorkerAsync method. However, the DoWork
event handler cannot manipulate any user-interface objects because it runs on the background thread.
Creating and Using Threads
If you need more control over the behavior of your application's threads, you can manage the threads yourself. However, be
aware that writing correct multithreaded applications can be difficult: Your application may stop responding or experience
transient errors due to race conditions. For more information, see Thread-Safe Components.
You create a new thread in Visual Basic by declaring a variable of type Thread and calling the constructor with the AddressOf
statement and the name of the procedure or method you want to execute on the new thread. The following code provides an
example:
VB
Dim TestThread As New System.Threading.Thread(AddressOf TestSub)
To stop the execution of a thread, use the Abort method, as in the following code:
VB
TestThread.Abort()
Besides starting and stopping threads, you can also pause threads by calling the Sleep or Suspend method, resume a
suspended thread with the Resume method, and destroy a thread using the Abort method, as in the following code:
VB
TestThread.Sleep(1000)
TestThread.Abort()
Thread Methods
The following table shows some of the methods you can use to control individual threads.
Meth Action
od
Start Causes a thread to start running.
Join Causes the current thread to wait for another thread to finish. If used with a time-out value, this method returns True if
the thread finishes in the allotted time.
Safe Points
Most of these methods are self-explanatory, but the concept of safe points may be new to you. Safe points are places in code
where it is safe for the common language runtime to perform automatic garbage collection, the process of releasing unused
variables and reclaiming memory. When you call the Abort or Suspend method of a thread, the common language runtime
analyzes the code and determines the location of an appropriate place for the thread to stop running.
Thread Properties
Threads also contain a number of useful properties, as shown in the following table:
Property Value
IsAlive Contains the value True if a thread is active.
IsBackground Gets or sets a Boolean that indicates if a thread is or should be a background thread. Background threads are l
ike foreground threads, but a background thread does not prevent a process from terminating. Once all foregr
ound threads belonging to a process have terminated, the common language runtime ends the process by call
ing the Abort method on background threads that are still alive.
Name Gets or sets the name of a thread. Most commonly used to discover individual threads when debugging.
Priority Gets or sets a value used by the operating system to prioritize thread scheduling.
ApartmentState Gets or sets the threading model used for a particular thread. Threading models are important when a thread
calls unmanaged code.
See Thread States for more information on thread states and methods.
Thread Priorities
Every thread has a priority property that determines how big or small a slice of processor time it gets to execute. The operating
system allocates longer time slices to high-priority threads and shorter time slices to low-priority threads. New threads are
created with the value of Normal, but you can change the Priority property to any value in the ThreadPriority enumeration.
See ThreadPriority for a detailed description of the various thread priorities.
Foreground and Background Threads
A foreground thread runs indefinitely, while a background thread terminates once the last foreground thread has stopped. You
can use the IsBackground property to determine or change the background status of a thread.
See Also
Concepts
Thread States
Parameters and Return Values for Multithreaded Procedures
Thread Synchronization
Multithreading with Forms and Controls
Other Resources
Multithreading in Components
Visual Basic Language Concepts
Thread States
The ThreadState property provides information about the status of a thread. Because threads can be in more than one state at
any given time, the value stored in ThreadState can be a combination of the values in the ThreadState enumeration. For
example, if a thread is blocked on a call to Wait, and another thread calls the Abort method on that same thread, the thread is
in both the WaitSleepJoin and the AbortRequested state at the same time.
Changing Thread States
Once a thread has started, you can call its methods to change its state. For example, you can cause a thread to pause for a fixed
number of milliseconds by calling System.Threading.Thread.Sleep(System.Int32). The Sleep method takes as a parameter a
time-out, which is the number of milliseconds that the thread remains blocked.
Calling Sleep with the argument Infinite causes a thread to sleep until it is interrupted by another thread that calls Interrupt.
The Interrupt method wakes the destination thread out of any wait state it may be in and causes an exception to be raised.
You can also pause a thread by calling Suspend. When a thread calls Suspend on itself, the call blocks until another thread
resumes it by calling Resume. When a thread calls Suspend on another thread, the call is non-blocking and causes the other
thread to pause. Calling Resume breaks another thread out of its suspended state and causes it to resume execution. Unlike
Sleep, Suspend does not immediately stop a thread; the suspended thread does not pause until the common language
runtime determines that it has reached a safe point.
The Abort method stops a running thread by raising a ThreadAbortException exception that causes the thread to die.
See Thread for detailed information about these methods.
See Also
Reference
SyncLock Statement
System.Threading
Concepts
Multithreaded Applications
Thread Synchronization
Parameters and Return Values for Multithreaded Procedures
Multithreading with Forms and Controls
Delegates and the AddressOf Operator
Other Resources
Multithreading in Components
Visual Basic Language Concepts
You can write a class that wraps the CalcArea function and creates fields to store input parameters, as follows:
VB
Class AreaClass
Public Base As Double
Public Height As Double
Public Area As Double
Sub CalcArea()
Area = 0.5 * Base * Height
MsgBox("The area is: " & Area)
End Sub
End Class
To use the AreaClass, you can create an AreaClass object, and set the Base and Height properties as shown in the following
code:
VB
Protected Sub TestArea()
Dim AreaObject As New AreaClass
Dim Thread As New System.Threading.Thread _
(AddressOf AreaObject.CalcArea)
AreaObject.Base = 30
AreaObject.Height = 40
Thread.Start()
End Sub
Notice that the TestArea procedure does not check the value of the Area field after calling the CalcArea method. Because
CalcArea runs on a separate thread, the Area field is not guaranteed to be set if you check it immediately after calling
Thread.Start. The next section discusses a better way to return values from multithreaded procedures.
You can provide parameters and return values to thread-pool threads by using the optional ByVal state-object variable of the
QueueUserWorkItem method. Thread-timer threads also support a state object for this purpose. For information on thread
pooling and thread timers, see Thread Pooling and Thread Timers.
See Also
Concepts
Thread States
Thread Pooling
Thread Synchronization
Events and Event Handlers
Multithreaded Applications
Multithreading with Forms and Controls
Delegates and the AddressOf Operator
Other Resources
Multithreading in Components
Visual Basic Language Concepts
Walkthrough: Multithreading
This walkthrough demonstrates how to create a multithreaded application that searches a text file for occurrences of a word. It
demonstrates:
Defining a class with a method that can be called by the BackgroundWorker component.
Handling events raised by the BackgroundWorker component.
Starting a BackgroundWorker component to run a method.
Implementing a Cancel button that stops the BackgroundWorker component.
4. Add a label next to each text box. Set the Text property for each label as shown in the following table.
Object Property Setting
First label Text Source File
5. Add a BackgroundWorker component from the Components section of the ToolBox to your form. It will appear in the
form's component tray.
6. Set the following properties for the BackgroundWorker1 object.
Property Setting
WorkerReportsProgress True
WorkerSupportsCancellation True
7.
To define the method that will run on a separate thread
1. From the Project menu, choose Add Class to add a class to the project. The Add New Item dialog box is displayed.
2. Select Class from the templates window and type Words.vb in the name field.
3. Click Add. The Words class is displayed.
4. Add an Option Compare statement to the top of the Words class, above the Class statement:
VB
Option Compare Text ' Case insensitive search.
' Use Option Compare Binary for case sensitive search.
If CompareString Is Nothing Or _
CompareString = System.String.Empty Then
Throw New Exception("CompareString not specified.")
End If
Try
' Open a new stream.
mystream = My.Computer.FileSystem.OpenTextFileReader(SourceFile)
' Do until the stream returns Nothing at end of file.
Do Until line Is Nothing
If worker.CancellationPending Then
e.Cancel = True
Exit Do
Else
line = mystream.ReadLine
WordCount += CountInString(line, CompareString)
LinesCounted += 1 ' Increment line count.
' This event handler is called when the background thread finishes.
' This method runs on the main thread.
To start and call a new thread that runs the WordCount method
1. Add the following procedures to your program:
VB
Private Sub BackgroundWorker1_DoWork( _
ByVal sender As Object, _
ByVal e As System.ComponentModel.DoWorkEventArgs) _
Handles BackgroundWorker1.DoWork
' Get the Works object and call the main method.
Dim WC As Words = CType(e.Argument, Words)
WC.CountWords(worker, e)
End Sub
Sub StartThread()
' This method runs on the main thread.
Me.WordsCounted.Text = "0"
2. Call the StartThread method from the Start button on your form:
VB
Private Sub Start_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Start.Click
StartThread()
End Sub
To implement a Cancel button that stops the thread
Call the StopThread procedure from the Click event handler for the Cancel button.
VB
Private Sub Cancel_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Cancel.Click
Testing
You can now test the application to make sure it works correctly.
To test the application
1. Press F5 to run the application.
2. When the form is displayed, enter the file path for the file you want to test in the sourceFile box. For example, assuming
your test file is named Test.txt, enter C:\Test.txt.
3. In the second text box, enter a word or phrase for the application to search for in the text file.
4. Click the Start button. The LinesCounted button should begin incrementing immediately. The application displays the
message "Finished Counting" when it is done.
Module Statement Words and phrases in an underlined, colored font are hyperlinks you can click to go immediately
to a relevant Help page.
object, variablename, argum Italic letters indicate placeholders for information that you supply.
entlist
{ Public | Friend | Private } In syntax, curly braces and vertical bars indicate a mandatory choice between two or more items.
You must choose one, and only one, of the items.
[ Protected | Friend ] In syntax, square brackets and vertical bars indicate two or more independent options. You can c
hoose any combination, or none, of the items.
[{ ByVal | ByRef }] In syntax, square brackets surrounding curly braces and vertical bars indicate that you can choos
e no more than one item, but you can also omit the items entirely.
memerbname1 In syntax, ellipses indicate an indefinite number of items of the kind immediately preceding the el
lipses.
...
In code, ellipses signify code omitted for the sake of clarity.
membernamen
ESC, ENTER Words in capital letters indicate key names and key sequences on your keyboard.
ALT+F1, CTRL+R A plus sign (+) between key names indicates a combination of keys. For example, ALT+F1 means
hold down the ALT key while pressing the F1 key.
Code Conventions
Sample code Description
sampleString = "Hello, world!" A fixed pitch font is used for code samples, as well as for code element
The preceding statement sets the value of sampleStrin s in explanatory text.
g to "Hello, world!".
' This is a comment. An apostrophe (') or the REM keyword introduces code comments.
REM This is also a comment.
sampleVar = "This is an " _ A space followed by an underscore ( _) at the end of a line continues th
& "example" _ e source code statement.
& " of how to continue code."
See Also
Tasks
How to: Break and Combine Statements in Code
Reference
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Concepts
Visual Basic Naming Conventions
Comments in Code
Other Resources
Visual Basic Reference
Visual Basic Language Reference
If Implements Imports In
NotOverridable Object Of On
- & &= *
*= / /= \
\= ^ ^= +
+= = -=
Note
EndIf, GoSub, Let, Variant, and Wend are retained as reserved keywords, although they are no longer used in Visual Basic.
Unreserved Keywords
The following keywords are not reserved, which means you can use them as names for your programming elements. However,
doing this is not recommended, because it can make your code hard to read and can lead to subtle errors that can be difficult
to find.
Ansi Assembly Auto Binary
#ExternalSource #Region
See Also
Reference
Visual Basic Run-Time Library Members
Keywords and Members by Task
Keywords Compared in Different Languages
Visual Basic Language Reference
Tab VerticalTab
Microsoft.VisualBasic.Conversion Module
ErrorToString Fix Hex Int
WeekDayName Year
Microsoft.VisualBasic.ErrObject Class
Clear Description Erl GetException
Raise Source
Microsoft.VisualBasic.FileSystem Module
ChDir ChDrive CurDir Dir
Write WriteLine
Microsoft.VisualBasic.Financial Module
DDB FV IPmt IRR
SYD
Microsoft.VisualBasic.Globals Module
ScriptEngine ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion
Microsoft.VisualBasic.Information Module
Err IsArray IsDate IsDBNull
Shell Switch
Microsoft.VisualBasic.Strings Module
Asc AscW Chr ChrW
Dates and Times Summary Converting and using date and time expressions.
Declarations and Constants Summary Declaring programming elements and defining constants.
Directories and Files Summary Controlling the file system and processing files.
Input and Output Summary Receiving input and displaying or printing output.
Information and Interaction Summary Starting other applications and processing events.
My Reference Documents My, a feature that allows easy and rapid application development by provid
ing intuitive access to commonly used methods, properties, and events used for progra
mming against the computer on which the application is running, the current applicatio
n, the application's resources, the application's settings, and so on
Arrays Summary
Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Verify an array. IsArray
Indicate a mapping between source lines and text external to the source. #ExternalSource Directive
See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
Conversion Summary
Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Convert ANSI value to string. Chr, ChrW
Convert one data type to another. CBool, CByte, CDate, CDbl, CDec, CInt, CLng, CSng, CShort, CStr, CType, Fix, Int
Convert date to day, month, weekday, or year. Day, Month, Weekday, Year
Set intrinsic data types Boolean, Byte, Char, Date, Decimal, Double, Integer, Long, Object, Short, Single, String
Verify data types IsArray, IsDate, IsDbNull, IsError, IsNothing, IsNumeric, IsReference
See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
Declare variables or constants. Const, Dim, Private, Protected, Public, Shadows, Shared, Static
Declare a class, delegate, enumeration, mod Class, Delegate, Enum, Module, Namespace, Structure
ule, namespace, or structure.
Get information about an object. GetType, IsArray, IsDate, IsDbNull, IsError, IsNothing, IsNumeric, IsReference,
SystemTypeName, TypeName, VarType, VbTypeName
Errors Summary
Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Generate run-time errors. Clear, Error, Raise
Financial Summary
Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Calculate depreciation. DDB, SLN, SYD
Get information about a file. EOF, FileAttr, FileDateTime, FileLen, FreeFile, GetAttr, Loc, LOF,
Seek
Math Summary
Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Derive trigonometric functions. Atn, Cos, Sin, Tan
My Reference
The My feature makes programming faster and easier by giving you intuitive access to commonly used methods, properties,
and events. This table lists the objects contained in My, and the actions that can be performed with each.
Action Object
Accessing application information and services. My.Application Object
Accessing the host computer and its resources, services, and data. My.Computer Object
Accessing XML Web services referenced by the current project. My.WebServices Object
See Also
Concepts
What's New in Visual Basic
Overview of the Visual Basic Application Model
Development with My
Visual Basic Language Reference
Operators Summary
Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Arithmetic ^, –, *, /, \, Mod, +, =
Concatenation &, +
Registry Summary
Visual Studio language keywords and run-time library members are organized by purpose and use.
Using the My feature provides you with greater productivity and performance in registry operations than these elements. For
more information, see My.Computer.Registry Object.
Action Language element
Delete program settings. DeleteSetting
Work with ASCII and ANSI values. Asc, AscW, Chr, ChrW
ComClassAttribute Class
The ComClassAttribute attribute instructs the compiler to add metadata that allows a class to be exposed as a COM object.
<System.AttributeUsage(System.AttributeTargets.Class, _
Inherited := False, AllowMultiple := False)> _
Public NotInheritable Class ComClassAttribute
Inherits System.Attribute
Remarks
Use ComClassAttribute to simplify the process of exposing COM components from Visual Basic. COM objects are very
different from .NET Framework assemblies; without the ComClassAttribute, you need to follow a number of steps to generate
a COM object from Visual Basic. For classes marked with ComClassAttribute, the compiler performs many of these steps
automatically.
Note
This attribute simplifies the creation of COM objects. To expose a class as a COM object, you must compile the project with th
e Register for COM Interop option selected in the Build section of the Configuration Properties dialog box.
Note
Although you can also expose a class created with Visual Basic as a COM object for unmanaged code to use, it is not a true C
OM object. For details, see COM Interoperability in .NET Framework Applications.
Example
To run this example, create a new Class Library application and add the following code to a class module.
VB
<ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> _
Public Class ComClass1
' Use the Region directive to define a section named COM Guids.
#Region "COM GUIDs"
' These GUIDs provide the COM identity for this class
' and its COM interfaces. You can generate
' these guids using guidgen.exe
Public Const ClassId As String = "7666AC25-855F-4534-BC55-27BF09D49D46"
Public Const InterfaceId As String = "54388137-8A76-491e-AA3A-853E23AC1217"
Public Const EventsId As String = "EA329A13-16A0-478d-B41F-47583A761FF2"
#End Region
Public Sub New()
MyBase.New()
End Sub
Function AddNumbers(ByVal X As Integer, ByVal Y As Integer)
AddNumbers = X + Y
End Function
End Class
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
Walkthrough: Creating COM Objects with Visual Basic 2005
Reference
ComClassAttribute Class Members
VBFixedArrayAttribute Class
VBFixedStringAttribute Class
System.Runtime.InteropServices
Concepts
Applying Interop Attributes
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
InterfaceShadows Property Indicates that a generated COM interface name shadows another member of the class or base clas
s.
Constructor
ComClassAttribute Constructor Initializes a new instance of the ComClassAttribute class.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
Walkthrough: Creating COM Objects with Visual Basic 2005
Reference
VBFixedArrayAttribute Class
VBFixedStringAttribute Class
ComClassAttribute Class
Shadows
System.Runtime.InteropServices
Concepts
Applying Interop Attributes
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
ComClassAttribute Constructor
Initializes a new instance of the ComClassAttribute class.
Parameters
_ClassID
Initializes the value of the ClassID property that is used to uniquely identify a class.
_InterfaceID
Initializes the value of the InterfaceID property that is used to uniquely identify an interface.
_EventId
Initializes the value of the EventID property that is used to uniquely identify an event.
Remarks
Use the constructor for the ComClassAttribute class to set the ClassID, InterfaceID, or EventID properties when applying
the ComClassAttribute to a class.
Requirements
Namespace: Microsoft.VisualBasic
Class: ComClassAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
Walkthrough: Creating COM Objects with Visual Basic 2005
Reference
ComClassAttribute Class
System.Runtime.InteropServices
Concepts
Attributes Used in Visual Basic
Object Lifetime: How Objects Are Created and Destroyed
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
ComClassAttribute.ClassID Property
Gets a class ID used to uniquely identify a class.
Return Value
Read-only. A string that can be used by the compiler to uniquely identify the class when a COM object is created.
Remarks
The constructor sets this property when the ComClassAttribute is applied to a class.
Requirements
Namespace: Microsoft.VisualBasic
Class: ComClassAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
ComClassAttribute Class
System.Runtime.InteropServices
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
ComClassAttribute.EventID Property
Gets an event ID used to uniquely identify an event.
Return Value
Read only. A string that can be used by the compiler to uniquely identify an event for the class when a COM object is created.
Remarks
The constructor sets this property when the ComClassAttribute is applied to a class.
Requirements
Namespace: Microsoft.VisualBasic
Class: ComClassAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
ComClassAttribute Class
System.Runtime.InteropServices
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
ComClassAttribute.InterfaceID Property
Gets an interface ID used to uniquely identify an interface.
Return Value
Read-only. A string that can be used by the compiler to uniquely identify an interface for the class when a COM object is
created.
Remarks
The constructor sets this property when the ComClassAttribute is applied to a class.
Requirements
Namespace: Microsoft.VisualBasic
Class: ComClassAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
ComClassAttribute Class
System.Runtime.InteropServices
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
ComClassAttribute.InterfaceShadows Property
Indicates that the COM interface name shadows another member of the class or base class.
Return Value
A Boolean value that indicates that the COM interface name shadows another member of the class or base class.
Remarks
Shadowing is when a member uses the same name as another member.
Requirements
Namespace: Microsoft.VisualBasic
Class: ComClassAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
ComClassAttribute Class
System.Runtime.InteropServices
Concepts
Shadowing in Visual Basic
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
HideModuleNameAttribute Class
The HideModuleNameAttribute attribute, when applied to a module, allows the module members to be accessed using only
the qualification needed for the module.
' Usage
<HideModuleName> Module moduleName
' Declaration
<System.AttributeUsage(System.AttributeTargets.Class, _
Inherited := False, AllowMultiple := False)> _
Public NotInheritable Class HideModuleNameAttribute
Inherits System.Attribute
Remarks
This attribute is useful for exposing module members without showing the module itself. When using IntelliSense in the Visual
Studio Integrated Development Environment (IDE) for Visual Basic, the module does not show in the statement completion list.
Instead, IntelliSense shows the module members.
Even when the module name is hidden, the module members are still accessible through the module.
If a member name conflicts with another identifier or with a member of another module with the
HideModuleNameAttribute attribute, then the member does not show in IntelliSense at the level of the module.
Example
This example shows how to use the HideModuleNameAttribute attribute to add a Database object to My, which can be
accessed through My.Database.
VB
Namespace My
<HideModuleName()> Module CustomMyDatabase
Public ReadOnly Property Database() As MyDatabase
Get
Return databaseValue
End Get
End Property
Private ReadOnly databaseValue As MyDatabase = New MyDatabase
End Module
End Namespace
Class MyDatabase
' The members of the My.Database object go here.
End Class
VBFixedArrayAttribute Class
Indicates that an array in a structure or non-local variable should be treated as a fixed-length array.
<System.AttributeUsage(System.AttributeTargets.Field, _
Inherited := False, AllowMultiple := False)> _
Public NotInheritable Class VBFixedArrayAttribute
Inherits System.Attribute
Remarks
Visual Basic arrays are of variable length by default. This attribute is useful when using Visual Basic file input and output
functions, such as FileGet and FilePut, and API calls that require fixed-length arrays.
Example
VB
Structure Book
<VBFixedArray(4)> Public Chapter() As Integer
End Structure
Sub WriteData()
Dim FileNum As Integer = FreeFile()
Dim MyBook As Book
ReDim MyBook.Chapter(4)
' Add code to populate the array.
MyBook.Chapter(0) = 1
MyBook.Chapter(1) = 2
MyBook.Chapter(2) = 3
MyBook.Chapter(3) = 4
MyBook.Chapter(4) = 5
' Write the array to a file.
FileOpen(FileNum, "C:\testfile", OpenMode.Binary, _
OpenAccess.Write, OpenShare.Default)
FilePut(FileNum, MyBook) ' Write data.
FileClose(FileNum)
End Sub
Note
The VBFixedArrayAttribute is informational and does not allocate any storage. The purpose of this attribute is to modify ho
w arrays in structures and non-local variables are used by methods or API calls that recognize the VBFixedArrayAttribute.
Keep in mind that this attribute does not convert a variable length array to a fixed array and that you must still allocate array
storage using Dim or ReDim statements.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedArrayAttribute Class Members
VBFixedStringAttribute Class
ComClassAttribute Class
FileGet Function
FilePut Function
FileOpen Function
MarshalAsAttribute
Other Resources
Attributes in Visual Basic
XML and SOAP Serialization
Visual Basic Language Reference
VBFixedArrayAttribute Constructor
Initializes the value of the Bounds property.
Parameters
UpperBound1
Initializes the value of upper field, which represents the size of the first dimension of the array.
UpperBound2
Initializes the value of upper field, which represents the size of the second dimension of the array.
Remarks
The constructor runs when the VBFixedArrayAttribute attribute is applied to an array.
Requirements
Namespace: Microsoft.VisualBasic
Class: VBFixedArrayAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedStringAttribute Class
ComClassAttribute Class
MarshalAsAttribute Class
Concepts
Attributes Used in Visual Basic
Object Lifetime: How Objects Are Created and Destroyed
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
VBFixedArrayAttribute.Bounds Property
Returns the bounds of the array.
Return Value
Contains an integer array that represents the bounds of the array.
Remarks
The constructor sets this property when the VBFixedArrayAttribute is applied to an array.
Requirements
Namespace: Microsoft.VisualBasic
Class: VBFixedArrayAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedStringAttribute Class
ComClassAttribute Class
MarshalAsAttribute
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
VBFixedArrayAttribute.Length Property
Returns the size of the array.
Return Value
Contains an integer that represents the number of elements in the array.
Remarks
The constructor sets this property when the VBFixedArrayAttribute is applied to an array.
Requirements
Namespace: Microsoft.VisualBasic
Class: VBFixedArrayAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedStringAttribute Class
ComClassAttribute Class
MarshalAsAttribute Class
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
VBFixedStringAttribute Class
Indicates that a string should be treated as if it were fixed length.
<System.AttributeUsage(System.AttributeTargets.Field, _
Inherited := False, AllowMultiple := False)> _
Public NotInheritable Class VBFixedStringAttribute
Inherits System.Attribute
Remarks
Visual Basic strings are of variable length by default. This attribute is useful when using Visual Basic file input and output
functions such as FileGet and FilePut that require fixed length strings.
Note
The VBFixedStringAttribute attribute specifies the length of a string in bytes, not characters.
Example
VB
Structure Person
Public ID As Integer
Public MonthlySalary As Decimal
Public LastReviewDate As Long
<VBFixedString(15)> Public FirstName As String
<VBFixedString(15)> Public LastName As String
<VBFixedString(15)> Public Title As String
<VBFixedString(150)> Public ReviewComments As String
End Structure
Note
The VBFixedStringAttribute is informational and cannot be used to convert a variable length string to a fixed string. The pu
rpose of this attribute is to modify how strings in structures and non-local variables are used by methods or API calls that rec
ognize the VBFixedStringAttribute, such as the Len and FilePut functions. Keep in mind that this attribute does not change
the actual length of the string itself.
VBFixedStringAttribute Constructor
Initializes the value of the SizeConst field.
Parameters
Length
The length of the fixed string.
Remarks
The constructor runs when the VBFixedStringAttribute attribute is applied to a string.
Smart Device Developer Notes
This constructor is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Class: VBFixedStringAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedStringAttribute Class
StringBuilder Class
MarshalAsAttribute Class
Concepts
Attributes Used in Visual Basic
Object Lifetime: How Objects Are Created and Destroyed
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
VBFixedStringAttribute.Length Property
Gets the length of the string.
Return Value
Returns the length of the string.
Remarks
The constructor for this attribute sets this property when the VBFixedStringAttribute is applied to a string.
Smart Device Developer Notes
This property is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Class: VBFixedStringAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedStringAttribute Class
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
AppWinStyle Enumeration
Indicates the window style to use for the invoked program when calling the Shell function.
Remarks
When you issue Shell commands, you can use the following enumeration members in your code in place of the actual values.
The Style argument takes the AppWinStyle enumeration members.
Members
Member Constant Description
Hide vbHide Window is hidden and focus is passed to the hidden window.
NormalFocus vbNormalFocus Window has focus and is restored to its original size and position.
NormalNoFocus vbNormalNoFocus Window is restored to its most recent size and position. The currently active window r
emains active.
MinimizedNoFo vbMinimizedNoFo Window is displayed as an icon. The currently active window remains active.
cus cus
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
Shell Function
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference
AudioPlayMode Enumeration
Indicates how to play sounds when calling audio methods.
Remarks
You can use the AudioPlayMode enumeration members to control how the My.Computer.Audio.Play Method plays sounds.
Members
Member Description
WaitToCo Causes the My.Computer.Audio.Play method to play the sound, and waits until it completes before calling code
mplete continues.
Backgroun Causes the My.Computer.Audio.Play method to play the sound in the background. The calling code continues t
d o execute.
Backgroun Causes the My.Computer.Audio.Play method to play the sound in the background until the
dLoop My.Computer.Audio.Stop Method is called. The calling code continues to execute.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.Audio.Play Method
AudioPlayMode
Concepts
Intrinsic Constants and Enumerations
Visual Basic Language Reference
BuiltInRole Enumeration
Indicates the type of role to check when calling the My.User.IsInRole Method.
Remarks
This enumeration provides functionality similar to the WindowsBuiltInRole enumeration.
These roles represent the local Windows groups common to most installations of Windows NT, Windows 2000, and Windows
XP.
Members
Member Description
AccountOp Account operators manage the user accounts on a computer or domain.
erator
Administrat Administrators have complete and unrestricted access to the computer or domain.
or
BackupOpe Backup operators can override security restrictions for the sole purpose of backing up or restoring files.
rator
PowerUser Power users possess most administrative permissions with some restrictions. Thus, power users can run legacy a
pplications, in addition to certified applications.
User Users are prevented from making accidental or intentional system-wide changes. Thus, users can run certified ap
plications, but not most legacy applications.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.User.IsInRole Method
Microsoft.VisualBasic.ApplicationServices.BuiltInRole
Concepts
Intrinsic Constants and Enumerations
Visual Basic Language Reference
CallType Enumeration
Indicates the type of procedure being invoked when calling the CallByName function.
Remarks
When you call the CallByName function, you can use the following CallType enumeration members in your code in place of
the actual values. The UseCallType argument takes the CallType enumeration members.
Members
Member Constant Description
Method vbMethod A method is being invoked.
CompareMethod Enumeration
Indicates how to compare strings when calling comparison functions.
Remarks
When you call comparison functions, you can use the CompareMethod enumeration in your code in place of the actual
values. The Compare argument takes the CompareMethod enumeration members.
Members
Member Constant Description
Binary vbBinaryCompare Performs a binary comparison.
D A Boolean value that can be set in the Project Properties dialog box. By default, the Debug configuration for a project def
EB ines DEBUG. When DEBUG is defined, Debug class methods generate output to the Output window. When it is not define
U d, Debug class methods are not compiled and no Debug output is generated.
G
TA A string representing the output type for the project or the setting of the command-line /target option. The possible value
R s of TARGET are: "winexe" for a Windows application, "exe" for a console application, "library" for a class library, and "modu
GE le" for a module. The /target option can be set in the Visual Studio integrated development environment. For more inform
T ation, see /target.
TR A Boolean value that can be set in the Project Properties dialog box. By default, all configurations for a project define TR
A ACE. When TRACE is defined, Trace class methods generate output to the Output window. When it is not defined, Trace cl
CE ass methods are not compiled and no Trace output is generated.
V A number representing the Visual Basic version, in major.minor format. The version number for Visual Basic 2005 is 8.0.
BC
_V
ER
_ A string representing the type of project being built. This controls which My objects are available in code. For more inform
M ation, see How My Depends on Project Type.
YT
YP
E
You can use these constants only for conditional compilation; they cannot be used in executable code.
Example
This example uses the TARGET conditional compilation constant to determine whether to compile certain statements.
VB
#If TARGET = "winexe" Then
' Insert code to be compiled for a Windows application.
#ElseIf TARGET = "exe" Then
' Insert code to be compiled for a console application.
#End If
Requirements
The Visual Studio integrated development environment defines the CONFIG, DEBUG, TRACE, and _MYTYPE conditional
compilation constants.
The Visual Basic compiler defines the TARGET and VBC_VER conditional compilation constants. The TARGET, VBC_VER, and
_MYTYPE constants are not available in compiler versions before Visual Basic 2005.
See Also
Tasks
How to: Declare Conditional Compilation Constants
Reference
#If...Then...#Else Directives
#Const Directive
/target (Visual Basic)
Concepts
Conditional Compilation Overview
How My Depends on Project Type
Visual Basic Language Reference
DateFormat Enumeration
Indicates how to display dates when calling the FormatDateTime function.
Remarks
When you call the FormatDateTime function, you can use the following enumeration members in your code in place of the
actual values.
Note
You can access your computer's regional settings by double-clicking the Regional Options icon, found in Control Panel.
Members
Mem Consta Description
ber nt
Gene vbGen For real numbers, displays a date and time. If the number has no fractional part, displays only a date. If the num
ralDa eralDa ber has no integer part, displays time only. Date and time display is determined by your computer's regional se
te te ttings.
Long vbLon Displays a date using the long-date format specified in your computer's regional settings.
Date gDate
Short vbShor Displays a date using the short-date format specified in your computer's regional settings.
Date tDate
Long vbLon Displays a time using the long-time format specified in your computer's regional settings.
Time gTime
Short vbShor Displays a time using the short-time format specified in your computer's regional settings.
Time tTime
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
FormatDateTime Function (Visual Basic)
Concepts
Custom DateTime Format Strings
When to Use an Enumeration
Visual Basic Language Reference
DateInterval Enumeration
Indicates how to determine and format date intervals when calling date-related functions.
Remarks
When you call date-related functions, you can use enumeration members in your code in place of the actual values.
The DateInterval enumeration defines constants used with date-related functions to identify how date intervals are
determined and formatted. The following table lists the DateInterval enumeration members.
Members
Member Description
Day Day of month (1 through 31)
Year Year
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
DateFormat Enumeration
DueDate Enumeration
DatePart Function (Visual Basic)
DateAdd Function (Visual Basic)
DateDiff Function (Visual Basic)
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference
DeleteDirectoryOption Enumeration
Specifies what should be done when a directory that is to be deleted contains files or directories.
Remarks
This enumeration is used with the My.Computer.FileSystem.DeleteDirectory Method.
Members
Member Description
DeleteAllContents Delete the contents of the directory along with the directory. Default.
ThrowIfDirectoryNon Throw an IOException if the directory is not empty. The Data property of the exception lists the file(s)
Empty that could not be deleted.
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: DeleteDirectoryOption
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Delete a Directory in Visual Basic
Reference
My.Computer.FileSystem.DeleteDirectory Method
Microsoft.VisualBasic.FileIO.DeleteDirectoryOption
Visual Basic Language Reference
DueDate Enumeration
Indicates when payments are due when calling financial methods.
Remarks
When you call financial functions, you can use enumeration members in your code in place of the actual values.
The DueDate enumeration defines constants used to identify when payments are due.
Members
Member Description
BegOfPeriod Falls at the beginning of the date interval
FieldType Enumeration
Indicates whether text fields are delimited or fixed width.
Remarks
This enumeration is used with the TextFieldParser Object.
Members
Member Name Description
Delimited Indicates that the fields are delimited.
FileAttribute Enumeration
Indicates the file attributes to use when calling file-access functions.
Remarks
When you call the Dir, GetAttr, or SetAttr functions, you can use the FileAttribute enumeration in your code in place of the
actual values.
The Attributes argument takes the FileAttribute enumeration members.
When performing file I/O operations, the My.Computer.FileSystem object provides greater performance and ease of use
than legacy file I/O methods. For more information, see My.Computer.FileSystem Object.
Members
Member Constant Description
Normal vbNormal Normal (default for Dir and SetAttr). No special characteristics apply to this file.
Volume vbVolume Volume label. This attribute is not valid when used with SetAttr.
FirstDayOfWeek Enumeration
Indicates the first day of the week to use when calling date-related functions.
Remarks
When you call date-related functions, you can use the following enumeration members in your code in place of the actual
values.
Some date-related functions take a DayOfWeek argument, a WeekOfYear argument, or both. The FirstDayOfWeek
enumeration specifies the valid values for the DayOfWeek arguments, as well as the possible return values from the functions.
The DayOfWeek argument takes the FirstDayOfWeek enumeration members.
Date-related functions also return FirstDayOfWeek values (except System).
Members
Member Constant Description
System vbUseSystemDayOfWeek The first day of the week as specified in your system settings
FirstWeekOfYear Enumeration
Indicates the first week of the year to use when calling date-related functions.
Remarks
When you call date-related functions, you can use the following enumeration members in your code in place of the actual
values.
Some date-related functions take a DayOfWeek argument, a WeekOfYear argument, or both. The FirstWeekOfYear
enumeration specifies the valid values for the WeekOfYear arguments, as well as the possible return values from the functions.
The WeekOfYear argument takes the FirstWeekOfYear enumeration members.
Members
Member Constant Description
System vbUseSystem The day of the week specified in your system settings as the first day of the week
FirstFourDays vbFirstFourDays The first week that has at least four days in the new year
MsgBoxResult Enumeration
Indicates which button was pressed on a message box, returned by the MsgBox function.
Remarks
When you call the MsgBox function, you can use the MsgBoxResult enumeration in your code in place of the actual values.
The MsgBox function returns a MsgBoxResult enumeration value.
Members
Member Constant Description
OK vbOK OK button was pressed.
MsgBoxStyle Enumeration
Indicates which buttons to display when calling the MsgBox function.
Remarks
When you call the MsgBox function, you can use the MsgBoxStyle enumeration in your code in place of the actual values.
The Buttons argument takes the MsgBoxStyle enumeration members.
Members
Member Constant Description
OKOnly vbOKOnly OK button only (default).
OpenAccess Enumeration
Indicates how to open a file when calling file-access functions.
Remarks
When you call file access-related functions, you can use enumeration members in your code in place of the actual values.
The OpenAccess enumeration defines constants used to identify whether a file can be read from (Read), written to (Write), or
both (ReadWrite). A file opened for Read access cannot be modified, only read from. The following table lists the
OpenAccess enumeration members.
When performing file I/O operations, the My.Computer.FileSystem object provides greater performance and ease of use
than legacy file I/O methods. For more information, see My.Computer.FileSystem Object.
Members
Member Description
Default Read and write access permitted. This is the default.
OpenMode Enumeration
Indicates how to open a file when calling file-access functions.
Remarks
When you call file access–related functions, you can use enumeration members in your code in place of the actual values.
The OpenMode enumeration defines constants used to set file access modes. The following table lists the OpenMode
enumeration members.
Input, Output, and Append are used when sequentially accessing files, such as text files, while Binary is used for binary file
access and Random for random file access.
When sequentially accessing a file, you cannot change its data. You can read the data, append to it, or overwrite it with new
data. If you open it for input, the contents of the file will be overwritten, even if you do not directly write to the file.
When performing file I/O operations, the My.Computer.FileSystem object provides greater performance and ease of use
than legacy file I/O methods. For more information, see My.Computer.FileSystem Object.
Members
Member Description
Append File opened to append to it. Default.
OpenShare Enumeration
Indicates how to open a file when calling file-access functions.
Remarks
When you call file access–related functions, you can use enumeration members in your code in place of the actual values.
The OpenShare enumeration defines constants that specify whether or not other processes can access the file while your
application has it open. The following table lists the OpenShare enumeration members.
When performing file I/O operations, the My.Computer.FileSystem object provides greater performance and ease of use
than legacy file I/O methods. For more information, see My.Computer.FileSystem Object.
Members
Member Description
Default LockReadWrite. This is the default.
n/a vbNullStrin String having valu Not the same as a zero-length string (""); used for calling external procedures.
g e0
n/a vbObjectErr -2147221504 Error number. User-defined error numbers should be greater than this value. For
or example:
Err.Raise(Number) = vbObjectError + 1000
Quote n/a Chr(34) Quotation mark character (" or ') used to enclose values.
Requirements
Namespace: Microsoft.VisualBasic
Module: Constants
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Print, PrintLine Functions
Write, WriteLine Functions
Concepts
Intrinsic Constants and Enumerations
Constants Overview
Constants Declared by Visual Basic
Visual Basic Language Reference
RecycleOption Enumeration
Specifies whether a file should be deleted permanently or placed in the Recycle Bin.
Remarks
This enumeration is used with the My.Computer.FileSystem.DeleteDirectory Method and the
My.Computer.FileSystem.DeleteFile Method.
To protect users against accidental deletion of important files, the Recycle Bin collects deleted files and provides a method for
restoring those files. You must explicitly delete the files from the Recycle Bin to make the deletion permanent. Until the files
are deleted from the Recycle Bin, the disk space occupied by those files is unavailable for other uses.
Sometimes it is beneficial to bypass the Recycle Bin, especially if you are deleting a large number of files (or a smaller number
of very large files) that you are sure are no longer needed, and you want to reclaim the disk space.
Members
Member Description
DeletePermanently Delete the file or directory permanently. Default.
SearchOption Enumeration
Specifies whether to search all or only top-level directories.
Remarks
This enumeration is used with the My.Computer.FileSystem.GetFiles Method, My.Computer.FileSystem.GetDirectories Method,
and My.Computer.FileSystem.FindInFiles Method.
Members
Member Description
SearchAllSubDirectories Search the specified directory and all subdirectories within it. Default.
TriState Enumeration
Indicates a Boolean value or whether the default should be used when calling number-formatting functions.
Remarks
When you call number-formatting functions, you can use the following enumeration members in your code in place of the
actual values.
Members
Member Description
True True. The numeric value of this member is -1.
UICancelOption Enumeration
Specifies whether an exception is thrown if the user clicks Cancel during an operation.
Remarks
This enumeration determines whether an IOException is thrown when a user clicks Cancel during an operation. In either case,
the operation is canceled.
Members
Member Name Description
DoNothing Do nothing when the user clicks Cancel.
UIOption Enumeration
Specifies which dialog boxes to show when copying, deleting, or moving files or directories.
Remarks
This enumeration is used with My.Computer.FileSystem.CopyDirectory Method, My.Computer.FileSystem.CopyFile Method,
My.Computer.FileSystem.DeleteDirectory Method, My.Computer.FileSystem.DeleteFile Method,
My.Computer.FileSystem.MoveDirectory Method, and My.Computer.FileSystem.MoveFile Method.
Members
Member Description
OnlyErrorDialogs Only show error dialog boxes and hide progress dialog boxes. Default.
AllDialogs Show progress dialog box and any error dialog boxes.
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: UIOption
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.FileSystem.CopyDirectory Method
My.Computer.FileSystem.CopyFile Method
My.Computer.FileSystem.DeleteDirectory Method
My.Computer.FileSystem.DeleteFile Method
My.Computer.FileSystem.MoveDirectory Method
My.Computer.FileSystem.MoveFile Method
Microsoft.VisualBasic.FileIO.UIOption
Visual Basic Language Reference
VariantType Enumeration
Indicates the type of a variant object, returned by the VarType function.
Remarks
When you call the VarType function, you can use enumeration members in your code in place of the actual values.
The VariantType enumeration defines constants used to identify possible Variant types. The following table lists the
VariantType enumeration members.
Members
Memb Constan Description
er t
Array vbArray Array.
DataO DataObject.
bject
Date vbDate Date. (0:00:00 on January 1, 0001 through 11:59:59 PM on December 31, 9999.)
Decim vbDeci Decimal. (0 through +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; 0 through +/-7.92
al mal 28162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/
-0.0000000000000000000000000001.)
Doubl vbDoub Double. (-1.79769313486231E+308 through -4.94065645841247E-324 for negative values; 4.940656458
e le 41247E-324 through 1.79769313486231E+308 for positive values.)
Error System.Exception
UserD vbUser User-defined type. Each member of the structure has a range determined by its data type and independent o
efined Defined f the ranges of the other members.
Type Type
VbStrConv Enumeration
Indicates which type of conversion to perform when calling the StrConv function.
Remarks
When you call the StrConv function, you can use the following enumeration members in your code in place of the actual
values. The Conversion argument takes the VbStrConv enumeration members.
Members
Member Constant Description
UpperCase vbUpperCase Converts the string to uppercase characters.
ProperCase vbProperCase Converts the first letter of every word in the string to uppercase.
Wide vbWide Converts narrow (single-byte) characters in the string to wide (double-byte) characters. A
pplies to Asian locales.
Narrow vbNarrow Converts wide (double-byte) characters in the string to narrow (single-byte) characters. A
pplies to Asian locales.
Katakana vbKatakana Converts Hiragana characters in the string to Katakana characters. Applies to Japanese loc
ale only.
Hiragana vbHiragana Converts Katakana characters in the string to Hiragana characters. Applies to Japanese loc
ale only.
LinguisticCasin vbLinguisticCasi Converts the string from file system rules for casing to linguistic rules.
g ng
Smart Device Developer Notes
This enumeration is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
StrConv Function
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Other Resources
Introduction to Strings in Visual Basic
Visual Basic Language Reference
Date DateTime 8 bytes 0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on December 3
1, 9999
Object Object (class) 4 bytes on 32 Any type can be stored in a variable of type Object
-bit platform
8 bytes on 64
-bit platform
Single (single-p Single 4 bytes -3.4028235E+38 through -1.401298E-45 † for negative values;
recision floating
-point) 1.401298E-45 through 3.4028235E+38 † for positive values
User-Defined (s (inherits from Depends on i Each member of the structure has a range determined by its data type and i
tructure) ValueType) mplementing ndependent of the ranges of the other members
platform
† In scientific notation, "E" refers to a power of 10. So 3.56E+2 signifies 3.56 x 10 2 or 356, and 3.56E-2 signifies 3.56 / 10 2 or
0.0356.
Note
For strings containing text, use the StrConv function to convert from one text format to another.
Memory Consumption
When you declare an elementary data type, it is not safe to assume that its memory consumption is the same as its nominal
storage allocation. This is due to the following considerations:
Storage Assignment. The common language runtime can assign storage based on the current characteristics of the
platform on which your application is executing. If memory is nearly full, it might pack your declared elements as closely
together as possible. In other cases it might align their memory addresses to natural hardware boundaries to optimize
performance.
Platform Width. Storage assignment on a 64-bit platform is different from assignment on a 32-bit platform.
Composite Data Types
The same considerations apply to each member of a composite data type, such as a structure or an array. You cannot rely on
simply adding together the nominal storage allocations of the type's members. Furthermore, there are other considerations,
such as the following:
Overhead. Some composite types have additional memory requirements. For example, an array uses extra memory for
the array itself and also for each dimension. On a 32-bit platform, this overhead is currently 12 bytes plus 8 bytes for
each dimension. On a 64-bit platform this requirement is doubled.
Storage Layout. You cannot safely assume that the order of storage in memory is the same as your order of declaration.
You cannot even make assumptions about byte alignment, such as a 2-byte or 4-byte boundary. If you are defining a
class or structure and you need to control the storage layout of its members, you can apply the StructLayoutAttribute
attribute to the class or structure.
Object Overhead
An Object referring to any elementary or composite data type uses 4 bytes in addition to the data contained in the data type.
See Also
Reference
Type Conversion Functions
Conversion Summary
StrConv Function
StructLayoutAttribute Class
Concepts
Type Characters
Efficient Use of Data Types
Visual Basic Language Reference
See Also
Tasks
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Conversion Summary
CType Function
System.Boolean
Concepts
Efficient Use of Data Types
Visual Basic Language Reference
Option Strict On
Dim charVar As Char
' The following statement attempts to convert a String literal to Char.
' Because Option Strict is On, it generates a compiler error.
charVar = "Z"
' The following statement succeeds because it specifies a Char literal.
charVar = "Z"C
Programming Tips
Negative Numbers. Char is an unsigned type and cannot represent a negative value. In any case, you should not use
Char to hold numeric values.
Interop Considerations. If you are interfacing with components not written for the .NET Framework, for example
Automation or COM objects, keep in mind that character types have a different data width (8 bits) in other environments.
If you are passing an 8-bit argument to such a component, declare it as Byte instead of Char in your new Visual Basic
code.
Widening. The Char data type widens to String. This means you can convert Char to String without encountering a
System.OverflowException error.
Type Characters. Appending the literal type character C to a single-character string literal forces it to the Char data type.
Char has no identifier type character.
Framework Type. The corresponding type in the .NET Framework is the System.Char structure.
See Also
Tasks
How to: Optimize Storage of Positive Integers With Unsigned Types
How to: Call a Windows Function that Takes Unsigned Types
Reference
Data Type Summary (Visual Basic)
String Data Type (Visual Basic)
Type Conversion Functions
Conversion Summary
Asc, AscW Functions
Chr, ChrW Functions
System.Char
Concepts
Efficient Use of Data Types
Visual Basic Language Reference
Alternatively, you can use one of the overloaded constructors of the DateTime structure to assemble a date and time value. The
following example creates a value to represent May 31, 1993 at 12:14 in the afternoon.
Hour Format
You can specify the time value in either 12-hour or 24-hour format, for example #1:15:30 PM# or #13:15:30#. However, if you
do not specify either the minutes or the seconds, you must specify AM or PM.
Date and Time Defaults
If you do not include a date in a date/time literal, Visual Basic sets the date part of the value to January 1, 0001. If you do not
include a time in a date/time literal, Visual Basic sets the time part of the value to the start of the day, that is, midnight (0:00:00).
Type Conversions
If you convert a Date value to the String type, Visual Basic renders the date according to the short date format specified by the
run-time locale, and it renders the time according to the time format (either 12-hour or 24-hour) specified by the run-time
locale.
Programming Tips
Interop Considerations. If you are interfacing with components not written for the .NET Framework, for example
Automation or COM objects, keep in mind that date/time types in other environments are not compatible with the Visual
Basic Date type. If you are passing a date/time argument to such a component, declare it as Double instead of Date in
your new Visual Basic code, and use the conversion methods System.DateTime.FromOADate(System.Double) and
System.DateTime.ToOADate.
Type Characters. Date has no literal type character or identifier type character. However, the compiler treats literals
enclosed within number signs (# #) as Date.
Framework Type. The corresponding type in the .NET Framework is the System.DateTime structure.
Example
A variable or constant of the Date data type holds both the date and the time. The following example illustrates this.
See Also
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Conversion Summary
System.DateTime
Concepts
Efficient Use of Data Types
Data Type Changes for Visual Basic 6.0 Users
Visual Basic Language Reference
The compiler interprets a literal as Long unless it is followed by a literal type character. The declaration for bigDec1 does not
produce an overflow because its value is within the range for Long. However, the value for bigDec2 is too large for Long, so
the compiler generates an error. The literal type character D solves the problem for bigDec3 by forcing the compiler to
interpret the literal as Decimal.
See Also
Reference
Data Type Summary (Visual Basic)
Single Data Type (Visual Basic)
Double Data Type (Visual Basic)
Type Conversion Functions
Conversion Summary
System.Decimal
System.Decimal.#ctor(System.Int32[])
Concepts
Efficient Use of Data Types
Visual Basic Language Reference
See Also
Reference
Data Type Summary (Visual Basic)
Long Data Type (Visual Basic)
Short Data Type (Visual Basic)
Type Conversion Functions
Conversion Summary
System.Int32
Concepts
Integer Data Type for Visual Basic 6.0 Users
Efficient Use of Data Types
Visual Basic Language Reference
The Object data type is a reference type. However, Visual Basic treats an Object variable as a value type when it refers to data
of a value type.
Storage
Whatever data type it refers to, an Object variable does not contain the data value itself, but rather a pointer to the value. It
always uses four bytes in computer memory, but this does not include the storage for the data representing the value of the
variable. Because of the code that uses the pointer to locate the data, Object variables holding value types are slightly slower
to access than explicitly typed variables.
Programming Tips
Interop Considerations. If you are interfacing with components not written for the .NET Framework, for example
Automation or COM objects, keep in mind that pointer types in other environments are not compatible with the Visual
Basic Object type.
Performance. A variable you declare with the Object type is flexible enough to contain a reference to any object.
However, when you invoke a method or property on such a variable, you always incur late binding (at run time). To force
early binding (at compile time) and better performance, declare the variable with a specific class name, or cast it to the
specific data type.
When you declare an object variable, try to use a specific class type, for example OperatingSystem, instead of the
generalized Object type. You should also use the most specific class available, such as TextBox instead of Control, so that
you can access its properties and methods. You can usually use the Classes list in the Object Browser to find available
class names.
Widening. All data types and all reference types widen to the Object data type. This means you can convert any type to
Object without encountering a System.OverflowException error.
However, if you convert between value types and Object, Visual Basic performs operations called boxing and unboxing,
which make execution slower.
Type Characters. Object has no literal type character or identifier type character.
Framework Type. The corresponding type in the .NET Framework is the System.Object class.
Example
The following example illustrates an Object variable pointing to an object instance.
See Also
Tasks
How to: Determine Whether Two Objects Are Related
How to: Determine Whether Two Objects Are Identical
Reference
Data Type Summary (Visual Basic)
Object Class
Type Conversion Functions
Conversion Summary
Concepts
Efficient Use of Data Types
Object as the Universal Data Type
Visual Basic Language Reference
Note that the contiguous quotation marks representing a quotation mark in the string are independent of the quotation marks
that begin and end the String literal.
String Manipulations
Once you assign a string to a String variable, that string is immutable, meaning you cannot change its length or contents.
When you alter a string in any way, Visual Basic creates a new string and abandons the previous one. The String variable then
points to the new string.
You can manipulate the contents of a String variable using a variety of string functions. The following example illustrates the
Left Function (Visual Basic).
A string created by another component might be padded with leading or trailing spaces. If you receive such a string, you can
use the Trim, LTrim, and RTrim Functions to remove these spaces.
For more information on string manipulations, see Strings in Visual Basic.
Programming Tips
Negative Numbers. Keep in mind that the characters held by String are unsigned and cannot represent negative
values. In any case, you should not use String to hold numeric values.
Interop Considerations. If you are interfacing with components not written for the .NET Framework, for example
Automation or COM objects, keep in mind that string characters have a different data width (8 bits) in other
environments. If you are passing a string argument of 8-bit characters to such a component, declare it as Byte(), an array
of Byte elements, instead of String in your new Visual Basic code.
Type Characters. Appending the identifier type character $ to any identifier forces it to the String data type. String has
no literal type character. However, the compiler treats literals enclosed within quotation marks (" ") as String.
Framework Type. The corresponding type in the .NET Framework is the System.String class.
See Also
Tasks
How to: Optimize Storage of Positive Integers With Unsigned Types
How to: Call a Windows Function that Takes Unsigned Types
Reference
Data Type Summary (Visual Basic)
Char Data Type (Visual Basic)
Type Conversion Functions
Conversion Summary
System.String
Concepts
Efficient Use of Data Types
Visual Basic Language Reference
See Also
Reference
Data Type Summary (Visual Basic)
ValueType Class
Type Conversion Functions
Conversion Summary
Structure Statement
Widening
Narrowing
StructLayoutAttribute
Concepts
Efficient Use of Data Types
Other Resources
Structures: Your Own Data Types
Visual Basic Language Reference
#Const Directive
Defines conditional compiler constants for Visual Basic.
Parts
constname
Required. String. Name of the constant being defined.
expression
Required. Literal, other conditional compiler constant, or any combination that includes any or all arithmetic or logical
operators except Is.
Remarks
Conditional compiler constants are always private to the file in which they appear. You cannot create public compiler constants
using the #Const directive; you can create them only in the user interface or with the /define compiler option.
You can use only conditional compiler constants and literals in expression. Using a standard constant defined with Const
causes an error. Conversely, you can use constants defined with the #Const keyword only for conditional compilation.
Constants can also be undefined, in which case they have a value of Nothing.
Example
This example uses the #Const directive.
VB
#Const MyLocation = "USA"
#Const Version = "8.0.0012"
#Const CustomerNumber = 36
See Also
Tasks
How to: Declare Conditional Compilation Constants
Reference
/define (Visual Basic)
#If...Then...#Else Directives
Const Statement (Visual Basic)
If...Then...Else Statement (Visual Basic)
Concepts
Conditional Compilation Overview
Visual Basic Language Reference
#ExternalSource Directive
Indicates a mapping between specific lines of source code and text external to the source.
Parts
StringLiteral
The path to the external source.
IntLiteral
The line number of the first line of the external source.
LogicalLine
The line where the error occurs in the external source.
#End ExternalSource
Terminates the #ExternalSource block.
Remarks
This directive is used only by the compiler and the debugger.
A source file may include external source directives, which indicate a mapping between specific lines of code in the source file
and text external to the source, such as an .aspx file. If errors are encountered in the designated source code during
compilation, they are identified as coming from the external source.
External source directives have no effect on compilation and cannot be nested. They are intended for internal use by the
application only.
See Also
Other Resources
Conditional Compilation (Visual Basic)
Visual Basic Language Reference
#If...Then...#Else Directives
Conditionally compiles selected blocks of Visual Basic code.
Parts
expression
Required for #If and #ElseIf statements, optional elsewhere. Any expression, consisting exclusively of one or more
conditional compiler constants, literals, and operators, that evaluates to True or False.
statements
Required for #If statement block, optional elsewhere. Visual Basic program lines or compiler directives that are compiled if
the associated expression evaluates to True.
#End If
Terminates the #If statement block.
Remarks
On the surface, the behavior of the #If...Then...#Else directives appears the same as that of the If...Then...Else statements.
However, the #If...Then...#Else directives evaluate what is compiled by the compiler, whereas the If...Then...Else statements
evaluate conditions at run time.
Conditional compilation is typically used to compile the same program for different platforms. It is also used to prevent
debugging code from appearing in an executable file. Code excluded during conditional compilation is completely omitted
from the final executable file, so it has no effect on size or performance.
Regardless of the outcome of any evaluation, all expressions are evaluated using Option Compare Binary. The Option
Compare statement does not affect expressions in #If and #ElseIf statements.
Note
No single-line form of the #If, #Else, #ElseIf, and #End If directives exists. No other code can appear on the same line as any
of the directives.
Example
This example uses the #If...Then...#Else construct to determine whether to compile certain statements.
VB
#Const CustomerNumber = 36
#If CustomerNumber = 35 Then
' Insert code to be compiled for customer # 35.
#ElseIf CustomerNumber = 36 Then
' Insert code to be compiled for customer # 36.
#Else
' Insert code to be compiled for all other customers.
#End If
See Also
Reference
#Const Directive
If...Then...Else Statement (Visual Basic)
Conditional Compilation Constants
Concepts
Conditional Compilation Overview
Visual Basic Language Reference
#Region Directive
Collapses and hides sections of code in Visual Basic files.
#Region "identifier_string"
#End Region
Parts
identifier_string
Required. String that acts as the title of a region when it is collapsed. Regions are collapsed by default.
#End Region
Terminates the #Region block.
Remarks
Use the #Region directive to specify a block of code to expand or collapse when using the outlining feature of the Visual
Studio Code Editor. #Region statements support block semantics (such as #If...#End If), meaning that the start and end must
be in the same code block.
Example
This example uses the #Region directive.
VB
#Region "MathFunctions"
' Insert code for the Math functions here.
#End Region
See Also
Tasks
How to: Outline and Hide Code
How to: Collapse and Hide Sections of Code
Reference
#If...Then...#Else Directives
Visual Basic Language Reference
Atn Atan Returns a Double value containing the angle whose tangent is the specified number.
Cos Cos Returns a Double value containing the cosine of the specified angle.
Exp Exp Returns a Double value containing e (the base of natural logarithms) raised to the specified power.
Log Log Returns a Double value containing the logarithm of a specified number. This method is overloaded an
d can return either the natural (base e) logarithm of a specified number or the logarithm of a specified
number in a specified base.
Round Round Returns a Double value containing the number nearest the specified value. Additional round functions
are available as methods of the intrinsic types such as Round.
Sqr Sqrt Returns a Double value specifying the square root of a number.
In addition, the .NET Framework math class provides constants and other static methods for trigonometric, logarithmic, and
other common mathematical functions. All of these can be used in a Visual Basic program.
To use these functions without qualification, import the System.Math namespace into your project by adding the following
code to the top of the source code:
'Imports System.Math
Example
This example uses the Abs method of the Math class to compute the absolute value of a number.
This example uses the Atan method of the Math class to calculate the value of pi.
This example uses the Cos method of the Math class to return the cosine of an angle.
This example uses the Exp method of the Math class to return e raised to a power.
This example uses the Log method of the Math class to return the natural logarithm of a number.
This example uses the Round method of the Math class to round a number to the nearest integer.
' Returns 3.
Dim MyVar2 As Double = Math.Round(2.8)
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)
This example uses the Sin method of the Math class to return the sine of an angle.
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)
This example uses the Tan method of the Math class to return the tangent of an angle.
Requirements
Class: Math
Namespace: System
Assembly: mscorlib (in mscorlib.dll)
See Also
Reference
Rnd Function (Visual Basic)
Randomize Function (Visual Basic)
Derived Math Functions (Visual Basic)
NaN
Visual Basic Language Reference
CBool(expression)
CByte(expression)
CChar(expression)
CDate(expression)
CDbl(expression)
CDec(expression)
CInt(expression)
CLng(expression)
CObj(expression)
CSByte(expression)
CShort(expression)
CSng(expression)
CStr(expression)
CUInt(expression)
CULng(expression)
CUShort(expression)
Part
expression
Required. Any expression of the source data type.
Return Value Data Type
The function name determines the data type of the value it returns, as shown in the following table.
Func Return data type Range for expression argument
tion
nam
e
CBo Boolean Data Type (Visual Basic) Any valid Char or String or numeric expression.
ol
CByt Byte Data Type (Visual Basic) 0 through 255 (unsigned); fractional parts are rounded.1
e
CCha Char Data Type (Visual Basic) Any valid Char or String expression; only first character of a String is converted; value
r can be 0 through 65535 (unsigned).
CDat Date Data Type (Visual Basic) Any valid representation of a date and time.
e
CDbl Double Data Type (Visual Basic) -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative va
lues; 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive
values.
CDec Decimal Data Type (Visual Basic) +/-79,228,162,514,264,337,593,543,950,335 for zero-scaled numbers, that is, numbers
with no decimal places. For numbers with 28 decimal places, the range is +/-7.922816
2514264337593543950335. The smallest possible non-zero number is 0.0000000000
000000000000000001 (+/-1E-28).
CInt Integer Data Type (Visual Basic) -2,147,483,648 through 2,147,483,647; fractional parts are rounded.1
CLng Long Data Type (Visual Basic) -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807; fractional parts are r
ounded.1
CSBy SByte Data Type (Visual Basic) -128 through 127; fractional parts are rounded.1
te
CSho Short Data Type (Visual Basic) -32,768 through 32,767; fractional parts are rounded.1
rt
CSng Single Data Type (Visual Basic) -3.402823E+38 through -1.401298E-45 for negative values; 1.401298E-45 through 3.4
02823E+38 for positive values.
CStr String Data Type (Visual Basic) Returns for CStr depend on the expression argument. See
Return Values for the CStr Function.
CUIn UInteger Data Type 0 through 4,294,967,295 (unsigned); fractional parts are rounded.1
t
CUL ULong Data Type (Visual Basic) 0 through 18,446,744,073,709,551,615 (unsigned); fractional parts are rounded.1
ng
CUS UShort Data Type (Visual Basic) 0 through 65,535 (unsigned); fractional parts are rounded.1
hort
1 Fractional parts can be subject to a special type of rounding called banker's rounding. See "Remarks" for more information.
Remarks
As a rule, you should use the Visual Basic type conversion functions in preference to the .NET Framework methods such as
ToString(), either on the Convert class or on an individual type structure or class. The Visual Basic functions are designed for
optimal interaction with Visual Basic code, and they also make your source code shorter and easier to read. In addition, the
.NET Framework conversion methods do not always produce the same results as the Visual Basic functions, for example when
converting Boolean to Integer. For more information, see Troubleshooting Data Types.
Behavior
Coercion. In general, you can use the data type conversion functions to coerce the result of an operation to a particular
data type rather than the default data type. For example, use CDec to force decimal arithmetic in cases where single-
precision, double-precision, or integer arithmetic would normally take place.
Failed Conversions. If the expression passed to the function is outside the range of the data type to which it is to be
converted, an OverflowException occurs.
Fractional Parts. When you convert a nonintegral value to an integral type, the integer conversion functions (CByte,
CInt, CLng, CSByte, CShort, CUInt, CULng, and CUShort) remove the fractional part and round the value to the closest
integer.
If the fractional part is exactly 0.5, the integer conversion functions round it to the nearest even integer. For example, 0.5
rounds to 0, and 1.5 and 2.5 both round to 2. This is sometimes called banker's rounding, and its purpose is to
compensate for a bias that could accumulate when adding many such numbers together.
CInt and CLng differ from the Int, Fix Functions (Visual Basic), which truncate, rather than round, the fractional part of a
number. Also, Fix and Int always return a value of the same data type as you pass in.
Date/Time Conversions. Use the IsDate Function (Visual Basic) to determine if a value can be converted to a date and
time. CDate recognizes date literals and time literals but not numeric values. To convert a Visual Basic 6.0 Date value to
a Visual Basic 2005 Date value, you can use the System.DateTime.FromOADate(System.Double) method.
Neutral Date/Time Values. The Date Data Type (Visual Basic) always contains both date and time information. For
purposes of type conversion, Visual Basic considers 1/1/0001 (January 1 of the year 1) to be a neutral value for the date,
and 00:00:00 (midnight) to be a neutral value for the time. If you convert a Date value to a string, CStr does not include
neutral values in the resulting string. For example, if you convert #January 1, 0001 9:30:00# to a string, the result is
"9:30:00 AM"; the date information is suppressed. However, the date information is still present in the original Date value
and can be recovered with functions such as DatePart Function (Visual Basic).
Culture Sensitivity. The type conversion functions involving strings perform conversions based on the current culture
settings for the application. For example, CDate recognizes date formats according to the locale setting of your system.
You must provide the day, month, and year in the correct order for your locale, or the date might not be interpreted
correctly. A long date format is not recognized if it contains a day-of-the-week string, such as "Wednesday".
If you need to convert to or from a string representation of a value in a format other than the one specified by your
locale, you cannot use the Visual Basic type conversion functions. To do this, use the ToString(IFormatProvider) and
Parse(String, IFormatProvider) methods of that value's type. For example, use
System.Double.Parse(System.String,System.IFormatProvider) when converting a string to a Double, and use
System.Double.ToString(System.IFormatProvider) when converting a value of type Double to a string.
CType Function
The CType Function takes a second argument, typename, and coerces expression to typename, where typename can be any
data type, structure, class, or interface to which there exists a valid conversion.
For a comparison of CType with the other type conversion keywords, see DirectCast and TryCast.
CBool Example
The following example uses the CBool function to convert expressions to Boolean values. If an expression evaluates to a
nonzero value, CBool returns True; otherwise, it returns False.
VB
Dim a, b, c As Integer
Dim check As Boolean
a = 5
b = 5
' The following line of code sets check to True.
check = CBool(a = b)
c = 0
' The following line of code sets check to False.
check = CBool(c)
CByte Example
The following example uses the CByte function to convert an expression to a Byte.
VB
Dim aDouble As Double
Dim aByte As Byte
aDouble = 125.5678
' The following line of code sets aByte to 126.
aByte = CByte(aDouble)
CChar Example
The following example uses the CChar function to convert the first character of a String expression to a Char type.
VB
Dim aString As String
Dim aChar As Char
' CChar converts only the first character of the string.
aString = "BCD"
' The following line of code sets aChar to "B".
aChar = CChar(aString)
The input argument to CChar must be of data type Char or String. You cannot use CChar to convert a number to a character,
because CChar cannot accept a numeric data type. The following example obtains a number representing a code point
(character code) and converts it to the corresponding character. It uses the InputBox Function (Visual Basic) to obtain the string
of digits, CInt to convert the string to type Integer, and ChrW to convert the number to type Char.
VB
Dim someDigits As String
Dim codePoint As Integer
Dim thisChar As Char
someDigits = InputBox("Enter code point of character:")
codePoint = CInt(someDigits)
' The following line of code sets thisChar to the Char value of codePoint.
thisChar = ChrW(codePoint)
CDate Example
The following example uses the CDate function to convert strings to Date values. In general, hard-coding dates and times as
strings (as shown in this example) is not recommended. Use date literals and time literals, such as #Feb 12, 1969# and
#4:45:23 PM#, instead.
VB
Dim aDateString, aTimeString As String
Dim aDate, aTime As Date
aDateString = "February 12, 1969"
aTimeString = "4:35:47 PM"
' The following line of code sets aDate to a Date value.
aDate = CDate(aDateString)
' The following line of code sets aTime to Date value.
aTime = CDate(aTimeString)
CDbl Example
VB
Dim aDec As Decimal
Dim aDbl As Double
' The following line of code uses the literal type character D to make aDec a Decimal.
aDec = 234.456784D
' The following line of code sets aDbl to 1.9225456288E+1.
aDbl = CDbl(aDec * 8.2D * 0.01D)
CDec Example
The following example uses the CDec function to convert a numeric value to Decimal.
VB
Dim aDouble As Double
Dim aDecimal As Decimal
aDouble = 10000000.0587
' The following line of code sets aDecimal to 10000000.0587.
aDecimal = CDec(aDouble)
CInt Example
The following example uses the CInt function to convert a value to Integer.
VB
Dim aDbl As Double
Dim anInt As Integer
aDbl = 2345.5678
' The following line of code sets anInt to 2346.
anInt = CInt(aDbl)
CLng Example
The following example uses the CLng function to convert values to Long.
VB
Dim aDbl1, aDbl2 As Double
Dim aLng1, aLng2 As Long
aDbl1 = 25427.45
aDbl2 = 25427.55
' The following line of code sets aLng1 to 25427.
aLng1 = CLng(aDbl1)
' The following line of code sets aLng2 to 25428.
aLng2 = CLng(aDbl2)
CObj Example
The following example uses the CObj function to convert a numeric value to Object. The Object variable itself contains only a
four-byte pointer, which points to the Double value assigned to it.
VB
Dim aDouble As Double
Dim anObject As Object
aDouble = 2.7182818284
' The following line of code sets anObject to a pointer to aDouble.
anObject = CObj(aDouble)
CSByte Example
The following example uses the CSByte function to convert a numeric value to SByte.
VB
Dim aDouble As Double
Dim anSByte As SByte
aDouble = 39.501
' The following line of code sets anSByte to 40.
anSByte = CSByte(aDouble)
CShort Example
The following example uses the CShort function to convert a numeric value to Short.
VB
Dim aByte As Byte
Dim aShort As Short
aByte = 100
' The following line of code sets aShort to 100.
aShort = CShort(aByte)
CSng Example
The following example uses the CSng function to convert values to Single.
VB
Dim aDouble1, aDouble2 As Double
Dim aSingle1, aSingle2 As Single
aDouble1 = 75.3421105
aDouble2 = 75.3421567
' The following line of code sets aSingle1 to 75.34211.
aSingle1 = CSng(aDouble1)
' The following line of code sets aSingle2 to 75.34216.
aSingle2 = CSng(aDouble2)
CStr Example
The following example uses the CStr function to convert a numeric value to String.
VB
Dim aDouble As Double
Dim aString As String
aDouble = 437.324
' The following line of code sets aString to "437.324".
aString = CStr(aDouble)
The following example uses the CStr function to convert Date values to String values.
VB
Dim aDate As Date
Dim aString As String
' The following line of code generates a COMPILER ERROR because of invalid format.
' aDate = #February 12, 1969 00:00:00#
' Date literals must be in the format #m/d/yyyy# or they are invalid.
' The following line of code sets the time component of aDate to midnight.
aDate = #2/12/1969#
' The following conversion suppresses the neutral time value of 00:00:00.
' The following line of code sets aString to "2/12/1969".
aString = CStr(aDate)
' The following line of code sets the time component of aDate to one second past midnight.
aDate = #2/12/1969 12:00:01 AM#
' The time component becomes part of the converted value.
' The following line of code sets aString to "2/12/1969 12:00:01 AM".
aString = CStr(aDate)
CStr always renders a Date value in the standard short format for the current locale, for example, "6/15/2003 4:35:47 PM".
However, CStr suppresses the neutral values of 1/1/0001 for the date and 00:00:00 for the time.
For more detail on the values returned by CStr, see Return Values for the CStr Function.
CUInt Example
The following example uses the CUInt function to convert a numeric value to UInteger.
VB
Dim aDouble As Double
Dim aUInteger As UInteger
aDouble = 39.501
' The following line of code sets aUInteger to 40.
aUInteger = CUInt(aDouble)
CULng Example
The following example uses the CULng function to convert a numeric value to ULong.
VB
Dim aDouble As Double
Dim aULong As ULong
aDouble = 39.501
' The following line of code sets aULong to 40.
aULong = CULng(aDouble)
CUShort Example
The following example uses the CUShort function to convert a numeric value to UShort.
VB
Dim aDouble As Double
Dim aUShort As UShort
aDouble = 39.501
' The following line of code sets aUShort to 40.
aUShort = CUShort(aDouble)
See Also
Reference
Conversion Functions (Visual Basic)
Asc, AscW Functions
Chr, ChrW Functions
Int, Fix Functions (Visual Basic)
Format Function
Hex Function (Visual Basic)
Oct Function
Str Function
Val Function
Other Resources
Type Conversions in Visual Basic
Visual Basic Language Reference
Date Data Type (Visual Basic) A string containing a Date value (date and time) in the short date format of your system.
See Also
Reference
Type Conversion Functions
Boolean Data Type (Visual Basic)
Date Data Type (Visual Basic)
DatePart Function (Visual Basic)
Visual Basic Language Reference
A-C Functions
The following table contains a listing of the Visual Basic run-time member functions.
CType CurDir
The math functions Abs, Atn, and Cos that were available as Visual Basic run-time member functions in version 6.0 and earlier
have been replaced by methods (Abs, Atan, Cos) in the Math class of the .NET Framework class library. For more information,
see Math Functions (Visual Basic).
Smart Device Developer Notes
The following functions are not supported in smart device applications: AppActivate, Beep, CallByName, ChDir, ChDrive,
CreateObject, and CurDir.
See Also
Reference
D-G Functions
H-L Functions
M-R Functions
S-Z Functions
Other Resources
Visual Basic Reference
Visual Basic Language Reference
AppActivate Function
Activates an application that is already running.
Parameters
Title
String expression specifying the title in the title bar of the application you want to activate. You can use the title assigned to
the application when it was launched.
ProcessId
Integer specifying the Win32 process ID number assigned to this process. You can use the ID returned by the Shell Function,
provided it is not zero.
Exceptions
Exception type Error number Condition
ArgumentException 5 Title or ProcessId cannot be found.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
You use AppActivate to bring an application's active window into focus. You might not have a handle or a reference to the
active window, or even know which window is active at a given moment. In such a case, you cannot use the Focus method.
The AppActivate function changes the focus to the named application or window but does not affect whether it is maximized
or minimized. Focus moves away from the activated application window when the user takes some action to change the focus
or close the window. You can use the Shell function to start an application and set the window style.
If you use the Title parameter, AppActivate uses a case-insensitive comparison but otherwise requires an exact match with the
contents of the title bar. It first looks through the top-level windows and then through the child windows. If it cannot find a
match, it throws an ArgumentException.
You can use AppActivate only with processes that own windows. Most console applications do not own windows, which
means that they do not appear in the list of processes that AppActivate searches. When running from a console application,
the system creates a separate process to run the application and returns the output to the console process. Consequently,
when you request the current process ID, you get the process ID of this separate process, rather than the console application's
process ID.
At run time, the AppActivate function activates any running application with a title that matches Title or with a process ID that
matches ProcessId. If there is no exact match, it activates any application whose title string ends with Title. If there is more than
one application named Title, the AppActivate function arbitrarily chooses one to activate.
Note
The AppActivate function requires UIPermission at the SafeTopLevelWindows level, which may affect its execution in parti
al-trust situations. For more information, see Requesting Permissions and UIPermission Class.
Example
This example illustrates various uses of the AppActivate function to activate an application window. If a Notepad process is
not running, the example throws an ArgumentException. The Shell procedure assumes the applications are in the paths
specified.
VB
Dim notepadID As Integer
' Activate a running Notepad process.
AppActivate("Untitled - Notepad")
' AppActivate can also use the return value of the Shell function.
' Shell runs a new instance of Notepad.
notepadID = Shell("C:\WINNT\NOTEPAD.EXE", AppWinStyle.NormalFocus)
' Activate the new instance of Notepad.
AppActivate(notepadID)
Parameters
String
Required. Any valid Char or 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 ArgumentException error occurs.
Exceptions
Exception type Error number Condition
ArgumentException 5 String is empty or is zero length.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Asc returns the code point, or character code, for the input character. This can be 0 through 255 for single-byte character set
(SBCS) values and -32768 through 32767 for double-byte character set (DBCS) values. For charts of the single-byte ASCII
characters, see ASCII Character Codes.
The returned value depends on the code page for the current thread, which is contained in the ANSICodePage property of the
TextInfo class in the System.Globalization namespace. You can obtain ANSICodePage by specifying
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage.
AscW returns the Unicode code point for the input character. This can be 0 through 65535. The returned value is independent
of the culture and code page settings for the current thread.
Note
The AscB function of earlier versions of Visual Basic returns a code for a byte, rather than a character. It is used primarily for
converting strings in double-byte character set (DBCS) applications. All Visual Basic 2005 strings are in Unicode, and AscB is
no longer supported.
Example
The following example uses the Asc function to return Integer Data Type (Visual Basic) character codes corresponding to the
first letter in each string.
VB
Dim codeInt As Integer
' The following line of code sets myInt to 65.
codeInt = Asc("A")
' The following line of code sets myInt to 97.
codeInt = Asc("a")
' The following line of code sets myInt to 65.
codeInt = Asc("Apple")
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Chr, ChrW Functions
Conversion Functions (Visual Basic)
Type Conversion Functions
Integer Data Type (Visual Basic)
System.Globalization
CultureInfo
ANSICodePage
ArgumentException
Other Resources
ASCII Character Codes
Visual Basic Language Reference
Beep Function
Sounds a tone through the computer's speaker.
Remarks
The pitch and duration of the beep depend on your hardware and system software and therefore vary among computers.
Note
The Beep function requires UIPermission at the SafeTopLevelWindows level, which may affect its execution in partial-trust s
ituations. For more information, see Requesting Permissions and UIPermission Class.
Example
This example uses the Beep function to sound a long, uninterrupted tone through the computer's speaker.
VB
Dim I As Integer
For I = 1 To 100 ' Loop 100 times.
Beep ' Sound a tone.
Next I
CallByName Function
Executes a method on an object, or sets or returns a property on an object.
Parameters
ObjectRef
Required. Object. A pointer to the object exposing the property or method.
ProcName
Required. String. A string expression containing the name of the property or method on the object.
UseCallType
Required. An enumeration member of type CallType Enumeration representing the type of procedure being called. The value
of CallType can be Method, Get, or Set.
Args
Optional. ParamArray. A parameter array containing the arguments to be passed to the property or method being called.
Exceptions
Exception type Error number Condition
ArgumentException 5 Invalid UseCallType value; must be Method, Get, or Set.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The CallByName function is used at runtime to get a property, set a property, or invoke a method.
Example
In the following example, the first line uses CallByName to set the Text property of a text box, the second line retrieves the
value of the Text property, and the third line invokes the Move method to move the text box.
VB
' Imports statements must be at the top of a module.
Imports Microsoft.VisualBasic.CallType
VB
Sub TestCallByName1()
'Set a property.
CallByName(TextBox1, "Text", CallType.Set, "New Text")
'Retrieve the value of a property.
MsgBox(CallByName(TextBox1, "Text", CallType.Get))
'Call a method.
CallByName(TextBox1, "Hide", CallType.Method)
End Sub
The next example uses the CallByName function to invoke the Add and Item methods of a collection object.
VB
Public Sub TestCallByName2()
Dim col As New Collection()
'Store the string "Item One" in a collection by
'calling the Add method.
CallByName(col, "Add", CallType.Method, "Item One")
'Retrieve the first entry from the collection using the
'Item property and display it using MsgBox().
MsgBox(CallByName(col, "Item", CallType.Get, 1))
End Sub
ChDir Function
Changes the current directory or folder.
The My feature provides you with greater productivity and performance in file I/O operations than the ChDir function. For
more information, see My.Computer.FileSystem.CurrentDirectory Property
Parameters
Path
Required. A String expression that identifies which directory or folder becomes the new default directory or folder. Path may
include the drive. If no drive is specified, ChDir changes the default directory or folder on the current drive.
Exceptions
Exception type Error number Condition
ArgumentException 52 Path is empty.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The ChDir function changes the default directory, but not the default drive. For example, if the default drive is C, the following
statement changes the default directory on drive D, but C remains the default drive:
VB
ChDir("D:\TMP")
Security Note
The ChDir function requires unmanaged code permission, which may affect its execution in partial-trust situations. For more
information, see SecurityPermission Class and Code Access Permissions.
Example
This example uses the ChDir function to change the current directory or folder.
VB
' Change current directory or folder to "MYDIR".
ChDir("MYDIR")
' Assume "C:" is the current drive. The following statement changes
' the default directory on drive "D:". "C:" remains the current drive.
ChDir("D:\WINDOWS\SYSTEM")
ChDrive Function
Changes the current drive.
Parameters
Drive
Required. String expression that specifies an existing drive. If you supply a zero-length string (""), the current drive doesn't
change. If the Drive argument is a multiple-character string, ChDrive uses only the first letter.
Exceptions
Exception type Error number Condition
IOException 68 Invalid drive is specified, or drive is unavailable.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The ChDrive function requires unmanaged-code permission, which may affect its execution in partial-trust situations. For
more information, see SecurityPermission Class and Code Access Permissions.
Example
This example uses the ChDrive function to change the current drive. The function throws an exception if the drive does not
exist.
VB
ChDrive("D") ' Make "D" the current drive.
Choose Function
Selects and returns a value from a list of arguments.
Parameters
Index
Required. Double. Numeric expression that results in a value between 1 and the number of elements passed in the Choice
argument.
Choice
Required. Object parameter array. You can supply either a single variable or an expression that evaluates to the Object data
type, to a list of Object variables or expressions separated by commas, or to a single-dimensional array of Object elements.
Remarks
The Choose function returns a member of the list passed in Choice(), based on the value of Index. The first member of the list
is selected when Index is 1. The last member of the list is selected when Index is UBound(Choice()). If Index is outside these
limits, Choose returns Nothing.
If Index is not a whole number, it is rounded to the nearest whole number before being evaluated.
You can use Choose to look up a value in a list of possibilities.
Note
The expressions in the argument list can include function calls. As part of preparing the argument list for the call to Choose, t
he Visual Basic compiler calls every function in every expression. This means that you cannot rely on a particular function not
being called if a different expression is selected by Index.
Example
This example uses the Choose function to display a name in response to an index passed into the procedure in the Ind
parameter.
VB
Function GetChoice(ByVal Ind As Integer) As String
GetChoice = CStr(Choose(Ind, "Speedy", "United", "Federal"))
End Function
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IIf Function
Select...Case Statement (Visual Basic)
Switch Function
Visual Basic Language Reference
Parameters
CharCode
Required. An Integer expression representing the code point, or character code, for the character. If CharCode is outside the
valid range, an ArgumentException error occurs. The valid range for Chr is 0 through 255, and the valid range for ChrW is -
32768 through 65535.
Exceptions
Exception type Error number Condition
ArgumentException 5 CharCode < -32768 or > 65535 for ChrW.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The asymmetric range accepted for CharCode compensates for the storage differences between the
Short Data Type (Visual Basic) and the Integer Data Type (Visual Basic). For example, -29183 is a Short but +36353 is an
Integer. This also facilitates compatibility with Visual Basic 6.0.
Chr uses the Encoding class in the System.Text namespace to determine if the current thread is using a single-byte character
set (SBCS) or a double-byte character set (DBCS). It then takes CharCode as a code point in the appropriate set. The range can
be 0 through 255 for SBCS characters and -32768 through 65535 for DBCS characters. For charts of the single-byte ASCII
characters, see ASCII Character Codes.
The returned value depends on the code page for the current thread, which is contained in the ANSICodePage property of the
TextInfo class in the System.Globalization namespace. You can obtain ANSICodePage by specifying
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage.
ChrW takes CharCode as a Unicode code point. The range is independent of the culture and code page settings for the current
thread. Values from -32768 through -1 are treated the same as values in the range +32768 through +65535.
Numbers from 0 through 31 are the same as standard nonprintable ASCII codes. For example, Chr(10) returns a line feed
character.
Note
The ChrB function in earlier versions of Visual Basic returns a single byte. It is used primarily for converting strings in double
-byte character set (DBCS) applications. All strings in Visual Basic and the .NET Framework are in Unicode, and ChrB is no lon
ger supported.
Example
The following example uses the Chr function to return the character associated with the specified character code.
VB
Dim associatedChar As Char
' Returns "A".
associatedChar = Chr(65)
' Returns "a".
associatedChar = Chr(97)
' Returns ">".
associatedChar = Chr(62)
' Returns "%".
associatedChar = Chr(37)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Asc, AscW Functions
Str Function
Conversion Functions (Visual Basic)
Type Conversion Functions
CultureInfo
ArgumentException
Other Resources
ASCII Character Codes
Visual Basic Language Reference
Command Function
Returns the argument portion of the command line used to start Visual Basic or an executable program developed with Visual
Basic.
The My feature provides greater productivity and performance than the Command function. For more information, see
My.Application.CommandLineArgs Property.
Remarks
After the arguments are returned, you can search for common delimiters, such as spaces, backward or forward slashes,
hyphens, or quotation marks, to split or search the string for individual parameters.
For applications developed with Visual Basic and compiled to an .exe file, the Command function returns any arguments that
appear after the name of the application on the command line, in this form: MyApp(cmdlineargs).
Example
This example uses the Command function to return the command-line arguments in an object that contains an array.
VB
Function GetCommandLineArgs() As String()
' Declare variables.
Dim separators As String = " "
Dim commands As String = Microsoft.VisualBasic.Interaction.Command()
Dim args() As String = commands.Split(separators.ToCharArray)
Return args
End Function
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Visual Basic Run-Time Library Members
Structure of a Visual Basic Program
Environment.GetCommandLineArgs Method
My.Application.CommandLineArgs Property
Concepts
Visual Basic Version of Hello, World
Other Resources
Visual Basic Compiler
Visual Basic Language Reference
Parameters
ProgId
Required. String. The program ID of the object to create.
ServerName
Optional. String. The name of the network server where the object will be created. If ServerName is an empty string (""), the
local computer is used.
Exceptions
Exception type Error nu Condition
mber
Exception 429 ProgId not found or not supplied
-or-
ServerName fails the DnsValidateName function, most likely because it is longer than 63 ch
aracters or contains an invalid character.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
To create an instance of a COM component, assign the object returned by CreateObject to an object variable:
Sub CreateADODB()
Dim adoApp As Object
adoApp = CreateObject("ADODB.Connection")
End Sub
The type of object variable you use to store the returned object can affect your application's performance. Declaring an object
variable with the As Object clause creates a variable that can contain a reference to any type of object. However, access to the
object through that variable is late-bound, that is, the binding occurs when your program runs. There are many reasons you
should avoid late binding, including slower application performance.
You can create an object variable that results in early binding—that is, binding when the program is compiled. To do so, add a
reference to the type library for your object from the COM tab of the Add Reference dialog box on the Project menu. Then
declare the object variable of the specific type of your object. In most cases, it is more efficient to use the Dim statement and a
primary interop assembly to create objects than it is to use the CreateObject function.
Interacting with Unmanaged Code
Another issue is that COM objects use unmanaged code — code without the benefit of the common language runtime. There is
a fair degree of complexity involved in mixing the managed code of Visual Basic with unmanaged code from COM. When you
add a reference to a COM object, Visual Basic searches for a primary interop assembly (PIA) for that library; if it finds one, then
it uses it. If it does not find a PIA, then it creates an interoperability assembly that contains local interoperability classes for each
class in the COM library. For more information, see COM Interoperability in .NET Framework Applications.
You should generally use strongly bound objects and primary interop assemblies whenever possible. The examples below use
the CreateObject function with Microsoft Office objects for demonstration purposes only. However, these objects are easier to
use and more reliable when used with the appropriate primary interop assembly.
Creating an Object on a Remote Computer
You can create an object on a remote networked computer by passing the name of the computer to the ServerName argument
of the CreateObject function. That name is the same as the Machine Name portion of a share name: for a share named
"\\MyServer\Public," ServerName is "MyServer."
Note
Refer to COM documentation (see Microsoft Developer Network) for additional information on making an application access
ible on a remote networked computer. You may need to add a registry key for your application.
The following code returns the version number of an instance of Excel running on a remote computer named MyServer:
Sub CreateRemoteExcelObj()
Dim xlApp As Object
' Replace string "\\MyServer" with name of the remote computer.
xlApp = CreateObject("Excel.Application", "\\MyServer")
MsgBox(xlApp.Version)
End Sub
Example
The following example uses the CreateObject function to create a Microsoft Excel worksheet and saves the worksheet to a file.
To use this example, Excel must be installed on the computer where this program runs. Also, you must add a reference to the
type library from the COM tab of the Add Reference dialog box on the Project menu. The name of the type library varies
depending on the version of Excel installed on your computer. For example, the type library for Microsoft Excel 2002 is named
Microsoft Excel 10.0 Object Library.
VB
Sub TestExcel()
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
xlApp = CType(CreateObject("Excel.Application"), _
Microsoft.Office.Interop.Excel.Application)
xlBook = CType(xlApp.Workbooks.Add, _
Microsoft.Office.Interop.Excel.Workbook)
xlSheet = CType(xlBook.Worksheets(1), _
Microsoft.Office.Interop.Excel.Worksheet)
' The following statement puts text in the second row of the sheet.
xlSheet.Cells(2, 2) = "This is column B row 2"
' The following statement shows the sheet.
xlSheet.Application.Visible = True
' The following statement saves the sheet to the C:\Test.xls directory.
xlSheet.SaveAs("C:\Test.xls")
' Optionally, you can call xlApp.Quit to close the workbook.
End Sub
CType Function
Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface.
CType(expression, typename)
Parts
expression
Any valid expression. If the value of expression is outside the range allowed by typename, Visual Basic throws an exception.
typename
Any expression that is legal within an As clause in a Dim statement, that is, the name of any data type, object, structure, class,
or interface.
Remarks
CType is compiled inline, which means that the conversion code is part of the code that evaluates the expression. In some
cases there is no call to a procedure to accomplish the conversion, which makes execution faster.
If no conversion is defined from expression to typename, for example from Integer to Date, Visual Basic displays a compile-
time error message.
If a conversion fails at run time, the appropriate exception occurs. If a narrowing conversion fails, an OverflowException is the
most common result. If the conversion is undefined, an InvalidCastException occurs. This can happen, for example, if expression
is of type Object and its run-time type has no conversion to typename.
If the data type of expression or typename is a class or structure you have defined, you can define CType on that class or
structure as a conversion operator. This makes CType act as an overloaded operator. If you do this, you can control the
behavior of conversions to and from your class or structure, including what exceptions can be thrown.
Overloading
The CType operator can also be overloaded on a class or structure defined outside your code. If your code converts to or from
such a class or structure, be sure you understand the behavior of its CType operator. For more information, see
Operator Procedures.
Example
The following example uses the CType function to convert an expression to the specified data type.
VB
Dim testNumber As Long = 1000
' The following line of code sets testNewType to 1000.0.
Dim testNewType As Single = CType(testNumber, Single)
See Also
Tasks
How to: Define a Conversion Operator
Reference
Type Conversion Functions
Conversion Functions (Visual Basic)
Operator Statement
OverflowException
InvalidCastException
Visual Basic Language Reference
CurDir Function
Returns a string representing the current path.
The My.Computer.FileSystem Object gives you greater productivity and performance in file I/O operations than CurDir. For
more information, see My.Computer.FileSystem.CurrentDirectory Property.
Parameters
Drive
Optional. Char expression that specifies an existing drive. If no drive is specified, or if Drive is a zero-length string (""), CurDir
returns the path for the current drive.
Exceptions
Exception type Error number Condition
IOException 68 Drive is not found.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
This function returns a string representing the current path.
Example
This example uses the CurDir function to return the current path.
VB
' Assume current path on C drive is "C:\WINDOWS\SYSTEM".
' Assume current path on D drive is "D:\EXCEL".
' Assume C is the current drive.
Dim MyPath As String
MyPath = CurDir() ' Returns "C:\WINDOWS\SYSTEM".
MyPath = CurDir("C"c) ' Returns "C:\WINDOWS\SYSTEM".
MyPath = CurDir("D"c) ' Returns "D:\EXCEL".
D-G Functions
The following table contains a listing of the Visual Basic run-time member functions.
The math function Exp that was available as a Visual Basic run-time member function in version 6.0 and earlier has been
replaced by a method (Exp) in the Math class of the .NET Framework class library. For more information, see
Math Functions (Visual Basic).
Smart Device Developer Notes
The following are not supported in smart device applications: DeleteSetting, Dir, Environ, EOF, FileAttr, FileClose, FileCopy,
FileDateTime, FileGet, FileGetObject, FileLen, FileOpen, FilePut, FilePutObject, FileWidth, FreeFile, GetAllSettings,
GetAttr, GetObject, and GetSetting.
See Also
Reference
A-C Functions
H-L Functions
M-R Functions
S-Z Functions
Other Resources
Visual Basic Reference
Visual Basic Language Reference
Parameters
Interval
Required. DateInterval enumeration value or String expression representing the time interval you want to add.
Number
Required. Double. Floating-point expression representing the number of intervals you want to add. Number can be positive
(to get date/time values in the future) or negative (to get date/time values in the past). Any fractional part of Number is
ignored.
DateValue
Required. Date. An expression representing the date and time to which the interval is to be added. DateValue itself is not
changed in the calling program.
Settings
The Interval argument can have one of the following settings.
Enumeration value String Unit of time interval to add
DateInterval.Day d Day; truncated to integral value
ArgumentOutOfRangeException 9 Calculated date is before 00:00:00 on January 1 of the year 1, or later than 23:59:5
9 on December 31, 9999.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
You can use the DateAdd function to add or subtract a specified time interval from a date. For example, you can calculate a
date 30 days from today or a time 45 minutes before now.
To add days to DateValue, you can use DateInterval.Day, DateInterval.DayOfYear, or DateInterval.Weekday. These are
treated as equivalent because DayOfYear and Weekday are not meaningful time intervals.
The DateAdd function never returns an invalid date. If necessary, the day part of the resulting date is adjusted downward to
the last day of the resulting month in the resulting year. The following example adds one month to January 31:
In this example, DateAdd returns #2/28/1995#, not #2/31/1995#. If DateValue is #1/31/1996#, it returns #2/29/1996# because
1996 is a leap year.
Note
DateAdd uses the current calendar setting from the CurrentCulture property of the CultureInfo class in the
System.Globalization namespace. The default CurrentCulture values are determined by Control Panel settings.
Since every Date value is supported by a DateTime structure, its methods give you additional options in adding time intervals.
For example, you can add a fractional number of days, rounded to the nearest millisecond, to a Date variable as follows:
Example
This example takes a date and, using the DateAdd function, displays a corresponding date a specified number of months in
the future.
VB
Dim Msg, Number, StartDate As String 'Declare variables.
Dim Months As Double
Dim SecondDate As Date
Dim IntervalType As DateInterval
IntervalType = DateInterval.Month ' Specifies months as interval.
StartDate = InputBox("Enter a date")
SecondDate = CDate(StartDate)
Number = InputBox("Enter number of months to add")
Months = Val(Number)
Msg = "New date: " & DateAdd(IntervalType, Months, SecondDate)
MsgBox(Msg)
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateDiff Function (Visual Basic)
DatePart Function (Visual Basic)
Day Function (Visual Basic)
Format Function
Now Property
Weekday Function (Visual Basic)
Year Function (Visual Basic)
Date Data Type (Visual Basic)
System
Visual Basic Language Reference
Parameters
Interval
Required. DateInterval enumeration value or String expression representing the time interval you want to use as the unit
of difference between Date1 and Date2.
Date1
Required. Date. The first date/time value you want to use in the calculation.
Date2
Required. Date. The second date/time value you want to use in the calculation.
DayOfWeek
Optional. A value chosen from the FirstDayOfWeek enumeration that specifies the first day of the week. If not specified,
FirstDayOfWeek.Sunday is used.
WeekOfYear
Optional. A value chosen from the FirstWeekOfYear enumeration that specifies the first week of the year. If not specified,
FirstWeekOfYear.Jan1 is used.
Settings
The Interval argument can have one of the following settings.
Enumeration value String value Unit of time difference
DateInterval.Day "d" Day
FirstDayOfWeek.Tuesday 3 Tuesday
FirstDayOfWeek.Wednesday 4 Wednesday
FirstDayOfWeek.Thursday 5 Thursday
FirstDayOfWeek.Friday 6 Friday
FirstDayOfWeek.Saturday 7 Saturday
FirstWeekOfYear.FirstFourD 2 Week that has at least four days in the new year (complies with ISO standard 8601, secti
ays on 3.17)
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
You can use the DateDiff function to determine how many specified time intervals exist between two date/time values. For
example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today
and the end of the year.
Behavior
Treatment of Parameters. DateDiff subtracts the value of Date1 from the value of Date2 to produce the difference.
Neither value is changed in the calling program.
Return Values. Because Date1 and Date2 are of the Date data type, they hold date and time values accurate to 100-
nanosecond ticks on the system timer. However, DateDiff always returns the number of time intervals as a Long value.
If Date1 represents a later date and time than Date2, DateDiff returns a negative number.
Day Intervals. If Interval is set to DateInterval.DayOfYear, it is treated the same as DateInterval.Day, because
DayOfYear is not a meaningful unit for a time interval.
Week Intervals. If Interval is set to DateInterval.WeekOfYear, the return value represents the number of weeks
between the first day of the week containing Date1 and the first day of the week containing Date2. The following
example shows how this produces different results from DateInterval.Weekday.
VB
' The following statements set datTim1 to a Thursday
' and datTim2 to the following Tuesday.
Dim datTim1 As Date = #1/4/2001#
Dim datTim2 As Date = #1/9/2001#
' Assume Sunday is specified as first day of the week.
Dim wD As Long = DateDiff(DateInterval.Weekday, datTim1, datTim2)
Dim wY As Long = DateDiff(DateInterval.WeekOfYear, datTim1, datTim2)
In the preceding example, DateDiff returns 0 to wD because the difference between the two dates is less than seven days,
but it returns 1 to wY because there is a seven-day difference between the first days of the respective calendar weeks.
Caution
When the time part of Date1 is greater than that of Date2 and Interval is set to DateInterval.WeekOfYear, the DateD
iff function returns a value that is one less than the correct value.
Larger Intervals. If Interval is set to DateInterval.Year, the return value is calculated purely from the year parts of
Date1 and Date2. Similarly, the return value for DateInterval.Month is calculated purely from the year and month parts
of the arguments, and for DateInterval.Quarter from the quarters containing the two dates.
For example, when comparing December 31 to January 1 of the following year, DateDiff returns 1 for
DateInterval.Year, DateInterval.Quarter, or DateInterval.Month, even though at most only one day has elapsed.
Other Intervals. Since every Date value is supported by a DateTime structure, its methods give you additional options
in finding time intervals. For example, you can use the Subtract method in either of its overloaded forms:
System.DateTime.Subtract(System.TimeSpan) subtracts a TimeSpan from a Date variable to return another Date value,
and System.DateTime.Subtract(System.DateTime) subtracts a Date value to return a TimeSpan. You can time a process
to find out how many milliseconds it takes, as the following example shows.
VB
Dim startTime As Date = Now
' Run the process that is to be timed.
Dim runLength As Global.System.TimeSpan = Now.Subtract(startTime)
Dim millisecs As Integer = runLength.Milliseconds
Example
This example uses the DateDiff function to display the number of days between a given date and today.
VB
Dim firstDate, msg As String
Dim secondDate As Date
firstDate = InputBox("Enter a date")
secondDate = CDate(firstDate)
msg = "Days from today: " & DateDiff(DateInterval.Day, Now, secondDate)
MsgBox(msg)
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateAdd Function (Visual Basic)
DatePart Function (Visual Basic)
Day Function (Visual Basic)
Format Function
Now Property
Weekday Function (Visual Basic)
Year Function (Visual Basic)
Date Data Type (Visual Basic)
DateTime
TimeSpan
Visual Basic Language Reference
Parameters
Interval
Required. DateInterval enumeration value or String expression representing the part of the date/time value you want to
return.
DateValue
Required. Date value that you want to evaluate.
FirstDayOfWeekValue, DayOfWeek
Optional. A value chosen from the FirstDayOfWeek enumeration that specifies the first day of the week. If not specified,
FirstDayOfWeek.Sunday is used.
FirstWeekOfYearValue, WeekOfYear
Optional. A value chosen from the FirstWeekOfYear enumeration that specifies the first week of the year. If not specified,
FirstWeekOfYear.Jan1 is used.
Settings
The Interval argument can have one of the following settings.
Enumeration value String Part of date/time value to return
DateInterval.Day d Day of month (1 through 31)
DateInterval.Hour h Hour
DateInterval.Minute n Minute
DateInterval.Month m Month
DateInterval.Quarter q Quarter
DateInterval.Second s Second
FirstDayOfWeek.Tuesday 3 Tuesday
FirstDayOfWeek.Wednesday 4 Wednesday
FirstDayOfWeek.Thursday 5 Thursday
FirstDayOfWeek.Friday 6 Friday
FirstDayOfWeek.Saturday 7 Saturday
FirstWeekOfYear.FirstFourD 2 Week that has at least four days in the new year (complies with ISO standard 8601, secti
ays on 3.17)
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
You can use the DatePart function to evaluate a date/time value and return a specific component. For example, you might use
DatePart to calculate the day of the week or the current hour.
If you choose DateInterval.Weekday for the Interval argument, the returned value is consistent with the values of the
FirstDayOfWeek enumeration. If you choose DateInterval.WeekOfYear, DatePart uses the Calendar and CultureInfo
classes of the System.Globalization namespace to determine your current settings.
The FirstDayOfWeekValue argument affects calculations that use the DateInterval.Weekday and
DateInterval.WeekOfYear Interval settings. The FirstWeekOfYearValue argument affects calculations that specify
DateInterval.WeekOfYear for Interval.
Since every Date value is supported by a DateTime structure, its methods give you additional options in retrieving date/time
parts. For example, you can obtain the entire date value of a Date variable, with the time value set to midnight, as follows:
Example
This example takes a date and, using the DatePart function, displays the quarter of the year in which it occurs.
VB
Dim FirstDate, Msg As String 'Declare variables.
Dim SecondDate As Date
FirstDate = InputBox("Enter a date:")
SecondDate = CDate(FirstDate)
Msg = "Quarter: " & DatePart(DateInterval.Quarter, SecondDate)
MsgBox(Msg)
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateAdd Function (Visual Basic)
DateDiff Function (Visual Basic)
Day Function (Visual Basic)
Format Function
Now Property
Weekday Function (Visual Basic)
Year Function (Visual Basic)
Date Data Type (Visual Basic)
System
Visual Basic Language Reference
Parameters
Year
Required. Integer expression from 1 through 9999. However, values below this range are also accepted. If Year is 0 through
99, it is interpreted as being between 1930 and 2029, as explained in the "Remarks" section below. If Year is less than 1, it is
subtracted from the current year.
Month
Required. Integer expression from 1 through 12. However, values outside this range are also accepted. The value of Month is
offset by 1 and applied to January of the calculated year. In other words, (Month - 1) is added to January. The year is
recalculated if necessary. The following results illustrate this effect:
If Month is 1, the result is January of the calculated year.
If Month is 0, the result is December of the previous year.
If Month is -1, the result is November of the previous year.
If Month is 13, the result is January of the following year.
Day
Required. Integer expression from 1 through 31. However, values outside this range are also accepted. The value of Day is
offset by 1 and applied to the first day of the calculated month. In other words, (Day - 1) is added to the first of the month.
The month and year are recalculated if necessary. The following results illustrate this effect:
If Day is 1, the result is the first day of the calculated month.
If Day is 0, the result is the last day of the previous month.
If Day is -1, the result is the penultimate day of the previous month.
If Day is past the end of the current month, the result is the appropriate day of the following month. For example, if
Month is 4 and Day is 31, the result is May 1.
Remarks
Under Windows 98 or Windows 2000, two-digit years for the Year argument are interpreted based on user-defined computer
settings. The default settings are that values from 0 through 29 are interpreted as the years 2000–2029, and values from 30
through 99 are interpreted as the years 1930–1999. For all other Year arguments, use a four-digit year; for example, 1924.
Earlier versions of Windows interpret two-digit years based on the defaults described previously. To be sure the function
returns the proper value, use a four-digit Year.
The following example demonstrates negative, zero, and positive argument values. Here, the DateSerial function returns a
Date representing the day before the first day of March in the year 10 years before the current year; in other words, the last
day of February ten years ago.
If either Month or Day exceeds its normal range, it is applied to the next larger unit as appropriate. For example, if you specify
32 days, it is evaluated as one month and from one to four days, depending on the value of Month. If Year is greater than 9999,
or if any argument is outside the range -2,147,483,648 through 2,147,483,647, an ArgumentException error occurs. If the date
specified by the three arguments is earlier than 00:00:00 on January 1 of the year 1, or later than 23:59:59 on December 31,
9999, an ArgumentOutOfRangeException error occurs.
The Date data type includes time components. DateSerial sets all of these to 0, so the returned value represents the
beginning of the calculated day.
Since every Date value is supported by a DateTime structure, its methods give you additional options in assembling a Date
value. For example, you can use one of the overloaded DateTime constructors to populate a Date variable using the desired
combination of components. The following example sets NewDateTime to May 6, 1978 at one tenth of a second before 8:30 in
the morning:
Example
This example uses the DateSerial function to return the date for the specified year, month, and day.
VB
Dim MyDate As Date
' MyDate contains the date for February 12, 1969.
MyDate = DateSerial(1969, 2, 12) ' Return a date.
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateValue Function (Visual Basic)
Day Function (Visual Basic)
Month Function (Visual Basic)
Now Property
TimeSerial Function (Visual Basic)
TimeValue Function (Visual Basic)
Weekday Function (Visual Basic)
Year Function (Visual Basic)
Date Data Type (Visual Basic)
System
Visual Basic Language Reference
Parameters
StringDate
Required. String expression representing a date/time value from 00:00:00 on January 1 of the year 1 through 23:59:59 on
December 31, 9999.
Exceptions
Exception type Error number Condition
InvalidCastException 13 StringDate includes invalid time information.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If StringDate includes only numbers from 1 through 12 separated by valid date separators, DateValue recognizes the order
for month, day, and year according to the Short Date format specified for your system. DateValue uses the current calendar
setting from the CurrentCulture property of the CultureInfo class in the System.Globalization namespace. The default
CurrentCulture values are determined by Control Panel settings. You can override the Short Date format by setting the
ShortDatePattern property of the DateTimeFormatInfo class in the System.Globalization namespace.
DateValue recognizes month names in long, abbreviated, and numeric form. For example, in addition to recognizing
12/30/1991 and 12/30/91, DateValue also recognizes December 30, 1991 and Dec 30, 1991.
If the year part of StringDate is omitted, DateValue uses the current year from your computer's system date.
If the StringDate argument includes time information, DateValue does not include it in the returned value. However, if
StringDate includes invalid time information, such as "89:98", an InvalidCastException error occurs.
Example
This example uses the DateValue function to convert a string to a date. You can also use date literals to directly assign a date
to an Object or Date variable, for example, oldDate = #2/12/69#.
VB
Dim oldDate As Date
oldDate = DateValue("February 12, 1969")
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateSerial Function (Visual Basic)
Day Function (Visual Basic)
Month Function (Visual Basic)
Now Property
TimeSerial Function (Visual Basic)
TimeValue Function (Visual Basic)
Weekday Function (Visual Basic)
Year Function (Visual Basic)
Date Data Type (Visual Basic)
DateTime
Visual Basic Language Reference
Parameters
DateValue
Required. Date value from which you want to extract the day.
Remarks
If you use the Day function, you might have to qualify it with the Microsoft.VisualBasic namespace, because the
System.Windows.Forms namespace defines Day as an enumeration. The following example shows how qualifying Day resolves
this ambiguity:
You can also obtain the day of the month by calling DatePart and specifying DateInterval.Day for the Interval argument.
Example
The following example uses the Day function to obtain the day of the month from a specified date. In the development
environment, the date literal is displayed in standard short format (such as "02/12/1969") using the locale settings of your
code.
VB
Dim oldDate As Date
Dim oldDay As Integer
' Assign a date using standard short format.
oldDate = #2/12/1969#
oldDay = Microsoft.VisualBasic.DateAndTime.Day(oldDate)
' oldDay now contains 12.
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DatePart Function (Visual Basic)
Month Function (Visual Basic)
Now Property
Weekday Function (Visual Basic)
Year Function (Visual Basic)
DateTime
ArgumentException
ArgumentOutOfRangeException
Visual Basic Language Reference
DDB Function
Returns a Double specifying the depreciation of an asset for a specific time period using the double-declining balance method
or some other method you specify.
Function DDB( _
ByVal Cost As Double, _
ByVal Salvage As Double, _
ByVal Life As Double, _
ByVal Period As Double, _
Optional ByVal Factor As Double = 2.0 _
) As Double
Parameters
Cost
Required. Double specifying initial cost of the asset.
Salvage
Required. Double specifying value of the asset at the end of its useful life.
Life
Required. Double specifying length of useful life of the asset.
Period
Required. Double specifying period for which asset depreciation is calculated.
Factor
Optional. Double specifying rate at which the balance declines. If omitted, 2 (double-declining method) is assumed.
Exceptions
Exception type Error number Condition
ArgumentException 5 Factor <= 0, Salvage < 0, Period <= 0, or Period > Life.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The double-declining balance method computes depreciation at an accelerated rate. Depreciation is highest in the first period
and decreases in successive periods.
The Life and Period arguments must be expressed in the same units. For example, if Life is given in months, Period must also
be given in months. All arguments must be positive numbers.
The DDB function uses the following formula to calculate depreciation for a given period:
Depreciation / Period = ((Cost – Salvage) * Factor) / Life
Example
This example uses the DDB function to return the depreciation of an asset for a specified period given the initial cost
(InitCost), the salvage value at the end of the asset's useful life (SalvageVal), the total life of the asset in years (LifeTime), and
the period in years for which the depreciation is calculated (Depr).
VB
Dim InitCost, SalvageVal, LifeTime, DepYear As Double
Dim Fmt As String = "###,##0.00"
' Use the SLN function to calculate the deprecation per year.
Dim SlnDepr As Double = SLN(InitCost, SalvageVal, LifeTime)
Dim msg As String = "The depreciation per year: " & Format(SlnDepr, Fmt)
msg &= vbCrLf & "Year" & vbTab & "Linear" & vbTab & "Doubling" & vbCrLf
' Use the SYD and DDB functions to calculate the deprecation for each year.
For DepYear = 1 To LifeTime
msg &= DepYear & vbTab & _
Format(SYD(InitCost, SalvageVal, LifeTime, DepYear), Fmt) & vbTab & _
Format(DDB(InitCost, SalvageVal, LifeTime, DepYear), Fmt) & vbCrLf
Next
MsgBox(msg)
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
SLN Function
SYD Function
Financial Summary
ArgumentException
Visual Basic Language Reference
DeleteSetting Function
Deletes a section or key setting from an application's entry in the Windows registry.
The My feature gives you greater productivity and performance in registry operations than the DeleteSetting function. For
more information, see My.Computer.Registry Object.
Parameters
AppName
Required. String expression containing the name of the application or project to which the section or key setting applies.
Section
Required. String expression containing the name of the section from which the key setting is being deleted. If only
AppName and Section are provided, the specified section is deleted along with all related key settings.
Key
Optional. String expression containing the name of the key setting being deleted.
Exceptions
Exception type Error number Condition
ArgumentException 5 Section, AppName, or Key setting does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If all arguments are provided, the specified setting is deleted. A run-time error occurs if you attempt to use DeleteSetting on a
nonexistent section or key setting.
DeleteSetting requires that a user be logged on since it operates under the HKEY_LOCAL_USER registry key, which is not
active until a user logs on interactively.
Registry settings that are to be accessed from a non-interactive process (such as Mtx.exe) should be stored under either the
HKEY_LOCAL_MACHINE\Software\ or the HKEY_USER\DEFAULT\Software registry keys.
Example
The following example first uses the SaveSetting procedure to make entries in the Windows registry for the MyApp application,
and then uses the DeleteSetting function to remove them. Because no Key argument is specified, the whole Startup section
is deleted, including the section name and all of its keys.
VB
' Place some settings in the registry.
SaveSetting("MyApp", "Startup", "Top", "75")
SaveSetting("MyApp","Startup", "Left", "50")
' Remove section and all its settings from registry.
DeleteSetting ("MyApp", "Startup")
' Remove MyApp from the registry.
DeleteSetting ("MyApp")
Smart Device Developer Notes
This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
GetAllSettings Function
GetSetting Function
SaveSetting Function
ArgumentException Class
Visual Basic Language Reference
Dir Function
Returns a string representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the
volume label of a drive.
The My.Computer.FileSystem Object gives you greater productivity and performance in file I/O operations than the Dir
function. See My.Computer.FileSystem.GetDirectoryInfo Method for more information.
Parameters
PathName
Optional. String expression that specifies a file name, directory or folder name, or drive volume label. A zero-length string
("") is returned if PathName is not found.
Attributes
Optional. Enumeration or numeric expression whose value specifies file attributes. If omitted, Dir returns files that match
PathName but have no attributes.
Settings
The Attributes argument enumeration values are as follows:
Value Constant Description
Normal vbnormal Default. Specifies files with no attributes.
Volume vbVolume Specifies volume label; if any other attribute is specified, vbVolume is ignored.
Remarks
The Dir function supports the use of multiple-character (*) and single-character (?) wildcards to specify multiple files.
VbVolume returns the volume label for the drive instead of a specific file name.
You must supply a PathName the first time you call the Dir function. To retrieve the next item, you can make subsequent calls
to the Dir function with no parameters.
Security Note
To run correctly, the Dir function requires the Read and PathDiscovery flags of FileIOPermission to be granted to the executi
ng code. For more information, see FileIOPermission, SecurityException, and Code Access Permissions.
Example
This example uses the Dir function to check if certain files and directories exist.
VB
Dim MyFile, MyPath, MyName As String
' Returns "WIN.INI" if it exists.
MyFile = Dir("C:\WINDOWS\WIN.INI")
' Returns filename with specified extension. If more than one *.INI
' file exists, the first file found is returned.
MyFile = Dir("C:\WINDOWS\*.INI")
' Call Dir again without arguments to return the next *.INI file in the
' same directory.
MyFile = Dir()
' Return first *.TXT file, including files with a set hidden attribute.
MyFile = Dir("*.TXT", vbHidden)
Environ Function
Returns the string associated with an operating-system environment variable.
Parameters
Expression
Required. Expression that evaluates either a string containing the name of an environment variable, or an integer
corresponding to the numeric order of an environment string in the environment-string table.
Exceptions
Exception type Error number Condition
ArgumentException 5 Expression is missing.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If Expression contains a string, the Environ function returns the text assigned to the specified environment string—that is, the
text following the equal sign (=) in the environment-string table for that environment variable. If the string in Expression
cannot be found in the environment-string table, a zero-length string ("") is returned.
If Expression contains an integer, the string occupying that numeric position in the environment-string table is returned. In this
case, Environ returns all of the text, including the name of the environment variable. If there is no environment string in the
specified position, Environ returns a zero-length string.
Security Note
The Environ function requires environment permission, which might affect its execution in partial-trust situations. For more i
nformation, see SecurityPermission and Code Access Permissions.
Example
This example uses the Environ function to supply the entry number and length of the PATH statement from the environment-
string table.
VB
Sub tenv()
Dim envString As String
Dim found As Boolean = False
Dim index As Integer = 1
Dim pathLength As Integer
Dim message As String
envString = Environ(index)
While Not found And (envString <> "")
If (envString.Substring(0, 5) = "Path=") Then
found = True
Else
index += 1
envString = Environ(index)
End If
End While
If found Then
pathLength = Environ("PATH").Length
message = "PATH entry = " & index & " and length = " & pathLength
Else
message = "No PATH environment variable exists."
End If
MsgBox(message)
End Sub
EOF Function
Returns a Boolean value True when the end of a file opened for Random or sequential Input has been reached.
Parameters
FileNumber
Required. An Integer containing any valid file number.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Use EOF to avoid the error generated by attempting to get input past the end of a file.
The EOF function returns False until the end of the file has been reached. With files opened for Random or Binary access, EOF
returns False until the last executed FileGet function is unable to read an entire record.
With files opened for Binary access, an attempt to read through the file using the Input function until EOF returns True
generates an error. Use the LOF and Loc functions instead of EOF when reading binary files with Input, or use Get when using
the EOF function. With files opened for Output, EOF always returns True.
Example
This example uses the EOF function to detect the end of a file. This example assumes that Testfile is a text file with a few lines
of text.
VB
Dim TextLine As String
' Open file.
FileOpen(1, "TESTFILE", OpenMode.Input)
' Loop until end of file.
Do While Not EOF(1)
' Read line into variable.
TextLine = LineInput(1)
' Display result in a message box.
MsgBox("End of file reached at " & TextLine)
Loop
FileClose(1)
ErrorToString Function
Returns the error message that corresponds to a given error number.
Parameters
ErrorNumber
Optional. Any valid error number.
Exceptions
Exception type Error number Condition
ArgumentException 5 ErrorNumber is out of range.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The ErrorToString function examines the property settings of the Err object to identify the most recent run-time error. The
return value of the ErrorToString function corresponds to the Description property of the Err object. If ErrorNumber is a
valid error number but is not defined, ErrorToString returns the string "Application-defined or object-defined error." If
ErrorNumber is not valid, an error occurs. If ErrorNumber is omitted, the message corresponding to the most recent run-time
error is returned. If no run-time error has occurred or ErrorNumber is 0, ErrorToString returns a zero-length string ("").
In Visual Basic version 6.0 and earlier, this functionality was provided by the Error function.
Example
The following code uses the ErrorToString function to display error messages that correspond to the specified error numbers.
VB
Dim ErrorNumber As Integer
For ErrorNumber = 61 To 64 ' Loop through values 61 - 64.
MsgBox(ErrorToString(ErrorNumber)) ' Display error names in message box.
Next ErrorNumber
Requirements
Namespace: Microsoft.VisualBasic
Module: Conversion
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Description Property (Err Object)
ArgumentException
Concepts
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Visual Basic Language Reference
FileAttr Function
Returns an enumeration representing the file mode for files opened using the FileOpen function.
The My.Computer.FileSystem Object gives you greater productivity and performance in file I/O operations than the FileAttr
function. See My.Computer.FileSystem.GetFileInfo Method for more information.
Parameters
FileNumber
Required. Integer. Any valid file number.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Return Value
The following enumeration values indicate the file access mode:
Value Mode
1 OpenMode.Input
2 OpenMode.Output
4 OpenMode.Random
8 OpenMode.Append
32 OpenMode.Binary
Remarks
This function returns an enumeration representing the file mode for files opened using the FileOpen function.
Example
This example uses the FileAttr function to return the file mode of an open file.
VB
Dim mode As OpenMode
FileOpen(1, "c:\TESTFILE.TXT", OpenMode.Input)
mode = FileAttr(1)
MsgBox("The file mode is " & mode.ToString())
FileClose(1)
FileClose Function
Concludes input/output (I/O) to a file opened using the FileOpen function.
Using My gives you greater productivity and performance in file I/O operations. See My.Computer.FileSystem Object for more
information.
Parameters
FileNumbers
Optional. Parameter array of 0 or more channels to be closed.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The FileClose function is provided for backward compatibility and may affect performance. For non-legacy applications, the
My.Computer.FileSystem object provides better performance. For more information, see File Access with Visual Basic.
If you omit FileNumbers, all active files opened by the FileOpen function are closed.
When you close files that were opened for Output or Append, the final buffer of output is written to the operating system
buffer for that file. All buffer space associated with the closed file is released.
When the FileClose function is executed, the association of a file with its file number ends.
Example
This example uses the FileClose function to close a file opened for Input.
VB
Dim TextLine As String
FileOpen(1, "TESTFILE", OpenMode.Input) ' Open file.
Do While Not EOF(1) ' Loop until end of file.
TextLine = LineInput(1) ' Read line into variable.
MsgBox(TextLine) ' Display the line
Loop
FileClose(1) ' Close file.
FileCopy Function
Copies a file.
The My.Computer.FileSystem Object gives you greater productivity and performance in file I/O operations than FileCopy. See
My.Computer.FileSystem.CopyFile Method for more information.
Parameters
Source
Required. String expression that specifies the name of the file to be copied. Source may include the directory or folder, and
drive, of the source file.
Destination
Required. String expression that specifies the target file name. Destination may include the directory or folder, and drive, of
the destination file.
Exceptions
Exception type Error number Condition
ArgumentException 52 Source or Destination is invalid or not specified.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If you try to use the FileCopy function on a currently open file, an error occurs.
FileCopy requires full trust to work on the local drive.
Example
This example uses the FileCopy function to copy one file to another. For purposes of this example, assume that SrcFile is a
file containing some data.
VB
Dim SourceFile, DestinationFile As String
SourceFile = "SRCFILE" ' Define source file name.
DestinationFile = "DESTFILE" ' Define target file name.
FileCopy(SourceFile, DestinationFile) ' Copy source to target.
FileDateTime Function
Returns a Date value that indicates the date and time a file was created or last modified.
The My feature gives you greater productivity and performance in file I/O operations than FileDateTime. For more
information, see My.Computer.FileSystem.GetFileInfo Method.
Parameters
PathName
Required. String expression that specifies a file name. PathName may include the directory or folder, and the drive.
Exceptions
Exception type Error number Condition
ArgumentException 52 PathName is invalid or contains wildcards.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
This function returns a Date value that indicates the date and time a file was created or last modified.
Example
This example uses the FileDateTime function to determine the date and time a file was created or last modified. The format of
the date and time displayed is based on the locale settings of your system.
VB
Dim MyStamp As Date
' Assume TESTFILE was last modified on October 12, 2001 at 4:35:47 PM.
' Assume English/U.S. locale settings.
' Returns "10/12/2001 4:35:47 PM".
MyStamp = FileDateTime("C:\TESTFILE.txt")
FileGet Function
Reads data from an open disk file into a variable.
The My feature gives you greater productivity and performance in file I/O operations than FileGet. For more information, see
My.Computer.FileSystem Object.
Parameters
FileNumber
Required. Any valid file number.
Value
Required. Valid variable name into which data is read.
RecordNumber
Optional. Record number (Random mode files) or byte number (Binary mode files) at which reading begins.
ArrayIsDynamic
Optional. Applies only when writing an array. Specifies whether the array is to be treated as dynamic and whether an array
descriptor describing the size and bounds of the array is necessary.
StringIsFixedLength
Optional. Applies only when writing a string. Specifies whether to write a two-byte descriptor for the string describing the
length. The default is False.
Exceptions
Exception type Error number Condition
ArgumentException 63 RecordNumber < 1 and not equal to -1.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
FileGet is valid only in Random and Binary mode.
Data read with FileGet is usually written to a file with FilePut.
The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit RecordNumber,
the next record or byte following the last FileGet or FilePut function (or pointed to by the last Seek function) is read.
Security Note
When reading from files, do not make decisions about the contents of a file based on the file name extension. For example, a
file named Form1.vb may not be a Visual Basic source file.
Random Mode
For files opened in Random mode, the following rules apply:
If the length of the data being read is less than the length specified in the RecordLength clause of the FileOpen function,
FileGet reads subsequent records on record-length boundaries. The space between the end of one record and the
beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data
cannot be determined with any certainty, it is generally a good idea to have the record length match the length of the
data being read.
If the variable being read into is a string, by default FileGet reads a two-byte descriptor containing the string length and
then reads the data that goes into the variable. Therefore, the record length specified by the RecordLength clause of the
FileOpen function must be at least two bytes greater than the actual length of the string. Visual Basic 6.0 and earlier
versions support fixed-length strings; when put to a file, the length descriptor is not written. If you want to read a string
without the descriptor, you should pass True to the StringIsFixedLength parameter, and the string you read into should
be the correct length.
If the variable being read into is an array, you can choose whether to read a descriptor for the size and dimension of the
array. To write the descriptor, set the ArrayIsDynamic parameter to True. When reading the array, you need to match the
way the array was written. If it was written with the descriptor, you need to read the descriptor. If the descriptor is not
used, then the size and bounds of the array passed into FileGet determine what to read.
The descriptor specifies the rank of the array, the size, and the lower bounds for each rank. Its length equals 2 plus 8
times the number of dimensions: (2 + 8 * NumberOfDimensions). The record length specified by the RecordLength
parameter in the FileOpen function must be greater than or equal to the sum of all the bytes required to write the array
data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written
to disk.
VB
Dim MyArray(4,9) As Integer
FileGetObject Function
Reads data from an open disk file into a variable.
The My feature gives you greater productivity and performance in file I/O operations than FileGetObject. For more
information, see My.Computer.FileSystem Object.
Parameters
FileNumber
Required. Any valid file number.
Value
Required. Valid variable name into which data is read.
RecordNumber
Optional. Record number (Random mode files) or byte number (Binary mode files) at which reading begins.
ArrayIsDynamic
Optional. Applies only when writing an array. Specifies whether the array is to be treated as dynamic and so whether to write
an array descriptor describing the size and bounds of the array.
StringIsFixedLength
Optional. Applies only when writing a string. Specifies whether to write a two-byte descriptor for the string describing the
length. The default is False.
Remarks
The FileGetObject function is used in place of FileGet to avoid ambiguities at compile time if type Object is returned rather
than another type, such as Integer, Long, Short, and so forth.
If you intend to write out the Variant type, FileGetObject is required. When in doubt, if you are using an object for the second
parameter, it is always suggested that you use FilePutObject and FileGetObject.
FileGetObject is valid only in Random and Binary mode.
Data read with FileGetObject is usually written with FilePutObject.
The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit RecordNumber,
FileGetObject reads the record or byte after the last FileGetObject or FilePutObject function (or pointed to by the last Seek
function).
Random Mode
For files opened in Random mode, the following rules apply:
If the length of the data being read is less than the length specified in the RecordLength clause of the FileOpen function,
FileGetObject reads subsequent records on record-length boundaries. The space between the end of one record and the
beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data
cannot be precisely determined, it is a good idea to have the record length match the length of the data being read.
If the variable being read into is a string, by default FileGetObject reads a two-byte descriptor containing the string
length and then reads the data that goes into the variable. Therefore, the record length specified by the RecordLength
clause of the FileOpen function must be at least two bytes greater than the actual length of the string. Visual Basic 6.0
and earlier versions support fixed-length strings and when read to a file, the length descriptor is not written. If you want
to read a string without the descriptor, you should pass True to the StringIsFixedLength parameter, and the string you
read into should be the correct length.
If the variable being read into is an array, then you can choose to read a descriptor for the size and dimension of the
array. To read the descriptor, set the ArrayIsDynamic parameter to True. When reading the array, you need to match the
way the array was written. If it was written with the descriptor, you need to read the descriptor. If the descriptor is not
used, the size and bounds of the array passed into FileGetObject are used to determine what to read.
The descriptor specifies the rank of the array, the size, and the lower bounds for each rank. Its length equals 2 plus 8
times the number of dimensions: 2 + 8 * NumberOfDimensions. The record length specified by the RecordLength
parameter in the FileOpen function must be greater than or equal to the sum of all the bytes required to write the array
data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written
to disk:
VB
Dim MyArray(4,9) As Integer
The 118 bytes are distributed as follows: 18 bytes for the descriptor (2 + 8 * 2), and 100 bytes for the data (5 * 10 * 2).
FileGetObject reads elements of structures as if each were being read individually, except that there is no padding
between elements. On disk, a dynamic array in a user-defined type (written with FilePutObject) is prefixed by a
descriptor whose length equals 2 plus 8 times the number of dimensions: 2 + 8 * NumberOfDimensions. The record
length specified by the RecordLength clause in the FileOpen function must be greater than or equal to the sum of all the
bytes required to read the individual elements, including any arrays and their descriptors. The
VBFixedStringAttribute Class can be applied to string fields in the structures to indicate the size of string when written to
disk.
Binary Mode
For files opened in Binary mode, all of the Random rules apply, with these exceptions:
The RecordLength clause in the FileOpen function has no effect. FileGetObject reads all variables from disk
contiguously, that is, with no padding between records.
For any array other than an array in a structure, FileGetObject reads only the data. No descriptor is read.
FileGetObject reads variable-length strings that are not elements of structures without expecting the two-byte length
descriptor. The number of bytes read equals the number of characters already in the string.
Security Note
When reading from files, do not make decisions about the contents of a file based on the file name extension. For example, a
file named Form1.vb may not be a Visual Basic source file.
Example
The following example reads a record into a test file and then retrieves it.
VB
Dim c As Object = "test"
FileSystem.FileOpen(1, "test.dat", OpenMode.Binary)
FileSystem.FilePutObject(1, "ABCDEF")
FileSystem.Seek(1, 1)
FileSystem.FileGetObject(1, c)
MsgBox(c)
FileSystem.FileClose(1)
FileLen Function
Returns a Long value specifying the length of a file in bytes.
The My feature gives you greater productivity and performance in file I/O operations than FileLen. For more information, see
My.Computer.FileSystem.GetFileInfo Method.
Parameters
PathName
Required. String expression that specifies a file. PathName may include the directory or folder, and the drive.
Exceptions
Exception type Error number Condition
FileNotFoundException 53 File does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If the specified file is open when the FileLen function is called, the value returned represents the size of the file at the time it
was opened.
Note
To obtain the current length of an open file, use the LOF function.
Example
This example uses the FileLen function to return the length of a file in bytes. For purposes of this example, assume that
TestFile is a file containing some data.
VB
Dim MySize As Long
' Returns file length (bytes).
MySize = FileLen("TESTFILE")
FileOpen Function
Opens a file for input or output.
The My feature gives you greater productivity and performance in file I/O operations than FileOpen. For more information,
see My.Computer.FileSystem Object.
Parameters
FileNumber
Required. Any valid file number. Use the FreeFile function to obtain the next available file number.
FileName
Required. String expression that specifies a file name—may include directory or folder, and drive.
Mode
Required. Enumeration specifying the file mode: Append, Binary, Input, Output, or Random. (For more information, see
OpenMode Enumeration.)
Access
Optional. Enumeration specifying the operations permitted on the open file: Read, Write, or ReadWrite. Defaults to
ReadWrite. (For more information, see OpenAccess Enumeration.)
Share
Optional. Enumeration specifying the operations not permitted on the open file by other processes: Shared, Lock Read,
Lock Write, and Lock Read Write. Defaults to Lock Read Write. (For more information, see OpenShare Enumeration.)
RecordLength
Optional. Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For
sequential files, this value is the number of characters buffered.
Exceptions
Exception type Error number Condition
ArgumentException 5 Invalid Access, Share, or Mode.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The FileOpen function is provided for backward compatibility and may affect performance. For non-legacy applications, the
My.Computer.FileSystem object provides better performance. For more information, see File Access with Visual Basic.
You must open a file before any I/O operation can be performed on it. FileOpen allocates a buffer for I/O to the file and
determines the mode of access to use with the buffer.
Security Note
When writing to a file, an application may need to create a file, if the file to which it is trying to write does not exist. To do so, i
t needs permission for the directory in which the file is to be created. However, if the file specified by FileName does exist, th
e application needs Write permission only to the file itself. Wherever possible, to help improve security, create the file during
deployment and grant Write permission to that file only, rather than to the entire directory. To help improve security, write d
ata to user directories rather than to the root directory or the Program Files directory.
Example
This example illustrates various uses of the FileOpen function to enable input and output to a file.
The following code opens the file TestFile in Input mode.
VB
FileOpen(1, "TESTFILE", OpenMode.Input)
' Close before reopening in another mode.
FileClose(1)
This example opens the file in Binary mode for writing operations only.
VB
FileOpen(1, "TESTFILE", OpenMode.Binary,OpenAccess.Write)
' Close before reopening in another mode.
FileClose(1)
The following example opens the file in Random mode. The file contains records of the structure Person.
VB
Structure Person
<VBFixedString(30)> Dim Name As String
Dim ID As Integer
End Structure
Public Sub ExampleMethod()
' Count 30 for the string, plus 4 for the integer.
FileOpen(1, "TESTFILE", OpenMode.Random, , , 34)
' Close before reopening in another mode.
FileClose(1)
End Sub
This code example opens the file in Output mode; any process can read or write to file.
VB
FileOpen(1, "TESTFILE", OpenMode.Output, OpenAccess.Default, OpenShare.Shared)
' Close before reopening in another mode.
FileClose(1)
This code example opens the file in Binary mode for reading; other processes cannot read file.
VB
FileOpen(1, "TESTFILE", OpenMode.Binary, OpenAccess.Read, _
OpenShare.LockRead)
FilePut Function
Writes data from a variable to a disk file.
The My feature gives you greater productivity and performance in file I/O operations than FilePut. For more information, see
My.Computer.FileSystem Object.
Parameters
FileNumber
Required. Any valid file number.
Value
Required. Valid variable name containing data written to disk.
RecordNumber
Optional. Record number (Random mode files) or byte number (Binary mode files) at which writing begins.
ArrayIsDynamic
Optional. Applies only when writing an array. Specifies whether the array is to be treated as dynamic, and whether to write
an array descriptor for the string describing the length.
StringIsFixedLength
Optional. Applies only when writing a string. Specifies whether to write a two-byte string length descriptor for the string to
the file. The default is False.
Exceptions
Exception type Error number Condition
ArgumentException 63 RecordNumber < 1 and not equal to -1.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
FilePut is valid only in Random and Binary mode.
Data written with FilePut is usually read from a file with FileGet.
The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit RecordNumber,
the next record or byte after the last FileGet or FilePut function or pointed to by the last Seek function is written.
The StringIsFixedLength argument controls whether the function interprets strings as variable or fixed length. FilePut does not
write the length descriptor when the argument is True. If you use StringIsFixedLength = True with FilePut, you need to do the
same with FileGet, and you need to make sure the string is initialized to the length expected.
Random Mode
For files opened in Random mode, the following rules apply:
If the length of the data being written is less than the length specified in the RecordLength clause of the FileOpen
function, FilePut writes subsequent records on record-length boundaries. The space between the end of one record and
the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding
data cannot be determined with any certainty, it is generally a good idea to have the record length match the length of
the data being written. If the length of the data being written is greater than the length specified in the RecordLength
clause of the FileOpen function, an exception will be thrown.
If the variable being written is a string, FilePut writes a two-byte descriptor containing the string length, and then writes
the data that goes into the variable. Therefore, the record length specified by the RecordLength clause in the FileOpen
function must be at least two bytes greater than the actual length of the string.
If the variable being written is an object containing a numeric type, FilePut writes two bytes identifying the VarType of
the object and then writes the variable. For example, when writing an object containing an integer, FilePut writes six
bytes: two bytes identifying the object as VarType(3) (Integer) and four bytes containing the data. The record length
specified by the RecordLength parameter in the FileOpen function must be at least two bytes greater than the actual
number of bytes required to store the variable.
If the variable being written is an object containing a string, FilePut writes a two byte descriptor identifying the
VarType(8) of the object, a two-byte descriptor indicating the length of the string, and then writes the string data. The
record length specified by the RecordLength parameter in the FileOpen function must be at least four bytes greater than
the actual length of the string. If you wish to put a string without the descriptor, then you should pass True to the
StringIsFixedLength parameter, and the string you read into should be the correct length.
If the variable being written is an array, then you have a choice as to whether or not to write a descriptor for the size and
dimensions of the array. Visual Basic 6.0 and earlier versions write the file descriptor for a dynamic array but not for a
fixed-size array. Visual Basic 2005 defaults to not writing the descriptor. To write the descriptor, set the ArrayIsDynamic
parameter to True. When writing the array, you need to match the way the array will be read; if it will be read with the
descriptor, then you need to write the descriptor. The descriptor specifies the rank of the array, the size, and the lower
bounds for each rank. Its length equals 2 plus 8 times the number of dimensions: (2 + 8 * NumberOfDimensions). The
record length specified by the RecordLength clause in the FileOpen function must be greater than or equal to the sum of
all the bytes required to write the array data and the array descriptor. For example, the following array declaration
requires 118 bytes when the array is written to disk.
VB
Dim MyArray(4,9) As Integer
If the variable being written is any other type of variable (not a variable-length string or an object), FilePut writes only
the variable data. The record length specified by the RecordLength clause in the FileOpen function must be greater than
or equal to the length of the data being written.
FilePut writes elements of structures as if each were written individually, except there is no padding between elements.
The VBFixedString attribute can be applied to string fields in the structures to indicate the size of the string when
written to disk.
Note
String fields that have more bytes than specified by the VBFixedString attribute are truncated when written to disk,
Binary Mode
For files opened in Binary mode, most of the Random mode rules apply, with a few exceptions. The following rules for files
opened in Binary mode differ from the rules for Random mode:
The RecordLength clause in the FileOpen function has no effect. FilePut writes all variables to disk contiguously, that is,
with no padding between records.
For any array other than an array in a structure, FilePut writes only the data. No descriptor is written.
FilePut writes variable-length strings that are not elements of structures without the two-byte length descriptor. The
number of bytes written equals the number of characters in the string. For example, the following statements write 11
bytes to file number 1:
VB
Dim hellow As String = "Hello World"
FilePut(1,hellow)
Writing to a file with the FilePut function requires Write access from the FileIOPermissionAccess enumeration.
Example
This example uses the FilePut function to write data to a file. Five records of the structure Person are written to the file.
VB
Structure Person
Public ID As Integer
Public Name As String
End Structure
Sub WriteData()
Dim PatientRecord As Person
Dim recordNumber As Integer
' Open file for random access.
FileOpen(1, "C:\TESTFILE.txt", OpenMode.Binary)
' Loop 5 times.
For recordNumber = 1 To 5
' Define ID.
PatientRecord.ID = recordNumber
' Create a string.
PatientRecord.Name = "Name " & recordNumber
' Write record to file.
FilePut(1, PatientRecord)
Next recordNumber
FileClose(1)
End Sub
FilePutObject Function
Writes data from a variable to a disk file.
The My feature gives you greater productivity and performance in file I/O operations than FilePutObject. For more
information, see My.Computer.FileSystem Object.
Parameters
FileNumber
Required. Any valid file number.
Value
Required. Valid variable name containing data written to disk.
RecordNumber
Optional. Record number (Random mode files) or byte number (Binary mode files) at which writing begins.
ArrayIsDynamic
Optional. Applies only when writing an array. Specifies whether the array is to be treated as dynamic, and whether to write
an array descriptor for the string describing the length.
StringIsFixedLength
Optional. Applies only when writing a string. Specifies whether to write a descriptor for the string describing the length. The
default is False.
Remarks
The FilePutObject function is used in place of FilePut to avoid ambiguities at compile time if type Object is passed rather
than another type, such as Integer, Long, Short, and so forth.
FilePutObject writes and reads descriptors that describe the object. If you intend to write out the Variant type, FilePutObject
is required. When in doubt, if you are using an object for the second parameter, it is suggested that you always use
FilePutObject and FileGetObject.
FilePutObject is valid only in Random and Binary mode.
Data written with FilePutObject is usually read from a file with FileGetObject.
The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit RecordNumber,
FilePutObject writes the next record or byte after the last FileGetObject or FilePutObject function (or the record or byte
pointed to by the last Seek function).
The StringIsFixedLength argument controls whether the function interprets strings as variable or fixed length. FilePutObject
does not write the length descriptor when the argument is True. If you use StringIsFixedLength = True with FilePutObject,
you need to do the same with FileGetObject, and you must also make sure that the string is initialized to the length expected.
Random Mode
For files opened in Random mode, the following rules apply:
If the length of the data being written is less than the length specified in the RecordLength clause of the FileOpen
function, FilePutObject writes subsequent records on record-length boundaries. The space between the end of one
record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of
padding data cannot be precisely determined, it is generally a good idea to have the record length match the length of
the data being written. If the length of the data being written is greater than the length specified in the RecordLength
clause of the FileOpen function, an exception is thrown.
If the variable being written is an object containing a numeric type, FilePutObject writes two bytes identifying the
VarType of the object and then writes the variable. For example, when writing an object containing an integer,
FilePutObject writes six bytes: two bytes identifying the object as VarType(3) (Integer) and four bytes containing the
data. The record length specified by the RecordLength parameter in the FileOpen function must be at least two bytes
greater than the actual number of bytes required to store the variable.
If the variable being written is an object containing a string, FilePutObject writes a two-byte descriptor identifying the
VarType(8) of the object, a two-byte descriptor indicating the length of the string, and then writes the string data. The
record length specified by the RecordLength parameter in the FileOpen function must be at least four bytes greater than
the actual length of the string. If you wish to put a string without the descriptor, then you should pass True to the
StringIsFixedLength parameter, and the string you read into should be the correct length.
If the variable being written is an array, you can choose to write a descriptor for the size and dimensions of the array.
Visual Basic 6.0 and earlier versions would write the file descriptor for a dynamic array, but not for a fixed-size array;
Visual Basic defaults to not writing the descriptor. To write the descriptor, set the ArrayIsDynamic parameter to True.
When writing the array, you need to match the way the array is read; if it is read with the descriptor, you need to write
the descriptor. The descriptor specifies the rank of the array, the size, and the lower bounds for each rank. Its length
equals 2 plus 8 times the number of dimensions: (2 + 8 * NumberOfDimensions). The record length specified by the
RecordLength clause in the FileOpen function must be greater than or equal to the sum of all the bytes required to write
the array data and the array descriptor.
Binary Mode
For files opened in Binary mode, all of the Random mode rules apply, except:
The RecordLength clause in the FileOpen function has no effect. FilePutObject writes all variables to disk contiguously,
that is, with no padding between records.
Example
This example uses the FilePutObject function to write a string to a file.
VB
Sub WriteData()
Dim text As String = "test"
FileOpen(1, "test.bin", OpenMode.Binary)
FilePutObject(1, text)
FileClose(1)
End Sub
FileWidth Function
Assigns an output line width to a file opened using the FileOpen function.
Parameters
FileNumber
Required. Any valid file number.
RecordWidth
Required. Numeric expression in the range 0–255, inclusive, which indicates how many characters appear on a line before a
new line is started. If RecordWidth equals 0, there is no limit to the length of a line. The default value for RecordWidth is 0.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
This function assigns an output line width to a file opened using the FileOpen function.
Example
This example uses the FileWidth function to set the output line width for a file.
VB
Dim i As Integer
FileOpen(1, "TESTFILE", OpenMode.Output) ' Open file for output.
FileWidth(1, 5) ' Set output line width to 5.
For i = 0 To 9 ' Loop 10 times.
Print(1, Chr(48 + I)) ' Prints five characters per line.
Next
FileClose(1) ' Close file.
Function Filter(
ByVal Source() As { Object | String },
ByVal Match As String,
Optional ByVal Include As Boolean = True,
Optional ByVal Compare As CompareMethod = CompareMethod.Binary
) As String()
Parameters
Source
Required. One-dimensional array of strings to be searched.
Match
Required. String to search for.
Include
Optional. Boolean value indicating whether to return substrings that include or exclude Match. If Include is True, the Filter
function returns the subset of the array that contains Match as a substring. If Include is False, the Filter function returns the
subset of the array that does not contain Match as a substring.
Compare
Optional. Numeric value indicating the kind of string comparison to use. See "Settings" for values.
Settings
The Compare argument can have the following values.
Constant Description
CompareMethod.Binary Performs a binary comparison
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If no matches of Match are found within Source, the Filter function returns an empty array. An error occurs if Source is set to
Nothing or is not a one-dimensional array.
The array returned by the Filter function contains only enough elements to contain the number of matched items.
Example
This example demonstrates the use of the Filter function.
VB
Dim TestStrings(2) As String
TestStrings(0) = "This"
TestStrings(1) = "Is"
TestStrings(2) = "It"
Dim subStrings() As String
' Returns ["This", "Is"].
subStrings = Filter(TestStrings, "is", True, CompareMethod.Text)
' Returns ["This"].
subStrings = Filter(TestStrings, "is", True, CompareMethod.Binary)
' Returns ["Is", "It"].
subStrings = Filter(TestStrings, "is", False, CompareMethod.Binary)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Replace Function (Visual Basic)
ArgumentException
Visual Basic Language Reference
Parameters
Number
Required. A number of type Double or any valid numeric expression. If Number contains Nothing, Nothing is returned.
Exceptions
Exception type Error number Condition
ArgumentNullException 5 Number is not specified.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Both the Int and Fix functions remove the fractional part of Number and return the resulting integer value.
The difference between Int and Fix functions is that if Number is negative, Int returns the first negative integer less than or
equal to Number, whereas Fix returns the first negative integer greater than or equal to Number. For example, Int converts -
8.4 to -9, and Fix converts -8.4 to -8.
Fix(number) is equivalent to Sign(number) * Int(Abs(number)).
Example
This example illustrates how the Int and Fix functions return integer portions of numbers. In the case of a negative number
argument, the Int function returns the first negative integer less than or equal to the number; the Fix function returns the first
negative integer greater than or equal to the number. The following example requires you to specify Option Strict Off
because implicit conversions from type Double to type Integer are not allowed under Option Strict On:
VB
' This code requires Option Strict Off
Dim MyNumber As Integer
MyNumber = Int(99.8) ' Returns 99.
MyNumber = Fix(99.8) ' Returns 99.
You can use the CInt function to explicitly convert other data types to type Integer with Option Strict Off. However, CInt
rounds to the nearest integer instead of truncating the fractional part of numbers. For example:
VB
MyNumber = CInt(99.8) ' Returns 100.
MyNumber = CInt(-99.8) ' Returns -100.
MyNumber = CInt(-99.2) ' Returns -99.
You can use the CInt function on the result of a call to Fix or Int to perform explicit conversion to integer without rounding.
For example:
VB
MyNumber = CInt(Fix(99.8)) ' Returns 99.
MyNumber = CInt(Int(99.8)) ' Returns 99.
Format Function
Returns a string formatted according to instructions contained in a format String expression.
Parameters
Expression
Required. Any valid expression.
Style
Optional. A valid named or user-defined format String expression.
Settings
For information on how to create the Style argument, see the appropriate topic listed below:
To format Do this
Numbers Use predefined numeric formats or create user-defined numeric formats.
Dates and times Use predefined date/time formats or create user-defined date/time formats.
Date and time serial numbers Use date and time formats or numeric formats.
If you try to format a number without specifying Style, the Format function provides functionality similar to the Str function,
although it is internationally aware. However, positive numbers formatted as strings using the Format function don't include a
leading space reserved for the sign of the value; those converted using the Str function retain the leading space.
Remarks
If you are formatting a nonlocalized numeric string, you should use a user-defined numeric format to ensure that you get the
look you want.
The System.String.Format method also provides similar functionality.
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".
TestStr = Format(23)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Different Formats for Different Numeric Values (Format Function)
Predefined Date/Time Formats (Format Function)
Predefined Numeric Formats (Format Function)
Str Function
Type Conversion Functions
User-Defined Date/Time Formats (Format Function)
User-Defined Numeric Formats (Format Function)
Format
Visual Basic Language Reference
Two sections The first section applies to positive values and zeros; the second applies to negative values.
Three sections The first section applies to positive values, the second applies to negative values, and the third applies to zero
s.
The following example has two sections: the first defines the format for positive values and zeros; the second section defines
the format for negative values. Since the Style argument of the Format function takes a string, it is enclosed by quotation
marks.
VB
Dim Style1 As String = "$#,##0;($#,##0)"
If you include semicolons with nothing between them, the missing section is printed using the format of the positive value. For
example, the following format displays positive and negative values using the format in the first section and displays Zero if
the value is zero.
VB
Dim Style2 As String = "$#,##0;;\Z\e\r\o"
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Predefined Numeric Formats (Format Function)
Format Function
String Manipulation Summary
Visual Basic Language Reference
Currency, C, Displays number with thousand separator, if appropriate; displays two digits to the right of the decimal separato
or c r. Output is based on system locale settings.
Fixed, F, or f Displays at least one digit to the left and two digits to the right of the decimal separator.
Standard, N, Displays number with thousand separator, at least one digit to the left and two digits to the right of the decimal
or n separator.
Percent Displays number multiplied by 100 with a percent sign (%) appended immediately to the right; always displays t
wo digits to the right of the decimal separator.
P, or p Displays number with thousandths separator multiplied by 100 with a percent sign (%) appended to the right a
nd separated by a single space; always displays two digits to the right of the decimal separator.
D, or d Displays number as a string that contains the value of the number in Decimal (base 10) format. This option is su
pported for integral types (Byte, Short, Integer, Long) only.
X, or x Displays number as a string that contains the value of the number in Hexadecimal (base 16) format. This option
is supported for integral types (Byte, Short, Integer, Long) only.
Long Date, Medium Da Displays a date according to your current culture's long date format.
te, or D
Short Date, or d Displays a date using your current culture's short date format.
Long Time, Medium Ti Displays a time using your current culture's long time format; typically includes hours, minutes, seco
me, or T nds.
Short Time, or t Displays a time using your current culture's short time format.
f Displays the long date and short time according to your current culture's format.
F Displays the long date and long time according to your current culture's format.
g Displays the short date and short time according to your current culture's format.
U Formats the date and time with the long date and long time as GMT.
For more information about the application's current culture information, see How Culture Affects Strings in Visual Basic.
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Conversion Summary
Format Function
Predefined Numeric Formats (Format Function)
User-Defined Date/Time Formats (Format Function)
Visual Basic Language Reference
(/) Date separator. In some locales, other characters may be used to represent the date separator. The date separator separate
s the day, month, and year when date values are formatted. The actual character used as the date separator in formatted o
utput is determined by your application's current culture.
(%) Used to indicate that the following character should be read as a single-letter format without regard to any trailing letters.
Also used to indicate that a single-letter format is read as a user-defined format. See below for further details.
d Displays the day as a number without a leading zero (for example, 1). Use %d if this is the only character in your user-defi
ned numeric format.
dd Displays the day as a number with a leading zero (for example, 01).
M Displays the month as a number without a leading zero (for example, January is represented as 1). Use %M if this is the on
ly character in your user-defined numeric format.
M Displays the month as a number with a leading zero (for example, 01/12/01).
M
h Displays the hour as a number without leading zeros using the 12-hour clock (for example, 1:15:15 PM). Use %h if this is t
he only character in your user-defined numeric format.
hh Displays the hour as a number with leading zeros using the 12-hour clock (for example, 01:15:15 PM).
H Displays the hour as a number without leading zeros using the 24-hour clock (for example, 1:15:15). Use %H if this is the
only character in your user-defined numeric format.
HH Displays the hour as a number with leading zeros using the 24-hour clock (for example, 01:15:15).
m Displays the minute as a number without leading zeros (for example, 12:1:15). Use %m if this is the only character in your
user-defined numeric format.
m Displays the minute as a number with leading zeros (for example, 12:01:15).
m
s Displays the second as a number without leading zeros (for example, 12:15:5). Use %s if this is the only character in your
user-defined numeric format.
ss Displays the second as a number with leading zeros (for example, 12:15:05).
f Displays fractions of seconds. For example ff will display hundredths of seconds, whereas ffff will display ten-thousandths
of seconds. You may use up to seven f symbols in your user-defined format. Use %f if this is the only character in your us
er-defined numeric format.
t Uses the 12-hour clock and displays an uppercase A for any hour before noon; displays an uppercase P for any hour betwe
en noon and 11:59 P.M. Use %t if this is the only character in your user-defined numeric format.
tt For locales that use a 12-hour clock, displays an uppercase AM with any hour before noon; displays an uppercase PM with a
ny hour between noon and 11:59 P.M.
For locales that use a 24-hour clock, displays nothing.
y Displays the year number (0-9) without leading zeros. Use %y if this is the only character in your user-defined numeric for
mat.
yy Displays the year in two-digit numeric format with a leading zero, if applicable.
z Displays the timezone offset without a leading zero (for example, -8). Use %z if this is the only character in your user-defi
ned numeric format.
zz Displays the timezone offset with a leading zero (for example, -08)
For more information about the application's current culture information, see How Culture Affects Strings in Visual Basic.
Example
The following are examples of user-defined date and time formats for December 7, 1958, 8:50 PM, 35 seconds:
Format Displays
M/d/yy 12/7/58
d-MMM 7-Dec
d-MMMM-yy 7-December-58
d MMMM 7 December
MMMM yy December 58
hh:mm tt 08:50 PM
h:mm:ss t 8:50:35 P
H:mm 20:50
H:mm:ss 20:50:35
(0 Digit placeholder. Displays a digit or a zero. If the expression has a digit in the position where the zero appears in the format
) string, display it; otherwise, displays a zero in that position.
If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, displays leading
or trailing zeros. If the number has more digits to the right of the decimal separator than there are zeros to the right of the d
ecimal separator in the format expression, rounds the number to as many decimal places as there are zeros. If the number h
as more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expr
ession, displays the extra digits without modification.
(# Digit placeholder. Displays a digit or nothing. If the expression has a digit in the position where the # character appears in th
) e format string, displays it; otherwise, displays nothing in that position.
This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren't displayed if the number has fewe
r digits than there are # characters on either side of the decimal separator in the format expression.
(.) Decimal placeholder. The decimal placeholder determines how many digits are displayed to the left and right of the decimal
separator. If the format expression contains only # characters to the left of this symbol; numbers smaller than 1 begin with a
decimal separator. To display a leading zero displayed with fractional numbers, use zero as the first digit placeholder to the l
eft of the decimal separator. In some locales, a comma is used as the decimal separator. The actual character used as a deci
mal placeholder in the formatted output depends on the number format recognized by your system. Thus, you should use t
he period as the decimal placeholder in your formats even if you are in a locale that uses a comma as a decimal placeholder.
The formatted string will appear in the format correct for the locale.
( Percent placeholder. Multiplies the expression by 100. The percent character (%) is inserted in the position where it appears
% in the format string.
)
(,) Thousand separator. The thousand separator separates thousands from hundreds within a number that has four or more pl
aces to the left of the decimal separator. Standard use of the thousand separator is specified if the format contains a thousa
nd separator surrounded by digit placeholders (0 or #).
A thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) or as the right
most character in the string means "scale the number by dividing it by 1,000, rounding as needed." Numbers smaller than 1
,000 but greater or equal to 500 are displayed as 1, and numbers smaller than 500 are displayed as 0. Two adjacent thousan
d separators in this position scale by a factor of 1 million, and an additional factor of 1,000 for each additional separator.
Multiple separators in any position other than immediately to the left of the decimal separator or the rightmost position in t
he string are treated simply as specifying the use of a thousand separator. In some locales, a period is used as a thousand se
parator. The actual character used as the thousand separator in the formatted output depends on the Number Format recog
nized by your system. Thus, you should use the comma as the thousand separator in your formats even if you are in a locale
that uses a period as a thousand separator. The formatted string will appear in the format correct for the locale.
For example, consider the three following format strings:
"#,0.", which uses the thousands separator to format the number 100 million as the string "100,000,000".
"#0,.", which uses scaling by a factor of one thousand to format the number 100 million as the string "100000".
"#,0,.", which uses the thousands separator and scaling by one thousand to format the number 100 million as the st
ring "100,000".
(:) Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates
hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted o
utput is determined by your system settings.
(/ Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates
) the day, month, and year when date values are formatted. The actual character used as the date separator in formatted outp
ut is determined by your system settings.
(E Scientific format. If the format expression contains at least one digit placeholder (0 or #) to the left of E-, E+, e-, or e+, the n
- umber is displayed in scientific format and E or e is inserted between the number and its exponent. The number of digit plac
E eholders to the left determines the number of digits in the exponent. Use E- or e- to place a minus sign next to negative exp
+ onents. Use E+ or e+ to place a minus sign next to negative exponents and a plus sign next to positive exponents. You must
e also include digit placeholders to the right of this symbol to get correct formatting.
-
e
+
)
- Literal characters. These characters are displayed exactly as typed in the format string. To display a character other than one
+ of those listed, precede it with a backslash (\) or enclose it in double quotation marks (" ").
$
()
(\ Displays the next character in the format string. To display a character that has special meaning as a literal character, preced
) e it with a backslash (\). The backslash itself isn't displayed. Using a backslash is the same as enclosing the next character in
double quotation marks. To display a backslash, use two backslashes (\\).
Examples of characters that can't be displayed as literal characters are the date-formatting and time-formatting characters (
a, c, d, h, m, n, p, q, s, t, w, y, /, and :), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-fo
rmatting characters (@, &, <, >, and !).
(" Displays the string inside the double quotation marks (" "). To include a string in the style argument from within code, you
A must use Chr(34) to enclose the text (34 is the character code for a quotation mark (")).
B
C
")
Example
The following table contains some sample format expressions for numbers. (These examples all assume that your system's
locale setting is English-U.S.) The first column contains the format strings for the Style argument of the Format function; the
other columns contain the resulting output if the formatted data has the value given in the column headings.
Format (Style) "5" formatted as "-5" formatted as "0.5" formatted as
Zero-length string ("") 5 -5 0.5
0 5 -5 1
#,##0 5 -5 1
$#,##0;($#,##0) $5 ($5) $1
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Conversion Summary
Different Formats for Different Numeric Values (Format Function)
Format Function
Predefined Numeric Formats (Format Function)
User-Defined Date/Time Formats (Format Function)
Visual Basic Language Reference
Function FormatCurrency(
ByVal Expression As Object,
Optional ByVal NumDigitsAfterDecimal As Integer = -1,
Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault,
Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault,
Optional ByVal GroupDigits As TriState = TriState.UseDefault
) As String
Parameters
Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places are displayed to the right of the decimal. Default value is –1, which
indicates that the computer's regional settings are used.
IncludeLeadingDigit
Optional. TriState enumeration that indicates whether or not a leading zero is displayed for fractional values. See "Settings"
for values.
UseParensForNegativeNumbers
Optional. TriState enumeration that indicates whether or not to place negative values within parentheses. See "Settings" for
values.
GroupDigits
Optional. TriState enumeration that indicates whether or not numbers are grouped using the group delimiter specified in the
computer's regional settings. See "Settings" for values.
Settings
The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments take the following TriState enumeration
values.
Value Description
TriState.True True
TriState.False False
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
When one or more optional arguments are omitted, the computer's matching regional-settings values are used instead.
The position of the currency symbol relative to the currency value is determined by the system's regional settings.
Note
All settings information comes from the locale of the application. By default, that will be the locale set in the control panel. Ho
wever, it may be changed programmatically by using the .NET Framework, except leading zero, which comes from the Num
ber tab.
Example
The following example illustrates the use of the FormatCurrency function.
VB
Dim TestDebt As Double = -4456.43
Dim TestString As String
' Returns "($4,456.43)".
TestString = FormatCurrency(TestDebt, , , TriState.True, TriState.True)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
FormatDateTime Function (Visual Basic)
FormatNumber Function (Visual Basic)
FormatPercent Function (Visual Basic)
TriState Enumeration
ArgumentException
InvalidCastException
Visual Basic Language Reference
Function FormatDateTime(
ByVal Expression As DateTime,
Optional ByVal NamedFormat As DateFormat = DateFormat.GeneralDate
) As String
Parameters
Expression
Required. Date expression to be formatted.
NamedFormat
Optional. Numeric value that indicates the date/time format used. If omitted, DateFormat.GeneralDate is used.
Settings
The NamedFormat argument has the following settings.
Constant Description
DateFormat.Gener Display a date and/or time. Display a date part as a short date. If there is a time part, display it as a long ti
alDate me. If present, both parts display.
DateFormat.Long Display a date using the long date format specified in your computer's regional settings.
Date
DateFormat.Short Display a date using the short date format specified in your computer's regional settings.
Date
DateFormat.LongT Display a time using the time format specified in your computer's regional settings.
ime
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Date data type always contains both date and time information. For purposes of type conversion, Visual Basic considers
1/1/1 (January 1 of the year 1) to be a neutral value for the date, and 00:00:00 (midnight) to be a neutral value for the time. If
you format a Date value as a date/time string, FormatDateTime does not include neutral values in the resulting string. For
example, if you convert #1/1/0001 9:30:00# to a string, the result is "9:30:00 AM"; the date information is suppressed.
However, the date information is still present in the original Date value and can be recovered with functions such as DatePart.
Note
If you pass the Expression argument as a String literal, FormatDateTime interprets it according to the CurrentCulture settin
g of your application. However, if you pass it as a Date literal, use the format #mm/dd/yyyy#, because FormatDateTime al
ways interprets a Date literal according to the English (US) culture. This is necessary because, if an application is developed a
nd coded using Date literals from one culture, but is then executed on a platform with a different culture, the Date literals co
uld be parsed incorrectly.
Example
This example demonstrates the use of the FormatDateTime function.
VB
' English (US) format.
Dim TestDate As DateTime = #3/12/1999#
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FormatCurrency Function (Visual Basic)
FormatNumber Function (Visual Basic)
FormatPercent Function (Visual Basic)
DatePart Function (Visual Basic)
String Manipulation Summary
ArgumentException
Visual Basic Language Reference
Function FormatNumber(
ByVal Expression As Object,
Optional ByVal NumDigitsAfterDecimal As Integer = -1,
Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault,
Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault,
Optional ByVal GroupDigits As TriState = TriState.UseDefault
) As String
Parameters
Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places are displayed to the right of the decimal. The default value is –1, which
indicates that the computer's regional settings are used.
IncludeLeadingDigit
Optional. TriState constant that indicates whether a leading 0 is displayed for fractional values. See "Settings" for values.
UseParensForNegativeNumbers
Optional. TriState constant that indicates whether to place negative values within parentheses. See "Settings" for values.
GroupDigits
Optional. TriState constant that indicates whether or not numbers are grouped using the group delimiter specified in the
locale settings. See "Settings" for values.
Settings
The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings.
Constant Description
TriState.True True
TriState.False False
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
When one or more optional arguments are omitted the values for omitted arguments are provided by the locale settings.
Note
All settings information comes from the locale of the application. By default, that will be the locale set in the control panel. Ho
wever, it may be changed programmatically by using the .NET Framework.
Example
This example demonstrates the FormatNumber function.
VB
Dim TestNumber As Integer = 45600
' Returns "45,600.00".
Dim TestString As String = FormatNumber(TestNumber, 2, , , TriState.True)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
FormatCurrency Function (Visual Basic)
FormatDateTime Function (Visual Basic)
FormatPercent Function (Visual Basic)
TriState Enumeration
InvalidCastException
Visual Basic Language Reference
Function FormatPercent(
ByVal Expression As Object,
Optional ByVal NumDigitsAfterDecimal As Integer = -1,
Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault,
Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault,
Optional ByVal GroupDigits As TriState = TriState.UseDefault
) As String
Parameters
Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places to the right of the decimal are displayed. Default value is –1, which
indicates that the locale settings are used.
IncludeLeadingDigit
Optional. TriState constant that indicates whether or not a leading zero displays for fractional values. See "Settings" for
values.
UseParensForNegativeNumbers
Optional. TriState constant that indicates whether or not to place negative values within parentheses. See "Settings" for
values.
GroupDigits
Optional. TriState constant that indicates whether or not numbers are grouped using the group delimiter specified in the
locale settings. See "Settings" for values.
Settings
The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings.
Constant Description
TriState.True True
TriState.False False
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
When one or more optional arguments are omitted, the values for omitted arguments are provided by the locale settings.
Note
All settings information comes from the locale of the application. By default, that will be the locale set in the control panel. Ho
wever, it may be changed programmatically by using the .NET Framework.
Example
This example illustrates the use of the FormatPercent function.
VB
Dim TestNumber As Single = 0.76
' Returns "76.00%".
Dim TestString As String = FormatPercent(TestNumber)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
FormatCurrency Function (Visual Basic)
FormatDateTime Function (Visual Basic)
FormatNumber Function (Visual Basic)
TriState Enumeration
InvalidCastException
Visual Basic Language Reference
FreeFile Function
Returns an Integer value representing the next file number available for use by the FileOpen function.
Exceptions
Exception type Error number Condition
IOException 67 More than 255 files are in use.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Use FreeFile to supply a file number that is not already in use.
Example
This example uses the FreeFile function to return the next available file number. Five files are opened for output within the
loop, and some sample data is written to each.
VB
Dim count As Integer
Dim fileNumber As Integer
For count = 1 To 5
fileNumber = FreeFile()
FileOpen(fileNumber, "TEST" & count & ".TXT", OpenMode.Output)
PrintLine(fileNumber, "This is a sample.")
FileClose(fileNumber)
Next
FV Function
Returns a Double specifying the future value of an annuity based on periodic, fixed payments and a fixed interest rate.
Function FV( _
ByVal Rate As Double, _
ByVal NPer As Double, _
ByVal Pmt As Double, _
Optional ByVal PV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod _
) As Double
Parameters
Rate
Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of
10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
NPer
Required. Double specifying total number of payment periods in the annuity. For example, if you make monthly payments
on a four-year car loan, your loan has a total of 4 x 12 (or 48) payment periods.
Pmt
Required. Double specifying payment to be made each period. Payments usually contain principal and interest that doesn't
change over the life of the annuity.
PV
Optional. Double specifying present value (or lump sum) of a series of future payments. For example, when you borrow
money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make. If
omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are
due at the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Remarks
An annuity is a series of fixed cash payments made over time. An annuity can be a loan (such as a home mortgage) or an
investment (such as a monthly savings plan).
The Rate and NPer arguments must be calculated using payment periods expressed in the same units. For example, if Rate is
calculated using months, NPer must also be calculated using months.
For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as
dividend checks) is represented by positive numbers.
Example
This example uses the FV function to return the future value of an investment given the percentage rate that accrues per period
(APR / 12), the total number of payments (TotPmts), the payment (Payment), the current value of the investment (PVal), and a
number that indicates whether the payment is made at the beginning or end of the payment period (PayType). Note that
because Payment represents cash paid out, it is a negative number.
VB
Sub TestFV()
Dim TotPmts As Integer
Dim Payment, APR, PVal, Fval As Double
Dim PayType As DueDate
Dim Response As MsgBoxResult
' Define money format.
Dim Fmt As String = "###,###,##0.00"
Payment = CDbl(InputBox("How much do you plan to save each month?"))
APR = CDbl(InputBox("Enter the expected interest annual percentage rate."))
' Ensure proper form.
If APR > 1 Then APR = APR / 100
TotPmts = CInt(InputBox("For how many months do you expect to save?"))
Response = MsgBox("Do you make payments at the end of month?", MsgBoxStyle.YesNo)
If Response = MsgBoxResult.No Then
PayType = DueDate.BegOfPeriod
Else
PayType = DueDate.EndOfPeriod
End If
PVal = CDbl(InputBox("How much is in this savings account now?"))
Fval = FV(APR / 12, TotPmts, -Payment, -PVal, PayType)
MsgBox("Your savings will be worth " & Format(Fval, Fmt) & ".")
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
Visual Basic Language Reference
GetAllSettings Function
Returns a list of key settings and their respective values (originally created with SaveSetting) from an application's entry in
the Windows registry.
Using the My feature gives you greater productivity and performance in registry operations than GetAllSettings. For more
information, see My.Computer.Registry Object.
Parameters
AppName
Required. String expression containing the name of the application or project whose key settings are requested.
Section
Required. String expression containing the name of the section whose key settings are requested. GetAllSettings returns an
object that contains a two-dimensional array of strings. The strings contain all the key settings in the specified section, plus
their corresponding values.
Exceptions
Exception type Error number Condition
ArgumentException 5 User is not logged in.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
GetAllSettings returns an uninitialized Object if either AppName or Section does not exist.
Because it operates under the HKEY_LOCAL_USER registry key, which is not active until a user logs on interactively,
GetAllSettings requires that a user be logged on.
Registry settings that are to be accessed from a non-interactive process (such as Mtx.exe) should be stored under either the
HKEY_LOCAL_MACHINE\Software\ or the HKEY_USER\DEFAULT\Software registry keys.
Example
This example first uses the SaveSetting function to make entries in the Windows registry for the application specified as
AppName, then uses the GetAllSettings function to display the settings. Note that application names and Section names
cannot be retrieved with GetAllSettings. Finally, the DeleteSetting function removes the application's entries.
VB
' Object to hold 2-dimensional array returned by GetAllSettings.
' Integer to hold counter.
Dim MySettings(,) As String
Dim intSettings As Integer
' Place some settings in the registry.
SaveSetting("MyApp", "Startup", "Top", "75")
SaveSetting("MyApp", "Startup", "Left", "50")
' Retrieve the settings.
MySettings = GetAllSettings("MyApp", "Startup")
For intSettings = LBound(MySettings, 1) To UBound(MySettings, 1)
WriteLine(1, MySettings(intSettings, 0))
WriteLine(1, MySettings(intSettings, 1))
Next intSettings
DeleteSetting("MyApp")
Smart Device Developer Notes
This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DeleteSetting Function
GetSetting Function
SaveSetting Function
ArgumentException Class
Concepts
Common Registry Tasks
Visual Basic Language Reference
GetAttr Function
Returns a FileAttribute value representing the attributes of a file, directory, or folder.
The My feature gives you greater productivity and performance in file I/O operations than FileAttribute. For more
information, see My.Computer.FileSystem Object.
Parameters
PathName
Required. String expression that specifies a file, directory, or folder name. PathName can include the directory or folder, and
the drive.
Return Value
The value returned by GetAttr is the sum of the following enumeration values:
Value Constant Description
Normal vbNormal Normal.
Exceptions
Exception type Error number Condition
IOException 52 Pathname is invalid or contains wildcards.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
To determine which attributes are set, use the And operator to perform a bitwise comparison of the value returned by the
GetAttr function and the value of the individual file attribute you want. If the result is not zero, that attribute is set for the
named file. For example, the return value of the following And expression is zero if the Archive attribute is not set:
GetChar Function
Returns a Char value representing the character from the specified index in the supplied string.
Parameters
str
Required. Any valid String expression.
Index
Required. Integer expression. The (1-based) index of the character in str to be returned.
Exceptions
Exception type Error number Condition
ArgumentException 5 str is Nothing, Index < 1, or Index is greater than index of last character of str.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If Index is less than 1 or greater than the index of the last character in str, an ArgumentException is thrown.
Example
This example shows how to use the GetChar function to return a character from a specified index in a String.
VB
Dim TestString As String = "ABCDE"
Dim TestChar As Char
' Returns "D"
TestChar = GetChar(TestString, 4)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Mid Function (Visual Basic)
ArgumentException
Visual Basic Language Reference
GetException Function
Returns the exception representing the error that occurred.
Remarks
The GetException function is available only from the Err object class. It works with the Exception property of the Err object
to display the error that has occurred.
Example
The following code displays the message assigned to the exception in the Err object:
VB
On Error Resume Next
Dim myError As System.Exception
' Generate an overflow exception.
Err.Raise(6)
' Assigns the exception from the Err object to myError.
myError = Err.GetException()
' Displays the message associated with the exception.
MsgBox(myError.Message)
Requirements
Namespace: Microsoft.VisualBasic
Class: Err Object
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Retrieve Information from an Error Object
Reference
Err Object (Visual Basic)
Concepts
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Visual Basic Language Reference
Parameters
Parame Description
ter
PathNa Optional. String. The full path and name of the file containing the object to retrieve. If PathName is omitted or is a ze
me ro-length string (""), Class is required.
Class Required if PathName is not supplied. String. A string representing the class of the object. The Class argument has th
e following syntax and parts:
appname . objecttype
Parameter Description
appname Required. String. The name of the application providing the object.
FileNotFoundException 432 No object with the specified path and file name exists.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Use the GetObject function to load an instance of a COM component from a file. The following example illustrates this.
When this code runs, the application associated with the specified PathName is started and the object in the specified file is
activated.
Default Cases
If PathName is a zero-length string (""), GetObject returns a new object instance of the specified class type. If the PathName
argument is omitted, GetObject returns a currently active object of the class type specified in Class. If no object of the specified
type exists, an error occurs.
Accessing a Subobject
Some applications allow you to activate a subobject associated with a file. To do this, add an exclamation point (!) to the end of
the file name and follow it with a string that identifies the part of the file you want to activate. For information on how to create
this string, see the documentation for the application that created the object.
For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following
code to activate a layer within a drawing called schema.cad.
layerObject = GetObject("C:\CAD\schema.cad!Layer3")
Specifying a Class
If you do not specify the object's Class, Automation determines the application to start and the object to activate, based on the
file name you provide. Some files, however, can support more than one class of object. For example, a drawing might support
three different types of objects: an Application object, a Drawing object, and a Toolbar object, all of which are part of the same
file. To specify which object in a file you want to activate, use the optional Class argument. The following example illustrates
this.
In the preceding example, Figment is the name of a drawing application and Drawing is one of the object types it supports.
Using the Object
Once an object is activated, you refer to it in code using the object variable you declared. In the preceding example, you access
properties and methods of the new object using the object variable drawObj. The following example illustrates this.
drawObj.Line(9, 90)
drawObj.InsertText(9, 100, "Hello, world.")
drawObj.SaveAs("C:\Drawings\sample.drw")
Note
Use the GetObject function when there is a current instance of the object or if you want to create the object with a file loade
d. If there is no current instance, and you do not want the object started with a file loaded, use the
CreateObject Function (Visual Basic).
If an object has registered itself as an ActiveX single-instance object, only one instance of the object is created, no matter how
many times CreateObject is called. With a single-instance object, GetObject always returns the same instance when called
with the zero-length string ("") syntax, and it causes an error if the PathName argument is omitted. You cannot use GetObje
ct to obtain a reference to a class created with Visual Basic.
Security Note
The GetObject function requires unmanaged code permission, which might affect its execution in partial-trust situations. For
more information, see SecurityPermission and Code Access Permissions.
When you are finished using the object, set all references to the object to Nothing. This allows the runtime to dispose of the
COM component.
Example
The following example uses the GetObject function to determine whether Excel is running.
VB
' Test to see if a copy of Excel is already running.
Private Sub testExcelRunning()
On Error Resume Next
' GetObject called without the first argument returns a
' reference to an instance of the application. If the
' application is not already running, an error occurs.
Dim excelObj As Object = GetObject(, "Excel.Application")
If Err.Number = 0 Then
MsgBox("Excel is running")
Else
MsgBox("Excel is not running")
End If
Err.Clear()
excelObj = Nothing
End Sub
The following example uses the GetObject function to obtain a reference to a specific Microsoft Excel worksheet (excelObj).
The call to GetObject returns a reference to the worksheet represented by the specified file, test.xls. Next, the example code
makes both Excel and the window containing the specified worksheet visible.
This example requires Option Strict Off because it uses late binding, where objects are assigned to variables of type Object.
You can specify Option Strict On and declare objects of specific object types if you add a project reference to the Excel type
library. To do so, open the Add Reference dialog box from the Project menu in Visual Studio and select the Excel type library
on the COM tab.
VB
' Add Option Strict Off to the top of your program.
Option Strict Off
VB
Private Sub getExcel()
Dim fileName As String = "c:\vb\test.xls"
excelObj = Nothing
End Sub
GetSetting Function
Returns a key setting value from an application's entry in the Windows registry.
The My feature gives you greater productivity and performance in registry operations than GetAllSettings. For more
information, see My.Computer.Registry Object.
Parameters
AppName
Required. String expression containing the name of the application or project whose key setting is requested.
Section
Required. String expression containing the name of the section in which the key setting is found.
Key
Required. String expression containing the name of the key setting to return.
Default
Optional. Expression containing the value to return if no value is set in the Key setting. If omitted, Default is assumed to be a
zero-length string ("").
Exceptions
Exception type Error number Condition
ArgumentException 5 One or more arguments are not String expressions, or user is not logged in.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If any of the items named in the GetSetting arguments do not exist, GetSetting returns a value of Default.
Because it operates under the HKEY_LOCAL_USER registry key, which is not active until a user logs on interactively,
GetSetting requires that a user be logged on.
Registry settings that are to be accessed from a non-interactive process (such as Mtx.exe) should be stored under either the
HKEY_LOCAL_MACHINE\Software\ or the HKEY_USER\DEFAULT\Software registry keys.
GetSetting requires Read Registry Permission.
Example
This example first uses the SaveSetting function to make entries in the Windows registry for the application specified as
AppName, and then uses the GetSetting function to display one of the settings. Because the Default argument is specified,
some value is guaranteed to be returned. Notice that Section names cannot be retrieved with GetSetting. Finally, the
DeleteSetting function removes all the application's entries.
VB
' Place some settings in the registry.
SaveSetting("MyApp", "Startup", "Top", "75")
SaveSetting("MyApp", "Startup", "Left", "50")
Console.WriteLine(GetSetting("MyApp", "Startup", "Left", "25"))
DeleteSetting("MyApp")
Smart Device Developer Notes
This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DeleteSetting Function
GetAllSettings Function
SaveSetting Function
ArgumentException Class
RegistryPermission Class
Concepts
Common Registry Tasks
Visual Basic Language Reference
H-L Functions
The following table contains a listing of the Visual Basic run-time member functions.
LSet LTrim
The math function Log that was available as a Visual Basic run-time member function in version 6.0 and earlier has been
replaced by a method (Log) in the Math class of the .NET Framework class library. For more information, see
Math Functions (Visual Basic).
Smart Device Developer Notes
The following are not supported in smart device applications: Input, InputString, Kill, LineInput, Loc, Lock, and LOF.
See Also
Reference
A-C Functions
D-G Functions
M-R Functions
S-Z Functions
Other Resources
Visual Basic Reference
Visual Basic Language Reference
Parameters
Number
Required. Any valid numeric expression or String expression.
Exceptions
Exception type Error number Condition
ArgumentNullException 5 Number is not specified.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If Number is not already a whole number, it is rounded to the nearest whole number before being evaluated.
If Number is Hex returns
Empty Zero (0)
You can represent hexadecimal numbers directly by preceding numbers in the proper range with &H. For example, &H10
represents decimal 16 in hexadecimal notation.
Example
This example uses the Hex function to return the hexadecimal value of a number.
VB
Dim TestHex As String
' Returns 5.
TestHex = Hex(5)
' Returns A.
TestHex = Hex(10)
' Returns 1CB.
TestHex = Hex(459)
Requirements
Namespace: Microsoft.VisualBasic
Module: Conversion
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Convert Hexadecimal Strings to Numbers
Reference
Oct Function
Type Conversion Functions
ArgumentNullException
Visual Basic Language Reference
Parameters
TimeValue
Required. Date value from which you want to extract the hour.
Remarks
You can also obtain the hour of the day by calling DatePart and specifying DateInterval.Hour for the Interval argument.
Example
This example uses the Hour function to obtain the hour from a specified time. In the development environment, the time literal
is displayed in short time format using the locale settings of your code.
VB
Dim someTime As Date
Dim someHour As Integer
someTime = #4:35:17 PM#
someHour = Hour(someTime)
' someHour now contains 16.
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Minute Function
Now Property
Second Function (Visual Basic)
TimeOfDay Property
DatePart Function (Visual Basic)
System
DateTime
ArgumentException
ArgumentOutOfRangeException
Visual Basic Language Reference
IIf Function
Returns one of two objects, depending on the evaluation of an expression.
Parameters
Expression
Required. Boolean. The expression you want to evaluate.
TruePart
Required. Object. Returned if Expression evaluates to True.
FalsePart
Required. Object. Returned if Expression evaluates to False.
Remarks
The IIf function provides a counterpart for the ternary Conditional Operator: ? : in Visual C++.
Example
This example uses the IIf function to evaluate the testMe parameter of the checkIt procedure and returns the word "Large" if
the amount is greater than 1000; otherwise, it returns the word "Small".
VB
Function checkIt(ByVal testMe As Integer) As String
Return CStr(IIf(testMe > 1000, "Large", "Small"))
End Function
Note that if Option Strict is On, you must use the CStr keyword to explicitly convert the return from Object to String.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Option Strict Statement
Type Conversion Functions
Choose Function
If...Then...Else Statement (Visual Basic)
Select...Case Statement (Visual Basic)
Switch Function
Visual Basic Language Reference
Input Function
Reads data from an open sequential file and assigns the data to variables.
Parameters
FileNumber
Required. Any valid file number.
Value
Required. Variable that is assigned the values read from the file—cannot be an array or object variable.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Input function is provided for backward compatibility and may have an impact on performance. For non-legacy
applications, the My.Computer.FileSystem object provides better performance. For more information, see
File Access with Visual Basic.
Data read with Input is usually written to a file with Write. Use this function only with files opened in Input or Binary mode.
Security Note
When reading from files, do not make decisions about the contents of the file based on the file name extension. For example,
a file named Form1.vb may not be a Visual Basic 2005 source file.
When read, standard string or numeric data is assigned to variables without modification. The following table illustrates how
other input data is treated.
Data Value assigned to variable
Delimiting comma or blank line Empty
#NULL# DBNull
If you reach the end of the file while you are inputting a data item, the input is terminated and an error occurs.
Note
The Input function is not localized. For example, in the German version, if you input 3,14159, it returns only 3, since the com
ma is treated as a variable separator rather than a decimal point.
Security Note
Reading from a file with the Input function requires Read access from the FileIOPermissionAccess enumeration. For more
information, see FileIOPermissionAccess Enumeration.
Example
This example uses the Input function to read data from a file into two variables. This example assumes that TestFile is a file
with a few lines of data written to it using the Write function, each line containing a string in quotations and a number
separated by a comma, for example: ("Hello", 234).
VB
FileOpen(1, "TESTFILE", OpenMode.Output)
Write(1, "hello")
Write(1, 14)
FileClose(1)
Dim s As String = "teststring"
Dim i As Integer
FileOpen(1, "TESTFILE", OpenMode.Input)
Input(1, s)
MsgBox(s)
Input(1, i)
MsgBox(i)
FileClose(1)
Parameters
Prompt
Required String expression displayed as the message in the dialog box. The maximum length of Prompt is approximately
1024 characters, depending on the width of the characters used. If Prompt consists of more than one line, you can separate
the lines using a carriage return character (Chr(13)), a line feed character (Chr(10)), or a carriage return/line feed
combination (Chr(13) & Chr(10)) between each line.
Title
Optional. String expression displayed in the title bar of the dialog box. If you omit Title, the application name is placed in the
title bar.
DefaultResponse
Optional. String expression displayed in the text box as the default response if no other input is provided. If you omit
DefaultResponse, the displayed text box is empty.
XPos
Optional. Numeric expression that specifies, in pixels, the distance of the left edge of the dialog box from the left edge of the
screen. If you omit XPos and YPos, the dialog box is centered on the screen.
YPos
Optional. Numeric expression that specifies, in pixels, the distance of the upper edge of the dialog box from the top of the
screen. If you omit XPos and YPos, the dialog box is centered on the screen.
Remarks
If the user clicks Cancel, a zero-length string is returned.
To specify more than the first argument, you must use the InputBox function in an expression. If you omit any positional
arguments, you must retain the corresponding comma delimiter.
Note
The InputBox function requires UIPermission at the SafeTopLevelWindows level, which may affect its execution in partial-tr
ust situations. For more information, see Requesting Permissions and UIPermission Class.
Example
This example shows various ways to use the InputBox function to prompt the user to enter a value. If the x and y positions are
omitted, the dialog box is automatically centered for the respective axes. The variable MyValue contains the value entered by
the user if the user clicks OK or presses the ENTER key.
VB
Dim message, title, defaultValue As String
Dim myValue As Object
' Set prompt.
message = "Enter a value between 1 and 3"
' Set title.
title = "InputBox Demo"
defaultValue = "1" ' Set default value.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
MsgBox Function (Visual Basic)
Chr, ChrW Functions
Visual Basic Language Reference
InputString Function
Returns String value containing characters from a file opened in Input or Binary mode.
The My feature gives you greater productivity and performance in file I/O operations than InputString. For more information,
see My.Computer.FileSystem Object.
InputString(_
ByVal FileNumber As Integer, _
ByVal CharCount As Integer _
) As String
Parameters
FileNumber
Required. Any valid file number.
CharCount
Required. Any valid numeric expression specifying the number of characters to read.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The InputString function is provided for backward compatibility and may have an impact on performance. For non-legacy
applications, the My.Computer.FileSystem object provides better performance. For more information, see
File Access with Visual Basic.
Data read with the InputString function is usually written to a file with Print or FilePut. Use this function only with files
opened in Input or Binary mode.
Unlike the Input function, the InputString function returns all of the characters it reads, including commas, carriage returns,
line feeds, quotation marks, and leading spaces.
With files opened for Binary access, an attempt to read through the file using the InputString function until EOF returns True
generates an error. Use the LOF and Loc functions instead of EOF when reading binary files with InputString, or use FileGet
when using the EOF function.
Security Note
When reading from files, do not make decisions about the contents of the file based on the file name extension. For example,
a file named Form1.vb may not be a Visual Basic source file.
Example
This example uses the InputString function to read one character at a time from a file and print it to the Output window. This
example assumes that MyFile is a text file with a few lines of sample data.
VB
Dim oneChar As String
' Open file.
FileOpen(1, "MYFILE.TXT", OpenMode.Input)
' Loop until end of file.
While Not EOF(1)
' Get one character.
oneChar = (InputString(1, 1))
' Print to the output window.
System.Console.Out.WriteLine(oneChar)
End While
FileClose(1)
Parameters
Start
Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character
position. The start index is 1-based.
String1
Required. String expression being searched.
String2
Required. String expression sought.
Compare
Optional. Specifies the type of string comparison. 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
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"
' 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)
' Returns 0.
TestPos = InStr(1, SearchString, "W")
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
InStrRev Function (Visual Basic)
Option Compare Statement
StrComp Function (Visual Basic)
ArgumentException
Concepts
Programming Element Support Changes Summary
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference
Parameters
StringCheck
Required. String expression being searched.
StringMatch
Required. String expression being searched for.
Start
Optional. Numeric expression setting the one-based starting position for each search, starting from the left side of the string.
If Start is omitted then –1 is used, meaning the search begins at the last character position. Search then proceeds from right
to left.
Compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. If omitted, a binary
comparison is performed. See Settings for values.
Settings
The Compare argument can have the following values.
Constant Description
Binary Performs a binary comparison.
StringMatch is found within StringCheck Position at which the first match is found, starting with the right side of the string.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Note that the syntax for the InStrRev function is not the same as the syntax for the InStr function.
Example
This example demonstrates the use of the InStrRev function.
VB
Dim TestString As String = "the quick brown fox jumps over the lazy dog"
Dim TestNumber As Integer
' Returns 32.
TestNumber = InStrRev(TestString, "the")
' Returns 1.
TestNumber = InStrRev(TestString, "the", 16)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
InStr Function (Visual Basic)
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference
Parameters
Number
Required. A number of type Double or any valid numeric expression. If Number contains Nothing, Nothing is returned.
Exceptions
Exception type Error number Condition
ArgumentNullException 5 Number is not specified.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Both the Int and Fix functions remove the fractional part of Number and return the resulting integer value.
The difference between Int and Fix functions is that if Number is negative, Int returns the first negative integer less than or
equal to Number, whereas Fix returns the first negative integer greater than or equal to Number. For example, Int converts -
8.4 to -9, and Fix converts -8.4 to -8.
Fix(number) is equivalent to Sign(number) * Int(Abs(number)).
Example
This example illustrates how the Int and Fix functions return integer portions of numbers. In the case of a negative number
argument, the Int function returns the first negative integer less than or equal to the number; the Fix function returns the first
negative integer greater than or equal to the number. The following example requires you to specify Option Strict Off
because implicit conversions from type Double to type Integer are not allowed under Option Strict On:
VB
' This code requires Option Strict Off
Dim MyNumber As Integer
MyNumber = Int(99.8) ' Returns 99.
MyNumber = Fix(99.8) ' Returns 99.
You can use the CInt function to explicitly convert other data types to type Integer with Option Strict Off. However, CInt
rounds to the nearest integer instead of truncating the fractional part of numbers. For example:
VB
MyNumber = CInt(99.8) ' Returns 100.
MyNumber = CInt(-99.8) ' Returns -100.
MyNumber = CInt(-99.2) ' Returns -99.
You can use the CInt function on the result of a call to Fix or Int to perform explicit conversion to integer without rounding.
For example:
VB
MyNumber = CInt(Fix(99.8)) ' Returns 99.
MyNumber = CInt(Int(99.8)) ' Returns 99.
IPmt Function
Returns a Double specifying the interest payment for a given period of an annuity based on periodic, fixed payments and a
fixed interest rate.
Function IPmt( _
ByVal Rate As Double, _
ByVal Per As Double, _
ByVal NPer As Double, _
ByVal PV As Double, _
Optional ByVal FV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod _
) As Double
Parameters
Rate
Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of
10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
Per
Required. Double specifying payment period in the range 1 through NPer.
NPer
Required. Double specifying total number of payment periods in the annuity. For example, if you make monthly payments
on a four-year car loan, your loan has a total of 4 x 12 (or 48) payment periods.
PV
Required. Double specifying present value, or value today, of a series of future payments or receipts. For example, when you
borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
FV
Optional. Double specifying future value or cash balance you want after you've made the final payment. For example, the
future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18
years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are due at
the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Exceptions
Exception type Error number Condition
ArgumentException 5 Per <= 0 or Per > NPer
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
An annuity is a series of fixed cash payments made over time. An annuity can be a loan (such as a home mortgage) or an
investment (such as a monthly savings plan).
The Rate and NPer arguments must be calculated using payment periods expressed in the same units. For example, if Rate is
calculated using months, NPer must also be calculated using months.
For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as
dividend checks) is represented by positive numbers.
Example
This example uses the IPmt function to calculate how much of a payment is interest when all the payments are of equal value.
Given are the interest percentage rate per period (APR / 12), the payment period for which the interest portion is desired
(Period), the total number of payments (TotPmts), the present value or principal of the loan (PVal), the future value of the loan
(FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).
VB
Sub TestIPMT()
Dim APR, PVal, Period, IntPmt, TotInt, TotPmts As Double
Dim PayType As DueDate
Dim Response As MsgBoxResult
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
ArgumentException
Visual Basic Language Reference
IRR Function
Returns a Double specifying the internal rate of return for a series of periodic cash flows (payments and receipts).
Function IRR( _
ByRef ValueArray() As Double, _
Optional ByVal Guess As Double = 0.1 _
) As Double
Parameters
ValueArray
Required. Array of Double specifying cash flow values. The array must contain at least one negative value (a payment) and
one positive value (a receipt).
Guess
Optional. Object specifying value you estimate will be returned by IRR. If omitted, Guess is 0.1 (10 percent).
Exceptions
Exception type Error number Condition
ArgumentException 5 Array argument values are invalid or Guess <= -1.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The internal rate of return is the interest rate received for an investment consisting of payments and receipts that occur at
regular intervals.
The IRR function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter
your payment and receipt values in the correct sequence. The cash flow for each period does not need to be fixed, as it is for an
annuity.
IRR is calculated by iteration. Starting with the value of Guess, IRR cycles through the calculation until the result is accurate to
within 0.00001 percent. If IRR cannot find a result after 20 tries, it fails.
Example
In this example, the IRR function returns the internal rate of return for a series of five cash flows contained in the array
Values(). The first array element is a negative cash flow representing business start-up costs. The remaining four cash flows
represent positive cash flows for the subsequent four years. Guess is the estimated internal rate of return.
VB
' Define money format.
Dim MoneyFmt As String = "###,##0.00"
' Define percentage format.
Dim PercentFmt As String = "#0.00"
Dim values(4) As Double
' Business start-up costs.
values(0) = -70000
' Positive cash flows reflecting income for four successive years.
values(1) = 22000
values(2) = 25000
values(3) = 28000
values(4) = 31000
' Use the IRR function to calculate the rate of return.
' Guess starts at 10 percent.
Dim Guess As Double = 0.1
' Calculate internal rate.
Dim CalcRetRate As Double = IRR(values, Guess) * 100
' Display internal return rate.
MsgBox("The internal rate of return for these cash flows is " & _
Format(CalcRetRate, CStr(PercentFmt)) & " percent.")
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
NPV Function
MIRR Function
Financial Summary
ArgumentException
Visual Basic Language Reference
Parameters
VarName
Required. Object variable.
Remarks
IsArray returns True if the variable points to an array; otherwise, it returns False. IsArray is especially useful with objects that
might contain arrays.
Example
This example uses the IsArray function to check if several variables refer to an array.
VB
Dim firstArray(4), secondArray(3) As Integer
Dim thisString As String = "Test"
Dim arrayCheck As Boolean
arrayCheck = IsArray(firstArray)
arrayCheck = IsArray(secondArray)
arrayCheck = IsArray(thisString)
' The first two calls to IsArray return True; the third returns False.
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Declare an Array Variable
Reference
IsDate Function (Visual Basic)
IsDBNull Function
IsError Function
IsNothing Function
IsNumeric Function (Visual Basic)
IsReference Function
Object Data Type
TypeName Function (Visual Basic)
Visual Basic Language Reference
Parameters
Expression
Required. Object expression.
Remarks
IsDate returns True if Expression is of the Date Data Type or can be converted to Date; otherwise, it returns False.
The Date data type holds both a date value and a time value. IsDate returns True if Expression represents a valid date, a valid
time, or a valid date and time.
Example
The following example uses the IsDate function to determine if several variables represent valid Date values.
VB
Dim firstDate, secondDate As Date
Dim timeOnly, dateAndTime, noDate As String
Dim dateCheck As Boolean
firstDate = CDate("February 12, 1969")
secondDate = #2/12/1969#
timeOnly = "3:45 PM"
dateAndTime = "March 15, 1981 10:22 AM"
noDate = "Hello"
dateCheck = IsDate(firstDate)
dateCheck = IsDate(secondDate)
dateCheck = IsDate(timeOnly)
dateCheck = IsDate(dateAndTime)
dateCheck = IsDate(noDate)
In the preceding example, IsDate returns True for the first four calls and False for the last call.
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IsArray Function (Visual Basic)
IsDBNull Function
IsError Function
IsNothing Function
IsNumeric Function (Visual Basic)
IsReference Function
Object Data Type
Date Data Type (Visual Basic)
TypeName Function (Visual Basic)
Visual Basic Language Reference
IsDBNull Function
Returns a Boolean value indicating whether an expression evaluates to the System.DBNull class.
Parameters
Expression
Required. Object expression.
Remarks
IsDBNull returns True if the data type of Expression evaluates to the DBNull type; otherwise, IsDBNull returns False.
The System.DBNull value indicates that the Object represents missing or nonexistent data. DBNull is not the same as
Nothing, which indicates that a variable has not yet been initialized. DBNull is also not the same as a zero-length string (""),
which is sometimes referred to as a null string.
Example
This example uses the IsDBNull function to determine if a variable evaluates to DBNull.
VB
Dim testVar As Object
Dim nullCheck As Boolean
nullCheck = IsDBNull(testVar)
testVar = ""
nullCheck = IsDBNull(testVar)
testVar = System.DBNull.Value
nullCheck = IsDBNull(testVar)
' The first two calls to IsDBNull return False; the third returns True.
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IsArray Function (Visual Basic)
IsDate Function (Visual Basic)
IsError Function
IsNothing Function
IsNumeric Function (Visual Basic)
IsReference Function
Object Data Type
TypeName Function (Visual Basic)
DBNull
Visual Basic Language Reference
IsError Function
Returns a Boolean value indicating whether an expression is an exception type.
Parameters
Expression
Required. Object expression.
Remarks
IsError returns True if the expression represents an Object variable that derives from the Exception class in the System
namespace.
An exception that derives from System.Exception can be caught with the Try...Catch...Finally statements.
Example
The following example uses the IsError function to check if an expression represents a system exception.
VB
Sub demonstrateIsError(ByVal firstArg As Integer)
Dim returnVal As New Object
Dim badArg As String = "Bad argument value"
Dim errorCheck As Boolean
If firstArg > 10000 Then
returnVal = New System.ArgumentOutOfRangeException(badArg)
End If
errorCheck = IsError(returnVal)
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IsArray Function (Visual Basic)
IsDate Function (Visual Basic)
IsDBNull Function
IsNothing Function
IsNumeric Function (Visual Basic)
IsReference Function
Object Data Type
TypeName Function (Visual Basic)
Visual Basic Language Reference
IsNothing Function
Returns a Boolean value indicating whether an expression has no object assigned to it.
Parameters
Expression
Required. Object expression.
Remarks
IsNothing returns True if the expression represents an object variable that currently has no object assigned to it; otherwise, it
returns False.
IsNothing is intended to work on reference types. A value type cannot hold a value of Nothing and reverts to its default value
if you assign Nothing to it. If you supply a value type in Expression, IsNothing always returns False.
Example
The following example uses the IsNothing function to determine if an object variable is associated with any object instance.
VB
Dim testVar As Object
' No instance has been assigned to variable testVar yet.
Dim testCheck As Boolean
' The following call returns True.
testCheck = IsNothing(testVar)
' Assign a string instance to variable testVar.
testVar = "ABCDEF"
' The following call returns False.
testCheck = IsNothing(testVar)
' Disassociate variable testVar from any instance.
testVar = Nothing
' The following call returns True.
testCheck = IsNothing(testVar)
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IsArray Function (Visual Basic)
IsDate Function (Visual Basic)
IsDBNull Function
IsError Function
IsNumeric Function (Visual Basic)
IsReference Function
Object Data Type
TypeName Function (Visual Basic)
Concepts
Value Types and Reference Types
Visual Basic Language Reference
Parameters
Expression
Required. Object expression.
Remarks
IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, SByte, Short,
Single, UInteger, ULong, or UShort, or an Object that contains one of those numeric types. It also returns True if Expression
is a Char or String that can be successfully converted to a number.
IsNumeric returns False if Expression is of data type Date or of data type Object and it does not contain a numeric type.
IsNumeric returns False if Expression is a Char or String that cannot be converted to a number.
Example
The following example uses the IsNumeric function to determine if the contents of a variable can be evaluated as a number.
VB
Dim testVar As Object
Dim numericCheck As Boolean
testVar = "53"
' The following call to IsNumeric returns True.
numericCheck = IsNumeric(testVar)
testVar = "459.95"
' The following call to IsNumeric returns True.
numericCheck = IsNumeric(testVar)
testVar = "45 Help"
' The following call to IsNumeric returns False.
numericCheck = IsNumeric(testVar)
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IsArray Function (Visual Basic)
IsDate Function (Visual Basic)
IsDBNull Function
IsError Function
IsNothing Function
IsReference Function
Object Data Type
TypeName Function (Visual Basic)
Visual Basic Language Reference
IsReference Function
Returns a Boolean value indicating whether an expression evaluates to a reference type.
Parameters
Expression
Required. Object expression.
Remarks
IsReference returns True if Expression represents a reference type, such as a class instance, a String type, or an array of any
type; otherwise, it returns False.
A reference type contains a pointer to data stored elsewhere in memory. A value type contains its own data.
Example
This example uses the IsReference function to check if several variables refer to reference types.
VB
Dim testArray(3) As Boolean
Dim testString As String = "Test string"
Dim testObject As Object = New Object()
Dim testNumber As Integer = 12
testArray(0) = IsReference(testArray)
testArray(1) = IsReference(testString)
testArray(2) = IsReference(testObject)
testArray(3) = IsReference(testNumber)
In the preceding example, the first three calls to IsReference return True. The last call returns False, because Integer is a value
type, not a reference type.
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IsArray Function (Visual Basic)
IsDate Function (Visual Basic)
IsDBNull Function
IsError Function
IsNothing Function
IsNumeric Function (Visual Basic)
Object Data Type
TypeName Function (Visual Basic)
Concepts
Value Types and Reference Types
Visual Basic Language Reference
Function Join(
ByVal SourceArray() As { Object | String },
Optional ByVal Delimiter As String = " "
) As String
Parameters
SourceArray
Required. One-dimensional array containing substrings to be joined.
Delimiter
Optional. Any string, used to separate the substrings in the returned string. If omitted, the space character (" ") is used. If
Delimiter is a zero-length string ("") or Nothing, all items in the list are concatenated with no delimiters.
Exceptions
Exception type Error number Condition
ArgumentException 5 SourceArray is not one dimensional.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
There is a parity between the Join and Split functions. The Join function takes an array of strings and joins them using a
delimiter string, to return a single string. The Split function takes a string and separates it at the delimiter, to return an array of
strings. However, a key difference is that Join can concatenate strings with any delimiter string, Split can only separate strings
using a single character delimiter.
Example
The following example demonstrates how to use the Join function to create a list from several strings.
VB
Dim TestItem() As String = {"Pickle", "Pineapple", "Papaya"}
' Returns "Pickle, Pineapple, Papaya"
Dim TestShoppingList As String = Join(TestItem, ", ")
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Split Function (Visual Basic)
ArgumentException
Visual Basic Language Reference
Kill Function
Deletes files from a disk.
The My feature gives you greater productivity and performance in file I/O operations than Kill. For more information, see
My.Computer.FileSystem Object.
Parameters
PathName
Required. String expression that specifies one or more file names to be deleted. PathName can include the directory or
folder, and the drive.
Exceptions
Exception type Error number Condition
IOException 55 Target file(s) open.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Kill supports the use of multiple-character (*) and single-character (?) wildcards to specify multiple files.
Security Note In order to execute, the Kill function requires Read and PathDiscovery flags of FileIOPermission to be
granted to the executing code. For more information, see SecurityException, and Code Access Permissions
Example
This example uses the Kill function to delete a file from a disk.
VB
' Assume TESTFILE is a file containing some data.
Kill("TestFile") ' Delete file.
Parameters
Array
Required. Array of any data type. The array in which you want to find the lowest possible subscript of a dimension.
Rank
Optional. Integer. The dimension for which the lowest possible subscript is to be returned. Use 1 for the first dimension, 2
for the second, and so on. If Rank is omitted, 1 is assumed.
Return Value
Integer. The lowest value the subscript for the specified dimension can contain. LBound always returns 0 as long as Array has
been initialized, even if it has no elements, for example if it is a zero-length string. If Array is Nothing, LBound throws an
ArgumentNullException.
Exceptions
Exception type Error number Condition
ArgumentNullException 9 Array is Nothing.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Since array subscripts start at 0, the lowest available subscript for every dimension is always 0.
For an array with the following dimensions, LBound returns the values in the following table:
LBound(a, 2) 0
LBound(a, 3) 0
Example
The following example uses the LBound function to determine the lowest available subscript for the indicated dimension of an
array.
VB
Dim lowest, bigArray(10, 15, 20), littleArray(6) As Integer
lowest = LBound(bigArray, 1)
lowest = LBound(bigArray, 3)
lowest = LBound(littleArray)
' All three calls to LBound return 0.
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
UBound Function (Visual Basic)
Dim Statement (Visual Basic)
ReDim Statement (Visual Basic)
ArgumentException
RankException
Visual Basic Language Reference
Parameters
Value
Required. Any valid String or Char expression.
Remarks
Only uppercase letters are converted to lowercase; all lowercase letters and nonletter characters remain unchanged.
This function uses the application's culture information when manipulating the string so that the case changes are appropriate
for the locale in which the application is being used.
Security Note
If your application makes security decisions based on the result of a comparison or case-change operation, then the operatio
n should use the System.String.Compare(System.String,System.String,System.StringComparison) method, and pass Ordinal
or OrdinalIgnoreCase for the comparisonType argument. For more information, see
How Culture Affects Strings in Visual Basic.
Example
This example uses the LCase function to return a lowercase version of a string.
VB
' String to convert.
Dim UpperCase As String = "Hello World 1234"
' Returns "hello world 1234".
Dim LowerCase As String = LCase(UpperCase)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
UCase Function (Visual Basic)
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference
Parameters
str
Required. String expression from which the leftmost characters are returned.
Length
Required. Integer expression. 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.
Exceptions
Exception type Error number Condition
ArgumentException 5 Length < 0.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
To determine the number of characters in str, use the Len function. If used in a Windows Forms application, or any other class
that has a Left property, you must fully qualify the function with Microsoft.VisualBasic.Left.
Note
The LeftB function in previous versions of Visual Basic returns a string in bytes rather than characters. It is used primarily for
converting strings in double-byte character set (DBCS) applications. All current Visual Basic strings are in Unicode, and LeftB
is no longer supported.
Example
This example demonstrates the use of the Left function to return a substring of a given String. In a class that has a Left
property, it may be necessary to fully qualify the Left function.
VB
Dim TestString As String = "Hello World!"
' Returns "Hello".
Dim subString As String = Microsoft.VisualBasic.Left(TestString, 5)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Right Function (Visual Basic)
Len Function (Visual Basic)
Mid Function (Visual Basic)
ArgumentException
Concepts
Programming Element Support Changes Summary
Visual Basic Language Reference
Parameters
Expression
Any valid String expression or variable name. If Expression is of type Object, the Len function returns the size as it will be
written to the file by the FilePut function.
Remarks
With user-defined types and Object variables, the Len function returns the size as it will be written to the file by the FilePut
function. If an Object contains a String, it will return the length of the string. If an Object contains any other type, it will return
the size of the object as it will be written to the file by the FilePut function.
The VBFixedString attribute can be applied to string fields in objects to indicate the size of the string, in bytes, when written to
disk. The Len function uses the VBFixedString attribute, if available, when determining the size of Object variables.
Note
The Len function may not be able to determine the actual number of storage bytes required when used with variable-length
strings in user-defined data types.
Note
The LenB function in earlier versions of Visual Basic returns the number of bytes in a string rather than characters. It is used
primarily for converting strings in double-byte character set (DBCS) applications. All current Visual Basic strings are in Unico
de, and LenB is no longer supported.
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)
LineInput Function
Reads a single line from an open sequential file and assigns it to a String variable.
Parameters
FileNumber
Required. Any valid file number.
Exceptions
Exception type Error number Condition
EndOfStreamException 62 End of file reached.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The LineInput function is provided for backward compatibility and may have an impact on performance. For non-legacy
applications, the My.Computer.FileSystem object provides better performance. For more information, see
File Access with Visual Basic.
Data read with LineInput is usually written to a file with Print.
Security Note
When reading from files, do not make decisions about the contents of a file based on the file name extension. For example, a
file named Form1.vb may not be a Visual Basic source file.
The LineInput function reads from a file one character at a time until it encounters a carriage return (Chr(13)) or carriage
return/line feed (Chr(13) + Chr(10)) sequence. Carriage return/line feed sequences are skipped rather than appended to the
character string.
Security Note
Reading from a file with the LineInput function requires Read access from the FileIOPermissionAccess enumeration.
Example
This example uses the LineInput function to read a line from a sequential file and assign it to a variable. This example assumes
that TestFile is a text file with a few lines of sample data.
VB
Dim TextLine As String
' Open file.
FileOpen(1, "TESTFILE", OpenMode.Input)
' Loop until end of file.
While Not EOF(1)
' Read line into variable.
TextLine = LineInput(1)
' Print to the console.
WriteLine(1, TextLine)
End While
FileClose(1)
Smart Device Developer Notes
This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Write Text to Files with a StreamWriter in Visual Basic
How to: Write Text to Files in Visual Basic
Reference
Chr, ChrW Functions
Input Function
Other Resources
File Access with Visual Basic
Visual Basic Language Reference
Loc Function
Returns a Long value specifying the current read/write position within an open file.
Parameters
FileNumber
Required. Any valid Integer file number.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Loc function is zero-based; using it to get the first byte in a file will return 0.
The Loc function is provided for backward compatibility and may have an impact on performance. For non-legacy applications,
the My.Computer.FileSystem object provides better performance. For more information, see File Access with Visual Basic.
The following describes the return value for each file access mode:
Mode Return value
Random Number of the last record read from or written to the file.
Sequenti Current byte position in the file divided by 128. However, information returned by Loc for sequential files is neither
al used nor required.
VB
Dim location As Long
Dim oneChar As Char
FileOpen(1, "C:\TESTFILE.TXT", OpenMode.Binary)
While location < LOF(1)
Input(1, oneChar)
location = Loc(1)
WriteLine(1, location & ControlChars.CrLf)
End While
FileClose(1)
Parameters
FileNumber
Required. Any valid file number.
Record
Optional. Number of the only record or byte to lock or unlock
FromRecord
Optional. Number of the first record or byte to lock or unlock.
ToRecord
Optional. Number of the last record or byte to lock or unlock.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Lock and Unlock functions are used in environments where several processes might need access to the same file.
Lock and Unlock functions are always used in pairs. The arguments to Lock and Unlock must match exactly.
If Record, or FromRecord and ToRecord are not supplied, the lock will be for the entire file. If Record alone is specified the
single record will be locked/unlocked.
If the file has been opened for sequential input or output, Lock and Unlock affect the entire file, regardless of the range
specified by FromRecord and ToRecord.
Example
This example illustrates the use of the Lock and Unlock functions. This example assumes that People.txt is a file containing
records of the structure Person.
VB
Structure Person
Dim Name As String
Dim ID As Integer
End Structure
Sub PutInLockedFile(ByVal index As Integer, ByVal onePerson As Person)
Try
FileOpen(1, "c:\people.txt", OpenMode.Binary)
Lock(1)
FilePut(index, onePerson)
Unlock(1)
FileClose(1)
Catch
' Error recovery code here.
End Try
End Sub
LOF Function
Returns a Long representing the size, in bytes, of a file opened using the FileOpen function.
The My feature gives you greater productivity and performance in file I/O operations than LOF. For more information, see
My.Computer.FileSystem Object.
Parameters
FileNumber
Required. An Integer containing a valid file number.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Use the FileLen function to obtain the length of a file that is not open.
Example
This example uses the LOF function to determine the size of an open file. This example assumes that TestFile is a text file
containing sample data.
VB
Dim length As Long
FileOpen(1, "C:\TESTFILE.TXT", OpenMode.Input) ' Open file.
length = LOF(1) ' Get length of file.
MsgBox(length)
FileClose(1) ' Close file.
LSet Function
Returns a left-aligned string containing the specified string adjusted to the specified length.
Parameters
Source
Required. String expression. String variable to be adjusted.
Length
Required. Integer expression. Length of returned string.
Remarks
If Source is longer than Length, LSet returns only the rightmost characters, up to the length of Length. If Source is shorter than
Length, LSet adds spaces to the right end of the returned string to produce the appropriate length.
Example
This example demonstrates the use of the LSet function.
VB
Dim TestString As String = "Left"
Dim lString As String
' Returns "Left "
lString = LSet(TestString, 10)
' Returns "Le"
lString = LSet(TestString, 2)
' Returns "Left"
lString = LSet(TestString, 4)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Data Type Summary (Visual Basic)
RSet Function
Concepts
Efficient Use of Data Types
Visual Basic Language Reference
M-R Functions
The following table contains a listing of the Visual Basic run-time member functions.
The math function Round that was available as a Visual Basic run-time member function in version 6.0 and earlier has been
replaced by a method (Round) in the Math class of the .NET Framework class library. For more information, see
Math Functions (Visual Basic).
Smart Device Developer Notes
The following are not supported in smart device applications: MkDir, Print, PrintLine, Rename, Reset, and RmDir.
See Also
Reference
A-C Functions
D-G Functions
H-L Functions
S-Z Functions
Other Resources
Visual Basic Reference
Visual Basic Language Reference
Parameters
str
Required. String expression from which characters are returned.
Start
Required. Integer expression. Starting position of the characters to return. If Start is greater than the number of characters in
str, the Mid function returns a zero-length string (""). Start is one based.
Length
Optional. Integer expression. Number of characters to return. If omitted or if there are fewer than Length characters in the
text (including the character at position Start), all characters from the start position to the end of the string are returned.
Exceptions
Exception type Error number Condition
ArgumentException 5 Start <= 0 or Length < 0.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
To determine the number of characters in str, use the Len function.
Visual Basic has a Mid function and a Mid statement. These elements both operate on a specified number of characters in a
string, but the Mid function returns the characters while the Mid statement replaces the characters. For more information, see
Mid Statement.
Note
The MidB function in previous versions of Visual Basic returns a string in bytes rather than characters. It is used primarily for
converting strings in double-byte character set (DBCS) applications. All Visual Basic strings are in Unicode, and MidB is no lo
nger supported.
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)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Left Function (Visual Basic)
Len Function (Visual Basic)
Trim, LTrim, and RTrim Functions
Mid Statement
Right Function (Visual Basic)
ArgumentException
Concepts
Programming Element Support Changes Summary
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference
Minute Function
Returns an Integer value from 0 through 59 representing the minute of the hour.
Parameters
TimeValue
Required. Date value from which you want to extract the minute.
Remarks
You can also obtain the minute of the hour by calling DatePart and specifying DateInterval.Minute for the Interval
argument.
Example
This example uses the Minute function to obtain the minute of the hour from a specified time. In the development
environment, the time literal is displayed in short time format using the locale settings of your code.
VB
Dim thisTime As Date
Dim thisMinute As Integer
thisTime = #4:35:17 PM#
thisMinute = Minute(thisTime)
' thisMinute now contains 35.
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Hour Function (Visual Basic)
Now Property
Second Function (Visual Basic)
TimeOfDay Property
DatePart Function (Visual Basic)
System
DateTime
ArgumentException
ArgumentOutOfRangeException
Visual Basic Language Reference
MIRR Function
Returns a Double specifying the modified internal rate of return for a series of periodic cash flows (payments and receipts).
Function MIRR( _
ByRef ValueArray() As Double, _
ByVal FinanceRate As Double, _
ByVal ReinvestRate As Double _
) As Double
Parameters
ValueArray
Required. Array of Double specifying cash-flow values. The array must contain at least one negative value (a payment) and
one positive value (a receipt).
FinanceRate
Required. Double specifying interest rate paid as the cost of financing.
ReinvestRate
Required. Double specifying interest rate received on gains from cash reinvestment.
Exceptions
Exception type Error number Condition
ArgumentException 5 Rank of ValueArray does not equal 1, FinanceRate = -1, or ReinvestRate = -1
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The modified internal rate of return is the internal rate of return when payments and receipts are financed at different rates.
The MIRR function takes into account both the cost of the investment (FinanceRate) and the interest rate received on
reinvestment of cash (ReinvestRate).
The FinanceRate and ReinvestRatearguments are percentages expressed as decimal values. For example, 12 percent is
expressed as 0.12.
The MIRR function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter
your payment and receipt values in the correct sequence.
Example
This example uses the MIRR function to return the modified internal rate of return for a series of cash flows contained in the
array Values(). LoanAPR represents the financing interest, and InvAPR represents the interest rate received on reinvestment.
VB
' Define money format.
Dim MoneyFmt As String = "###,##0.00"
' Define percentage format.
Dim PercentFmt As String = "#0.00"
Dim values(4) As Double
' Business start-up costs.
values(0) = -70000
' Positive cash flows reflecting income for four successive years.
values(1) = 22000
values(2) = 25000
values(3) = 28000
values(4) = 31000
' Use the MIRR function to calculate the internal return rate.
' Set the loan rate.
Dim LoanAPR As Double = 0.1
' Set the reinvestment rate.
Dim InvAPR As Double = 0.12
' Calculate internal rate.
Dim RetRate As Double = MIRR(values, LoanAPR, InvAPR)
' Display internal return rate.
MsgBox("The modified internal rate of return for these cash flows is " & _
Format(Math.Abs(RetRate) * 100, CStr(PercentFmt)) & "%.")
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IRR Function
NPV Function
Financial Summary
ArgumentException
DivideByZeroException
Visual Basic Language Reference
MkDir Function
Creates a new directory.
The My feature gives you greater productivity and performance in file I/O operations than MkDir. For more information, see
My.Computer.FileSystem.CreateDirectory Method.
Parameters
Path
Required. String expression that identifies the directory to be created. The Path may include the drive. If no drive is specified,
MkDir creates the new directory on the current drive.
Exceptions
Exception type Error number Condition
ArgumentException 52 Path is not specified or is empty.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Security Note
Both read and write file I/O permissions are necessary to create a directory or folder. For more information, see
FileIOPermission and Code Access Permissions.
Remarks
This function creates any new directories specified in Path, unless they already exist or if some part of Path is invalid. The Path
parameter must specify a directory path, not a file path.
Example
This example uses the MkDir function to create a directory. If the drive is not specified, the new directory is created on the
current drive.
VB
' Make new directory.
MkDir("C:\TESTDIR")
Parameters
DateValue
Required. Date value from which you want to extract the month.
Remarks
You can also obtain the month of the year by calling DatePart and specifying DateInterval.Month for the Interval argument.
Example
This example uses the Month function to obtain the month from a specified date. In the development environment, the date
literal is displayed in short date format using the locale settings of your code.
VB
Dim thisDate As Date
Dim thisMonth As Integer
thisDate = #2/12/1969#
thisMonth = Month(thisDate)
' thisMonth now contains 2.
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Now Property
Weekday Function (Visual Basic)
Year Function (Visual Basic)
DatePart Function (Visual Basic)
System
DateTime
ArgumentException
ArgumentOutOfRangeException
Visual Basic Language Reference
Parameters
Month
Required. Integer. The numeric designation of the month, from 1 through 13; 1 indicates January and 12 indicates
December. You can use the value 13 with a 13-month calendar. If your system is using a 12-month calendar and Month is
13, MonthName returns an empty string.
Abbreviate
Optional. Boolean value that indicates if the month name is to be abbreviated. If omitted, the default is False, which means
the month name is not abbreviated.
Exceptions
Exception type Error number Condition
ArgumentException 5 Month is less than 1 or greater than 13.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The string returned by MonthName depends not only on the input arguments, but also on the Regional Options settings
specified in the Windows Control Panel.
Note
MonthName uses the current calendar setting from the CurrentCulture property of the CultureInfo class in the
System.Globalization namespace. The default CurrentCulture values are determined by Control Panel settings.
Example
This example uses the MonthName function to determine the name of the month, by the integer given. The Boolean value will
determine whether the full name (False) or the abbreviated name (True) will be displayed.
VB
Dim thisMonth As Integer
Dim name As String
thisMonth = 4
' Set Abbreviate to True to return an abbreviated name.
name = MonthName(thisMonth, True)
' name now contains "Apr".
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
WeekdayName Function (Visual Basic)
System
System.Globalization
DateTime
ArgumentException
CultureInfo
Visual Basic Language Reference
Parameters
Prompt
Required. String expression displayed as the message in the dialog box. The maximum length of Prompt is approximately
1024 characters, depending on the width of the characters used. If Prompt consists of more than one line, you can separate
the lines using a carriage return character (Chr(13)), a line feed character (Chr(10)), or a carriage return/linefeed character
combination (Chr(13) & Chr(10)) between each line.
Buttons
Optional. Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to
use, the identity of the default button, and the modality of the message box. If you omit Buttons, the default value is zero.
Title
Optional. String expression displayed in the title bar of the dialog box. If you omit Title, the application name is placed in the
title bar.
Settings
The MsgBoxStyle enumeration values are listed in the following table.
Member Value Description
OKOnly 0 Displays OK button only.
ApplicationModal 0 Application is modal. The user must respond to the message box before continuing work in the c
urrent application.
SystemModal 4096 System is modal. All applications are suspended until the user responds to the message box.
MsgBoxSetForegro 65536 Specifies the message box window as the foreground window.
und
MsgBoxRtlReading 10485 Specifies text should appear as right-to-left reading on Hebrew and Arabic systems.
76
The first group of values (0–5) describes the number and type of buttons displayed in the dialog box. The second group (16, 32,
48, 64) describes the icon style. The third group (0, 256, 512) determines which button is the default. The fourth group (0,
4096) determines the modality of the message box, and the fifth group specifies whether or not the message box window is
the foreground window, along with the alignment and direction of the text. When adding numbers to create a final value for
the Buttons argument, use only one number from each group.
Return Value
Constant Value
OK 1
Cancel 2
Abort 3
Retry 4
Ignore 5
Yes 6
No 7
Exceptions
Exception type Error numb Condition
er
ArgumentException 5 Prompt is not a String expression, or Title is invalid.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If the dialog box displays a Cancel button, pressing the ESC key has the same effect as clicking Cancel. If the dialog box
contains a Help button, context-sensitive Help is provided for the dialog box. However, no value is returned until one of the
other buttons is clicked.
Note
To specify more than the first argument, you must use the MsgBox function in an expression. If you omit any positional argu
ments, you must retain the corresponding comma delimiter.
Note
The MsgBox function requires UIPermission at the SafeTopLevelWindows level, which may affect its execution in partial-tru
st situations. For more information, see Requesting Permissions and UIPermission.
Example
This example uses the MsgBox function to display a critical-error message in a dialog box with Yes and No buttons. The No
button is specified as the default response. This is done by combining the MsgBox constant values into one numeric
expression. In this case, adding 4 (the Yes/No button combination) and 16 (the Critical Message window) and 256 (the
second button as default button) gives a total of 276. The value returned by the MsgBox function depends on the button
chosen by the user: Yes returns a value of 6; No returns a value of 7.
VB
Dim msg As String
Dim title As String
Dim style As MsgBoxStyle
Dim response As MsgBoxResult
msg = "Do you want to continue?" ' Define message.
style = MsgBoxStyle.DefaultButton2 Or _
MsgBoxStyle.Critical Or MsgBoxStyle.YesNo
title = "MsgBox Demonstration" ' Define title.
' Display message.
response = MsgBox(msg, style, title)
If response = MsgBoxResult.Yes Then ' User chose Yes.
' Perform some action.
Else
' Perform some other action.
End If
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
InputBox Function (Visual Basic)
Visual Basic Language Reference
NPer Function
Returns a Double specifying the number of periods for an annuity based on periodic fixed payments and a fixed interest rate.
Function NPer( _
ByVal Rate As Double, _
ByVal Pmt As Double, _
ByVal PV As Double, _
Optional ByVal FV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod _
) As Double
Parameters
Rate
Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of
10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
Pmt
Required. Double specifying payment to be made each period. Payments usually contain principal and interest that does not
change over the life of the annuity.
PV
Required. Double specifying present value, or value today, of a series of future payments or receipts. For example, when you
borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
FV
Optional. Double specifying future value or cash balance you want after you have made the final payment. For example, the
future value of a loan is $0 because that is its value after the final payment. However, if you want to save $50,000 over 18
years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are due at
the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Exceptions
Exception type Error number Condition
ArgumentException 5 Rate <= -1.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage)
or an investment (such as a monthly savings plan).
For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as
dividend checks) is represented by positive numbers.
Example
This example uses the NPer function to return the number of periods during which payments must be made to pay off a loan
whose value is contained in PVal. Also provided are the interest percentage rate per period (APR / 12), the payment (Payment),
the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the
payment period (PayType).
VB
Sub TestNPer()
Dim TotPmts As Double
Dim PVal, APR, Payment As Double
Dim PayType As DueDate
Dim Response As MsgBoxResult
MsgBox("It will take you " & TotPmts & " months to pay off your loan.")
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
ArgumentException
Visual Basic Language Reference
NPV Function
Returns a Double specifying the net present value of an investment based on a series of periodic cash flows (payments and
receipts) and a discount rate.
Function NPV( _
ByVal Rate As Double, _
ByRef ValueArray() As Double _
) As Double
Parameters
Rate
Required. Double specifying discount rate over the length of the period, expressed as a decimal.
ValueArray
Required. Array of Double specifying cash flow values. The array must contain at least one negative value (a payment) and
one positive value (a receipt).
Exceptions
Exception type Error number Condition
ArgumentException 5 ValueArray is Nothing, rank of ValueArray <> 1, or Rate = -1
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The net present value of an investment is the current value of a future series of payments and receipts.
The NPV function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter
your payment and receipt values in the correct sequence.
The NPV investment begins one period before the date of the first cash flow value and ends with the last cash flow value in the
array.
The net present value calculation is based on future cash flows. If your first cash flow occurs at the beginning of the first period,
the first value must be added to the value returned by NPV and must not be included in the cash flow values of ValueArray.
The NPV function is similar to the PV function (present value) except that the PV function allows cash flows to begin either at
the end or the beginning of a period. Unlike the variable NPV cash flow values, PV cash flows must be fixed throughout the
investment.
Example
This example uses the NPV function to return the net present value for a series of cash flows contained in the array values().
The return value, stored in FixedRetRate, represents the fixed internal rate of return.
VB
' Define money format.
Dim MoneyFmt As String = "###,##0.00"
' Define percentage format.
Dim PercentFmt As String = "#0.00"
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IRR Function
MIRR Function
Financial Summary
ArgumentException
Visual Basic Language Reference
Oct Function
Returns a string representing the octal value of a number.
Parameters
Number
Required. Any valid numeric expression or String expression.
Exceptions
Exception type Error number Condition
ArgumentNullException 5 Number is not specified.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If Number is not already a whole number, it is rounded to the nearest whole number before being evaluated.
If Number is Oct returns
Empty Zero (0)
You can represent octal numbers directly by preceding numbers in the proper range with &O. For example, &O10 is the octal
notation for decimal 8.
Example
This example uses the Oct function to return the octal value of a number.
VB
Dim TestOct As String
' Returns "4".
TestOct = Oct(4)
' Returns "10".
TestOct = Oct(8)
' Returns "713".
TestOct = Oct(459)
Requirements
Namespace: Microsoft.VisualBasic
Module: Conversion
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Conversion Summary
Hex Function (Visual Basic)
Type Conversion Functions
ArgumentNullException
Visual Basic Language Reference
Partition Function
Returns a string representing the calculated range that contains a number.
Parameters
Number
Required. Long. Whole number that you want to locate within one of the calculated ranges.
Start
Required. Long. Whole number that indicates the start of the set of calculated ranges. Start cannot be less than 0.
Stop
Required. Long. Whole number that indicates the end of the set of calculated ranges. Stop cannot be less than or equal to
Start.
Interval
Required. Long. Whole number that indicates the size of each range calculated between Start and Stop. Interval cannot be
less than 1.
Exceptions
Exception type Error number Condition
ArgumentException 5 Start < 0, Stop <= Start, or Interval < 1.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Partition function calculates a set of numeric ranges, each containing the number of values specified by Interval. The first
range begins at Start, and the last range ends at Stop. The Partition function then identifies which range contains Number and
returns a string describing that range. The range is represented in the string as "lowervalue:uppervalue", where the low end of
the range (lowervalue) is separated from the high end (uppervalue) by a colon (:).
If necessary, the Partition function inserts leading spaces before lowervalue and uppervalue so that they both have the same
number of characters as the string representation of the value (Stop + 1). This ensures that if you use the output of the
Partition function with several values of Number, the resulting text will be handled properly during any subsequent sort
operation.
The following table shows some sample strings for ranges calculated using three sets of Start, Stop, and Interval. The "First
range" and "Last range" columns show the lowest and highest ranges possible given the values of Start and Stop. The "Before
first range" and "After last range" columns show the strings returned for values of Number less than Start and greater than
Stop, respectively.
Start Stop Interval Before first range First range Last range After last range
0 99 5 " : -1" " 0: 4" " 95: 99" "100: "
100 1010 20 " : 99" " 100: 119" "1000:1010" "1011: "
In the preceding table, the third line shows the result when Start and Stop define a set of numbers that cannot be evenly
divided by Interval. The last range ends at Stop, making it only 11 numbers long, even though Interval is 20.
If Interval is 1, the range is "Number:Number", regardless of the Start and Stop arguments. For example, if Number is 267, Stop
is 1000, and Interval is 1, Partition returns " 267: 267".
Partition can be useful when constructing database queries. You can create a SELECT query that shows how many orders
occur within various value ranges, for example with invoice values from 1 to 1000, 1001 to 2000, and so on.
Example
The following example sets up a series of ranges for decades from 1950 through 2049. It locates the value of year within the
appropriate range and returns a String value showing the range. If year has a value of 1984, for example, Partition returns
"1980:1989".
VB
Dim year As Long = 1984
' Assume the value of year is provided by data or by user input.
Dim decade As String
decade = Partition(year, 1950, 2049, 10)
MsgBox("Year " & CStr(year) & " is in decade " & decade & ".")
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Other Resources
How Do I (SQL Server)
Visual Basic Language Reference
Pmt Function
Returns a Double specifying the payment for an annuity based on periodic, fixed payments and a fixed interest rate.
Function Pmt( _
ByVal Rate As Double, _
ByVal NPer As Double, _
ByVal PV As Double, _
Optional ByVal FV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod _
) As Double
Parameters
Rate
Required. Double specifies the interest rate per period. For example, if you get a car loan at an annual percentage rate (APR)
of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
NPer
Required. Double specifies the total number of payment periods in the annuity. For example, if you make monthly payments
on a four-year car loan, your loan has a total of 4 × 12 (or 48) payment periods.
PV
Required. Double specifies the present value (or lump sum) that a series of payments to be paid in the future is worth now.
For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car
payments you will make.
FV
Optional. Double specifying future value or cash balance you want after you have made the final payment. For example, the
future value of a loan is $0 because that is its value after the final payment. However, if you want to save $50,000 during 18
years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are due at
the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Exceptions
Exception type Error number Condition
ArgumentException 5 NPer = 0.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
An annuity is a series of fixed cash payments made during a period of time. An annuity can be a loan (such as a home
mortgage) or an investment (such as a monthly savings plan).
The Rate and NPer arguments must be calculated using payment periods expressed in the same units. For example, if Rate is
calculated using months, NPer must also be calculated using months.
For all arguments, cash paid (such as deposits to savings) is represented by negative numbers; cash received (such as dividend
checks) is represented by positive numbers.
Example
This example uses the Pmt function to return the monthly payment for a loan during a fixed period. Given are the interest
percentage rate per period (APR / 12), the total number of payments (TotPmts), the present value or principal of the loan
(PVal), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of
the payment period (PayType).
VB
Sub TestPMT()
Dim PVal, APR, Payment, TotPmts As Double
Dim PayType As DueDate
Dim Response As MsgBoxResult
' Define money format.
Dim Fmt As String = "###,###,##0.00"
' Usually 0 for a loan.
Dim FVal As Double = 0
PVal = CDbl(InputBox("How much do you want to borrow?"))
APR = CDbl(InputBox("What is the annual percentage rate of your loan?"))
If APR > 1 Then APR = APR / 100 ' Ensure proper form.
TotPmts = CDbl(InputBox("How many monthly payments will you make?"))
Response = MsgBox("Do you make payments at the end of month?", MsgBoxStyle.YesNo)
If Response = MsgBoxResult.No Then
PayType = DueDate.BegOfPeriod
Else
PayType = DueDate.EndOfPeriod
End If
Payment = Pmt(APR / 12, TotPmts, -PVal, FVal, PayType)
MsgBox("Your payment will be " & Format(Payment, Fmt) & " per month.")
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
ArgumentException
Visual Basic Language Reference
PPmt Function
Returns a Double specifying the principal payment for a given period of an annuity based on periodic fixed payments and a
fixed interest rate.
Function PPmt( _
ByVal Rate As Double, _
ByVal Per As Double, _
ByVal NPer As Double, _
ByVal PV As Double, _
Optional ByVal FV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod _
) As Double
Parameters
Rate
Required. Double specifies the interest rate per period. For example, if you get a car loan at an annual percentage rate (APR)
of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
Per
Required. Double specifies the payment period in the range 1 through NPer.
NPer
Required. Double specifies the total number of payment periods in the annuity. For example, if you make monthly payments
on a four-year car loan, your loan has a total of 4 x 12 (or 48) payment periods.
PV
Required. Double specifies the current value of a series of future payments or receipts. For example, when you borrow
money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
FV
Optional. Double specifying future value or cash balance you want after you have made the final payment. For example, the
future value of a loan is $0 because that is its value after the final payment. However, if you want to save $50,000 over 18
years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are due at
the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Exceptions
Exception type Error number Condition
ArgumentException 5 Per <=0 or Per > NPer.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage)
or an investment (such as a monthly savings plan).
The Rate and NPer arguments must be calculated using payment periods expressed in the same units. For example, if Rate is
calculated using months, NPer must also be calculated using months.
For all arguments, cash paid (such as deposits to savings) is represented by negative numbers; cash received (such as dividend
checks) is represented by positive numbers.
Example
This example uses the PPmt function to calculate how much of a payment for a specific period is principal when all the
payments are of equal value. Given are the interest percentage rate per period (APR / 12), the payment period for which the
principal portion is desired (Period), the total number of payments (TotPmts), the present value or principal of the loan (PVal),
the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the
payment period (PayType).
VB
Sub TestPPMT()
Dim PVal, APR, TotPmts, Payment, Period, P, I As Double
Dim PayType As DueDate
Dim Msg As String
Dim Response As MsgBoxResult
' Define money format.
Dim Fmt As String = "###,###,##0.00"
' Usually 0 for a loan.
Dim Fval As Double = 0
PVal = CDbl(InputBox("How much do you want to borrow?"))
APR = CDbl(InputBox("What is the annual percentage rate of your loan?"))
' Ensure proper form.
If APR > 1 Then APR = APR / 100
TotPmts = CDbl(InputBox("How many monthly payments do you have to make?"))
Response = MsgBox("Do you make payments at the end of month?", MsgBoxStyle.YesNo)
If Response = MsgBoxResult.No Then
PayType = DueDate.BegOfPeriod
Else
PayType = DueDate.EndOfPeriod
End If
Payment = Math.Abs(-Pmt(APR / 12, TotPmts, PVal, FVal, PayType))
Msg = "Your monthly payment is " & Format(Payment, Fmt) & ". "
Msg = Msg & "Would you like a breakdown of your principal and "
Msg = Msg & "interest per period?"
' See if chart is desired.
Response = MsgBox(Msg, MsgBoxStyle.YesNo)
If Response <> MsgBoxResult.No Then
If TotPmts > 12 Then MsgBox("Only first year will be shown.")
Msg = "Month Payment Principal Interest" & vbNewLine
For Period = 1 To TotPmts
' Show only first 12.
If Period > 12 Then Exit For
P = PPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType)
' Round principal.
P = (Int((P + 0.005) * 100) / 100)
I = Payment - P
' Round interest.
I = (Int((I + 0.005) * 100) / 100)
Msg = Msg & Period & vbTab & Format(Payment, Fmt)
Msg = Msg & vbTab & Format(P, Fmt) & vbTab & Format(I, Fmt) & vbNewLine
Next Period
' Display amortization table.
MsgBox(Msg)
End If
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
ArgumentException
Visual Basic Language Reference
Parameters
FileNumber
Required. Any valid file number.
Output
Optional. Zero or more comma-delimited expressions to write to a file.
The Output argument settings are:
Setti Description
ng
SPC( Used to insert space characters in the output, where n is the number of space characters to insert.
n)
TAB( Used to position the insertion point to an absolute column number, where n is the column number. Use TAB with no ar
n ) gument to position the insertion point at the beginning of the next print zone.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Print and PrintLine functions are provided for backward compatibility and may have an impact on performance. For non-
legacy applications, the My.Computer.FileSystem object provides better performance. For more information, see
File Access with Visual Basic.
Print does not include a line feed at the end of a line; PrintLine, however, does include a line feed.
Data written with Print is usually read from a file with LineInput or Input.
If you omit Output for PrintLine, a blank line is printed to the file; for Print, nothing is output. Multiple expressions separated
with a comma will be aligned on tab boundaries, but mixing commas and TAB may result in inconsistent results.
For Boolean data, either True or False is printed. The True and False keywords are not translated, regardless of the locale.
Date data is written to the file using the standard short date format recognized by your system. When either the date or the
time component is missing or zero, only the part provided is written to the file.
Nothing is written to the file if Output data is empty. However, if Output list data is DBNull, Null is written to the file.
For Error data, the output appears as Error errorcode. The Error keyword is not translated regardless of the locale.
All data written to the file using Print is internationally aware; that is, the data is properly formatted using the appropriate
decimal separator. If the user wishes to output data for use by multiple locales, then Write should be used.
Writing to a file with the Print or PrintLine functions requires Write access from the FileIOPermissionAccess enumeration.
For more information, see FileIOPermissionAccess Enumeration.
Example
This example uses the Print and PrintLine functions to write data to a file.
VB
FileOpen(1, "c:\trash.txt", OpenMode.Output) ' Open file for output.
Print(1, "This is a test.") ' Print text to file.
PrintLine(1) ' Print blank line to file.
PrintLine(1, "Zone 1", TAB(), "Zone 2") ' Print in two print zones.
PrintLine(1, "Hello", "World") ' Separate strings with a tab.
PrintLine(1, SPC(5), "5 leading spaces ") ' Print five leading spaces.
PrintLine(1, TAB(10), "Hello") ' Print word at column 10.
' Dates and booleans are translated using locale settings of your system.
PrintLine(1, aBool, " is a Boolean value")
PrintLine(1, aDate, " is a date")
FileClose(1) ' Close file.
PV Function
Returns a Double specifying the present value of an annuity based on periodic, fixed payments to be paid in the future and a
fixed interest rate.
Function PV( _
ByVal Rate As Double, _
ByVal NPer As Double, _
ByVal Pmt As Double, _
Optional ByVal FV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod _
) As Double
Parameters
Rate
Required. Double specifies the interest rate per period. For example, if you get a car loan at an annual percentage rate (APR)
of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
NPer
Required. Double specifies the total number of payment periods in the annuity. For example, if you make monthly payments
on a four-year car loan, your loan has 4 x 12 (or 48) payment periods.
Pmt
Required. Double specifies the payment to be made each period. Payments usually contain principal and interest that does
not change during the life of the annuity.
FV
Optional. Double specifies the future value or cash balance you want after you make the final payment. For example, the
future value of a loan is $0 because that is its value after the final payment. However, if you want to save $50,000 over 18
years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are due at
the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Remarks
An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage)
or an investment (such as a monthly savings plan).
The Rate and NPer arguments must be calculated using payment periods expressed in the same units. For example, if Rate is
calculated using months, NPer must also be calculated using months.
For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as
dividend checks) is represented by positive numbers.
Example
In this example, the PV function returns the present value of an $1,000,000 annuity that will provide $50,000 a year for the
next 20 years. Provided are the expected annual percentage rate (APR), the total number of payments (TotPmts), the amount of
each payment (YrIncome), the total future value of the investment (FVal), and a number that indicates whether each payment is
made at the beginning or end of the payment period (PayType). Note that YrIncome is a negative number because it represents
cash paid out from the annuity each year.
VB
Sub TestPV()
' Define money format.
Dim Fmt As String = "###,##0.00"
' Annual percentage rate.
Dim APR As Double = 0.0825
' Total number of payments.
Dim TotPmts As Double = 20
' Yearly income.
Dim YrIncome As Double = 50000
' Future value.
Dim FVal As Double = 1000000
' Payment at beginning of month.
Dim PayType As DueDate = DueDate.BegOfPeriod
Dim PVal As Double = PV(APR, TotPmts, -YrIncome, FVal, PayType)
MsgBox("The present value is " & Format(PVal, Fmt) & ".")
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
Visual Basic Language Reference
QBColor Function
Returns an Integer value representing the RGB color code corresponding to the specified color number.
QBColor(Color)
Parameters
Color
Required. A whole number in the range 0–15.
Settings
The Color argument has these settings.
Number Color Number Color
0 Black 8 Gray
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Starting with the least-significant byte, the returned value specifies the red, green, and blue values used to set the appropriate
color in the RGB system used by the Visual Basic language.
Example
This example uses the QBColor function to change to the color indicated by colorInteger. QBColor accepts integer values
between 0 and 15.
VB
Dim colorInteger As Integer
' Use 4 for red.
colorInteger = QBColor(4)
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
RGB Function (Visual Basic)
ArgumentException Class
Visual Basic Language Reference
Parameters
Number
Optional. An Object or any valid numeric expression.
Remarks
Randomize uses Number to initialize the Rnd function's random-number generator, giving it a new seed value. If you omit
Number, the value returned by the system timer is used as the new seed value.
If Randomize is not used, the Rnd function (with no arguments) uses the same number as a seed the first time it is called, and
thereafter uses the last-generated number as a seed value.
Note
To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a n
umeric argument. Using Randomize with the same value for Number does not repeat the previous sequence.
Security Note
Because the Random statement and the Rnd function start with a seed value and generate numbers that fall within a finite r
ange, the results may be predictable by someone who knows the algorithm used to generate them. Consequently, the Rand
om statement and the Rnd function should not be used to generate random numbers for use in cryptography. For more info
rmation, see RandomNumberGenerator.
Example
This example uses the Randomize statement to initialize the random-number generator. Because the number argument has
been omitted, Randomize uses the return value from the Timer function as the new seed value.
VB
' Initialize the random-number generator.
Randomize()
' Generate random value between 1 and 6.
Dim value As Integer = CInt(Int((6 * Rnd()) + 1))
Requirements
Namespace: Microsoft.VisualBasic
Module: VBMath
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Math Summary
Rnd Function (Visual Basic)
Visual Basic Language Reference
Rate Function
Returns a Double specifying the interest rate per period for an annuity.
Function Rate( _
ByVal NPer As Double, _
ByVal Pmt As Double, _
ByVal PV As Double, _
Optional ByVal FV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod, _
Optional ByVal Guess As Double = 0.1 _
) As Double
Parameters
NPer
Required. Double specifies the total number of payment periods in the annuity. For example, if you make monthly payments
on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
Pmt
Required. Double specifies the payment to be made each period. Payments usually contain principal and interest that
doesn't change over the life of the annuity.
PV
Required. Double specifies the present value, or value today, of a series of future payments or receipts. For example, when
you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will
make.
FV
Optional. Double specifies the future value or cash balance you want after you make the final payment. For example, the
future value of a loan is $0 because that is its value after the final payment. However, if you want to save $50,000 over 18
years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are due at
the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Guess
Optional. Double specifying value you estimate is returned by Rate. If omitted, Guess is 0.1 (10 percent).
Exceptions
Exception type Error number Condition
ArgumentException 5 NPer <= 0.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage)
or an investment (such as a monthly savings plan).
For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as
dividend checks) is represented by positive numbers.
Rate is calculated by iteration. Starting with the value of Guess, Rate cycles through the calculation until the result is accurate
to within 0.00001 percent. If Rate cannot find a result after 20 tries, it fails. If your guess is 10 percent and Rate fails, try a
different value for Guess.
Example
This example uses the Rate function to calculate the interest rate of a loan given the total number of payments (TotPmts), the
amount of the loan payment (Payment), the present value or principal of the loan (PVal), the future value of the loan (FVal), a
number that indicates whether the payment is due at the beginning or end of the payment period (PayType), and an
approximation of the expected interest rate (Guess).
VB
Sub TestRate()
Dim PVal, Payment, TotPmts, APR As Double
Dim PayType As DueDate
' Define percentage format.
Dim Fmt As String = "##0.00"
Dim Response As MsgBoxResult
' Usually 0 for a loan.
Dim FVal As Double = 0
' Guess of 10 percent.
Dim Guess As Double = 0.1
PVal = CDbl(InputBox("How much did you borrow?"))
Payment = CDbl(InputBox("What's your monthly payment?"))
TotPmts = CDbl(InputBox("How many monthly payments do you have to make?"))
Response = MsgBox("Do you make payments at the end of the month?", MsgBoxStyle.YesNo)
If Response = MsgBoxResult.No Then
PayType = DueDate.BegOfPeriod
Else
PayType = DueDate.EndOfPeriod
End If
APR = (Rate(TotPmts, -Payment, PVal, FVal, PayType, Guess) * 12) * 100
MsgBox("Your interest rate is " & Format(CInt(APR), Fmt) & " percent.")
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
ArgumentException
Visual Basic Language Reference
Rename Function
Renames a disk file or directory.
The My feature gives you greater productivity and performance in file I/O operations than Rename. For more information, see
My.Computer.FileSystem Object.
Parameters
OldPath
Required. String expression that specifies the existing file name and location. OldPath may include the directory, and drive,
of the file.
NewPath
Required. String expression that specifies the new file name and location. NewPath may include directory and drive of the
destination location. The file name specified by NewPath cannot already exist.
Exceptions
Exception type Error number Condition
ArgumentException 5 Path is invalid.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Rename function renames a file and moves it to a different directory, if necessary. The Rename function can move a file
across drives, but it can only rename an existing directory when both NewPath and OldPath are located on the same drive.
Rename cannot create a new file or directory.
Using the Rename function on an open file produces an error. You must close an open file before renaming it. Rename
arguments cannot include multiple-character (*) and single-character (?) wildcards.
Security Note
When using Rename to copy a file from an unprotected location to a protected location, the file retains the less restricted rig
hts. Check to make sure you are not introducing a possible security risk.
Example
This example uses the Rename function to rename a file. For purposes of this example, assume that the directories that are
specified already exist.
VB
Dim OldName, NewName As String
OldName = "OLDFILE"
' Define file names.
NewName = "NEWFILE"
' Rename file.
Rename(OldName, NewName)
OldName = "C:\OLDDIR\OLDFILE"
NewName = "C:\NEWDIR\NEWFILE"
' Move and rename file.
Rename(OldName, NewName)
Parameters
Expression
Required. String expression containing substring to replace.
Find
Required. Substring being searched for.
Replacement
Required. Replacement substring.
Start
Optional. Position within Expression where substring search is to begin. If omitted, 1 is assumed.
Count
Optional. Number of substring substitutions to perform. If omitted, the default value is –1, which means "make all possible
substitutions."
Compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings for values.
Settings
The Compare argument can have the following values.
Constant Description
Binary Performs a binary comparison
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The return value of the Replace function is a string that begins at the position specified by Start and concludes at the end of
the Expression string, with the substitutions made as specified by the Find and Replace values.
Example
This example demonstrates the Replace function.
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Filter Function (Visual Basic)
ArgumentException
Visual Basic Language Reference
Reset Function
Closes all disk files opened using the FileOpen function.
The My feature gives you greater productivity and performance in file I/O operations than Reset. For more information, see
My.Computer.FileSystem Object.
Remarks
The Reset function closes all active files opened by the FileOpen function and has the same function as FileClose() without
any parameters.
Example
This example uses the Reset function to close all open files and write the contents of all file buffers to disk. Note the use of the
Object variable FileNumber as both a string and a number.
VB
' Open 5 files named TEST1, TEST2, etc.
Dim fileNumber As Integer
' Open 5 files.
For fileNumber = 1 To 5
FileOpen(fileNumber, "TEST" & fileNumber, OpenMode.Output)
PrintLine(fileNumber, "Hello World")
Next fileNumber
' Close files and write contents to disk.
Reset()
RGB( _
Red As Integer, _
Green As Integer, _
Blue As Integer _
)
Parameters
Red
Required. Integer in the range 0–255, inclusive, that represents the intensity of the red component of the color.
Green
Required. Integer in the range 0–255, inclusive, that represents the intensity of the green component of the color.
Blue
Required. Integer in the range 0–255, inclusive, that represents the intensity of the blue component of the color.
Exceptions
Exception type Error number Condition
ArgumentException 5 Green, Blue, or Red outside of range 0 and 255, inclusive.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Application methods and properties that accept a color specification expect that specification to be a number representing an
RGB color value. An RGB color value specifies the relative intensity of red, green, and blue to cause a specific color to be
displayed.
If the value for any argument to RGB is greater than 255, 255 is used.
The following table lists some standard colors and the red, green, and blue values they include.
Color Red value Green value Blue value
Black 0 0 0
Blue 0 0 255
Green 0 255 0
Red 255 0 0
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
QBColor Function
ArgumentException Class
Visual Basic Language Reference
Parameters
str
Required. String expression from which the rightmost characters are returned.
Length
Required. Integer. 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.
Exceptions
Exception type Error number Condition
ArgumentException 5 Length < 0.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
To determine the number of characters in str, use the Len function. If used in a Windows Form, or any other class that has a
Right property, you must fully qualify the function with Microsoft.VisualBasic.Right.
Note
The RightB function in earlier versions of Visual Basic returns a string in bytes, rather than characters. It is used primarily for
converting strings in double-byte character set (DBCS) applications. All current Visual Basic strings are in Unicode, and Right
B is no longer supported.
Example
This example demonstrates the use of the Right function to return a substring of a given String. In a class that has a Right
property, it may be necessary to fully qualify the Right function.
VB
Dim TestString As String = "Hello World!"
' Returns "World!".
Dim subString As String = Microsoft.VisualBasic.Right(TestString, 6)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Left Function (Visual Basic)
Len Function (Visual Basic)
Mid Function (Visual Basic)
ArgumentException
Concepts
Programming Element Support Changes Summary
Visual Basic Language Reference
RmDir Function
Removes an existing directory.
The My feature gives you greater productivity and performance in file I/O operations than RmDir. For more information, see
My.Computer.FileSystem.DeleteDirectory Method.
Parameters
Path
Required. String expression that identifies the directory or folder to be removed. Path can include the drive. If no drive is
specified, RmDir removes the directory on the current drive.
Exceptions
Exception type Error number Condition
ArgumentException 52 Path is not specified or is empty.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
An error occurs if you try to use RmDir on a directory containing files. Use the Kill function to delete all files before attempting
to remove a directory.
Example
This example uses the RmDir function to remove an existing directory.
VB
' Assume that MYDIR is an empty directory.
' Remove MYDIR.
RmDir("MYDIR")
Parameters
Number
Optional. A Single value or any valid Single expression.
Return Value
If number is Rnd generates
Less than zero The same number every time, using Number as the seed.
Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.
Note
To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a n
umeric argument. Using Randomize with the same value for Number does not repeat the previous sequence.
Security Note
Because the Random statement and the Rnd function start with a seed value and generate numbers that fall within a finite r
ange, the results may be predictable by someone who knows the algorithm used to generate them. Consequently, the Rand
om statement and the Rnd function should not be used to generate random numbers for use in cryptography.
Example
This example uses the Rnd function to generate a random integer value in the range from 1 to 6.
VB
' Initialize the random-number generator.
Randomize()
' Generate random value between 1 and 6.
Dim value As Integer = CInt(Int((6 * Rnd()) + 1))
Requirements
Namespace: Microsoft.VisualBasic
Module: VBMath
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Randomize Function (Visual Basic)
Math Summary
Randomize Function (Visual Basic)
Visual Basic Language Reference
RSet Function
Returns a right-aligned string containing the specified string adjusted to the specified length.
Parameters
Source
Required. String expression. String to be adjusted.
Length
Required. Integer expression. Length of returned string.
Remarks
If Source is longer than Length, RSet returns only the leftmost characters, up to the length of Length. If Source is shorter than
Length, RSet adds spaces to the left end of the string to produce the appropriate length.
Example
This example demonstrates the use of the RSet function.
VB
Dim TestString As String = "Right"
' Returns " Right"
Dim rString As String = RSet(TestString, 11)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Data Type Summary (Visual Basic)
LSet Function
Concepts
Efficient Use of Data Types
Visual Basic Language Reference
Parameters
str
Required. Any valid String expression.
Remarks
The LTrim, RTrim, and Trim functions remove spaces from the ends of strings. To remove other forms of white space, such as
tab characters, use the System.String.Trim method.
Example
This example uses the LTrim function to strip leading spaces and the RTrim function to strip trailing spaces from a string
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)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Left Function (Visual Basic)
Right Function (Visual Basic)
Trim
Visual Basic Language Reference
S-Z Functions
The following table contains a listing of the Visual Basic run-time member functions.
Year
The math functions Sgn, Sin, Sqr, and Tan that were available as Visual Basic run-time member functions in version 6.0 and
earlier have been replaced by methods (Sign, Sin, Sqrt, and Tan) in the Math class of the .NET Framework class library. For
more information, see Math Functions (Visual Basic).
Smart Device Developer Notes
The following are not supported in smart device applications: SaveSetting, Seek, SetAttr, Shell, SPC, StrConv, TAB, Unlock,
VarType, Write, and WriteLine.
See Also
Reference
A-C Functions
D-G Functions
H-L Functions
M-R Functions
Other Resources
Visual Basic Reference
Visual Basic Language Reference
SaveSetting Function
Saves or creates an application entry in the Windows registry.
The My feature gives you greater productivity and performance in registry operations than SaveSetting. For more
information, see My.Computer.Registry Object.
Parameters
AppName
Required. String expression containing the name of the application or project to which the setting applies.
Section
Required. String expression containing the name of the section in which the key setting is being saved.
Key
Required. String expression containing the name of the key setting being saved.
Setting
Required. Expression containing the value to which Key is being set.
Exceptions
Exception type Error number Condition
ArgumentException 5 Key registry could not be created, or user is not logged in.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The SaveSetting function adds the key to HKEY_CURRENT_USER\Software\VB and VBA Program Settings.
If the key setting cannot be saved for any reason, an error occurs.
SaveSetting requires that a user be logged on since it operates under the HKEY_LOCAL_USER registry key, which is not
active until a user logs on interactively.
Registry settings that are to be accessed from a non-interactive process (such as Mtx.exe) should be stored under either the
HKEY_LOCAL_MACHINE\Software\ or the HKEY_USER\DEFAULT\Software registry keys.
SaveSetting requires Write and Create Registry Permission.
Example
The following example first uses the SaveSetting function to make entries in the Windows registry for the MyApp application,
and then uses the DeleteSetting function to remove them.
VB
' Place some settings in the registry.
SaveSetting("MyApp", "Startup", "Top", "75")
SaveSetting("MyApp","Startup", "Left", "50")
' Remove Startup section and all its settings from registry.
DeleteSetting ("MyApp", "Startup")
' Remove MyApp from the registry.
DeleteSetting ("MyApp")
Parameters
TimeValue
Required. Date value from which you want to extract the second.
Remarks
You can also obtain the second of the minute by calling DatePart and specifying DateInterval.Second for the Interval
argument.
Example
The following example uses the Second function to obtain the second of the minute from a specified time. In the development
environment, the time literal is displayed in short time format using the locale settings of your code.
VB
Dim thisTime As Date
Dim thisSecond As Integer
thisTime = #4:35:17 PM#
thisSecond = Second(thisTime)
' thisSecond now contains 17.
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Hour Function (Visual Basic)
Minute Function
Now Property
TimeOfDay Property
DatePart Function (Visual Basic)
System
DateTime
ArgumentException
ArgumentOutOfRangeException
Visual Basic Language Reference
Seek Function
Returns a Long specifying the current read/write position within a file opened using the FileOpen function, or sets the
position for the next read/write operation within a file opened using the FileOpen function.
The My feature gives you greater productivity and performance in file I/O operations than Seek. For more information, see
My.Computer.FileSystem Object.
Parameters
FileNumber
Required. An Integer containing a valid file number.
Position
Required. Number in the range 1–2,147,483,647, inclusive, that indicates where the next read/write operation should occur.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Seek returns a value between 1 and 2,147,483,647 (equivalent to 2^31 – 1), inclusive.
The following describes the return values for each file access mode:
Mode Return Value
Random Number of the next record read or written
Binary, Input, Output, Byte position at which the next operation takes place. The first byte in a file is at position 1, the secon
Append d byte is at position 2, and so on.
Example
This example uses the Seek function to return the current file position. The example assumes TestFile is a file containing
records of the structure Record.
VB
Structure Record ' Define user-defined type.
Dim ID As Integer
Dim Name As String
End Structure
For files opened in Random mode, Seek returns the number of next record.
VB
FileOpen(1, "TESTFILE", OpenMode.Random)
Do While Not EOF(1)
WriteLine(1,Seek(1)) ' Write record number.
FileGet(1, MyRecord, -1) ' Read next record.
Loop
FileClose(1)
For files opened in modes other than Random mode, Seek returns the byte position at which the next operation takes place.
Assume TestFile is a file containing a few lines of text.
VB
' Report character position at beginning of each line.
Dim TextLine As String
FileOpen(1, "TESTFILE", OpenMode.Input) ' Open file for reading.
While Not EOF(1)
' Read next line.
TextLine = LineInput(1)
' Position of next line.
MsgBox(Seek(1))
End While
FileClose(1)
This example uses the Seek function to set the position for the next read or write within a file. This example assumes
People.txt is a file containing records of the structure Record.
VB
Structure TestRecord
Dim Name As String
Dim ID As Integer
End Structure
For files opened in modes other than Random mode, Seek sets the byte position at which the next operation takes place.
Assume TestFile is a file containing a few lines of text.
VB
Dim someText As String = "This is a test string."
' Open file for output.
FileOpen(1, "TESTFILE", OpenMode.Input)
' Move to the third character.
Seek(1, 3)
Input(1, someText)
Console.WriteLine(someText)
FileClose(1)
SetAttr Function
Sets attribute information for a file.
The My feature gives you greater productivity and performance in file I/O operations than SetAttr. For more information, see
My.Computer.FileSystem Object.
Parameters
PathName
Required. String expression that specifies a file name. PathName can include directory or folder, and drive.
Attributes
Required. Constant or numeric expression, whose sum specifies file attributes.
Settings
The Attributes argument enumeration values are:
Value Constant Description
Normal vbNormal Normal (default).
Exceptions
Exception type Error number Condition
ArgumentException 52 PathName invalid or does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
A run-time error occurs if you try to set the attributes of an open file.
Example
This example uses the SetAttr function to set attributes for a file.
VB
' Set hidden attribute.
SetAttr("TESTFILE", vbHidden)
' Set hidden and read-only attributes.
SetAttr("TESTFILE", vbHidden Or vbReadOnly)
Shell Function
Runs an executable program and returns an integer containing the program's process ID if it is still running.
Parameters
PathName
Required. String. Name of the program to execute, together with any required arguments and command-line switches.
PathName can also include the drive and the directory path or folder.
If you do not know the path to the program, you can use the My.Computer.FileSystem.GetFiles Method to locate it. For
example, you can call My.Computer.FileSystem.GetFiles("C:\", True, "testFile.txt"), which returns the full path of
every file named testFile.txt anywhere on drive C:\.
Style
Optional. AppWinStyle. A value chosen from the AppWinStyle Enumeration specifying the style of the window in which the
program is to run. If Style is omitted, Shell uses AppWinStyle.MinimizedFocus, which starts the program minimized and
with focus.
Wait
Optional. Boolean. A value indicating whether the Shell function should wait for completion of the program. If Wait is
omitted, Shell uses False.
Timeout
Optional. Integer. The number of milliseconds to wait for completion if Wait is True. If Timeout is omitted, Shell uses -1,
which means there is no timeout and Shell does not return until the program finishes. Therefore, if you omit Timeout or set
it to -1, it is possible that Shell might never return control to your program.
Exceptions
Exception type Error number Condition
ArgumentException 5 Style is not within range 0 through 9, inclusive.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The return value of the Shell function depends on whether the program named in PathName is still executing when Shell
returns. If you set Wait to True and the program finishes before the timeout expires, Shell returns zero. If the timeout expires,
or if you omit Wait or set it to False, Shell returns the process ID of the program. The process ID is a unique number that
identifies the running program.
Failure to Start
If the Shell function cannot start the named program, a FileNotFoundException error occurs. This can happen, for example,
when you attempt to run a 16-bit program, such as command.com, from an application using System.Windows.Forms. For a
workaround, you can run a 32-bit program that calls the desired 16-bit program. In the case of command.com, you can run
cmd.exe as an alternative.
Waiting for Completion
By default, the Shell function runs the program asynchronously. This means that a program started with the Shell function
might not finish executing before the statements following the Shell function are executed. If you want to wait for the program
to finish before you continue, set Wait to True.
Determining the Exit Code
A process can return an exit code when it terminates. However, you cannot use Shell to retrieve this exit code, because Shell
returns zero if it waits for termination, and also because the process runs in a different object from Shell.
To retrieve the exit code from a process, you must write your own code to initiate the process and wait for termination. The
following example shows how to initiate a process, wait for it to terminate, and retrieve its exit code.
Each pair of adjacent double quotation marks (" ") within the string literal is interpreted as one double quotation character in
the string. Therefore, the preceding example presents the following string to the Shell function:
"C:\Program Files\display.exe" -a -q
If you did not have the path enclosed in quotation marks, Windows would look for a file called Program.exe in the C:\ directory,
instead of display.exe in the C:\Program Files directory.
Security Note
If you do not enclose the path and file specification in quotation marks, there is a security risk if the file name or a path node
contains spaces. In the preceding example, the path node \Program Files includes a space. If the specification were not insid
e quotation marks and a program named Program.exe had been installed in C:\, for example by illicit tampering, Windows w
ould execute it instead of display.exe.
Security Note
The Shell function requires unmanaged code permission, which might affect its execution in partial-trust situations. For mor
e information, see SecurityPermission and Code Access Permissions.
Example
The following example uses the Shell function to run an application specified by the user. Specifying
Microsoft.VisualBasic.AppWinStyle.NormalFocus as the second argument opens the application in normal size and gives it the
focus.
VB
Dim procID As Integer
' Run calculator.
procID = Shell("C:\Windows\system32\calc.exe", AppWinStyle.NormalFocus)
' The preceding path is for Windows XP.
' The Windows 2000 path is C:\WINNT\system32\calc.exe.
Smart Device Developer Notes
This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
AppWinStyle Enumeration
My.Computer.FileSystem.GetFiles Method
AppActivate Function
ArgumentException
FileNotFoundException
NullReferenceException
Visual Basic Language Reference
SLN Function
Returns a Double specifying the straight-line depreciation of an asset for a single period.
Function SLN( _
ByVal Cost As Double, _
ByVal Salvage As Double, _
ByVal Life As Double _
) As Double
Parameters
Cost
Required. Double specifying initial cost of the asset.
Salvage
Required. Double specifying value of the asset at the end of its useful life.
Life
Required. Double specifying length of the useful life of the asset.
Exceptions
Exception type Error number Condition
ArgumentException 5 Life = 0.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The depreciation period must be expressed in the same unit as the Life argument. All arguments must be positive numbers.
Example
This example uses the SLN function to return the straight-line depreciation of an asset for a single period given the asset's
initial cost (InitCost), the salvage value at the end of the asset's useful life (SalvageVal), and the total life of the asset in years
(LifeTime).
VB
Dim InitCost, SalvageVal, LifeTime, DepYear As Double
Dim Fmt As String = "###,##0.00"
' Use the SLN function to calculate the deprecation per year.
Dim SlnDepr As Double = SLN(InitCost, SalvageVal, LifeTime)
Dim msg As String = "The depreciation per year: " & Format(SlnDepr, Fmt)
msg &= vbCrLf & "Year" & vbTab & "Linear" & vbTab & "Doubling" & vbCrLf
' Use the SYD and DDB functions to calculate the deprecation for each year.
For DepYear = 1 To LifeTime
msg &= DepYear & vbTab & _
Format(SYD(InitCost, SalvageVal, LifeTime, DepYear), Fmt) & vbTab & _
Format(DDB(InitCost, SalvageVal, LifeTime, DepYear), Fmt) & vbCrLf
Next
MsgBox(msg)
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
SYD Function
DDB Function
Financial Summary
ArgumentException
Visual Basic Language Reference
Parameters
Number
Required. Integer expression. The number of spaces you want in the string.
Exceptions
Exception type Error number Condition
ArgumentException 5 Number < 0.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Space function is useful for formatting output and clearing data in fixed-length strings.
Example
This example uses the Space function to return a string consisting of a specified number of spaces.
VB
Dim TestString As String
' Returns a string with 10 spaces.
TestString = Space(10)
' Inserts 10 spaces between two strings.
TestString = "Hello" & Space(10) & "World"
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
SPC Function
ArgumentException
Visual Basic Language Reference
SPC Function
Used with the Print or PrintLine function to position output.
Parameters
Count
Required. The number of spaces to insert before displaying or printing the next expression in a list.
Remarks
If Count is less than the output line width, the next print position immediately follows the number of spaces printed. If Count is
greater than the output line width, SPC calculates the next print position using the formula:
currentprintposition(+(Count Mod width))
For example, if the current print position is 24, the output line width is 80, and you specify SPC(90), the next print will start at
position 34 (current print position + the remainder of 90/80). If the difference between the current print position and the
output line width is less than Count (or Count Mod width), the SPC function skips to the beginning of the next line and
generates spaces equal to Count – (width – currentprintposition).
Note
Make sure your tabular columns are wide enough to accommodate wide letters.
Example
This example uses the SPC function to position output in a file and in the Output window.
VB
' The SPC function can be used with the Print function.
FileOpen(1, "TESTFILE", OpenMode.Output) ' Open file for output.
Print(1, "10 spaces between here", SPC(10), "and here.")
FileClose(1) ' Close file.
Function Split(
ByVal Expression As String,
Optional ByVal Delimiter As String = " ",
Optional ByVal Limit As Integer = -1,
Optional ByVal Compare As CompareMethod = CompareMethod.Binary
) As String()
Parameters
Expression
Required. String expression containing substrings and delimiters.
Delimiter
Optional. Any single character used to identify substring limits. If Delimiter is omitted, the space character (" ") is assumed to
be the delimiter.
Limit
Optional. Maximum number of substrings into which the input string should be split. The default, –1, indicates that the input
string should be split at every occurrence of the Delimiter string.
Compare
Optional. Numeric value indicating the comparison to use when evaluating substrings. See "Settings" for values.
Returns
String array. If Expression is a zero-length string (""), Split returns a single-element array containing a zero-length string. If
Delimiter is a zero-length string, or if it does not appear anywhere in Expression, Split returns a single-element array
containing the entire Expression string.
Settings
The Compare argument can have the following values.
Constant Description Value
CompareMethod.Binary Performs a binary comparison 0
The following example demonstrates how to split strings with multiple delimiters in a row and filter out the empty strings.
VB
Dim TestString As String = "apple pear banana "
Dim TestArray() As String = Split(TestString)
' TestArray holds {"apple", "", "", "", "pear", "banana", "", ""}
Dim LastNonEmpty As Integer = -1
For i As Integer = 0 To TestArray.Length - 1
If TestArray(i) <> "" Then
LastNonEmpty += 1
TestArray(LastNonEmpty) = TestArray(i)
End If
Next
ReDim Preserve TestArray(LastNonEmpty)
' TestArray now holds {"apple", "pear", "banana"}
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Join Function (Visual Basic)
CompareMethod Enumeration
Visual Basic Language Reference
Str Function
Returns a String representation of a number.
Parameters
Number
Required. An Object containing any valid numeric expression.
Exceptions
Exception type Error number Condition
ArgumentNullException 5 Number is not specified.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
When numbers are converted to strings, a leading space is always reserved for the sign of Number. If Number is positive, the
returned string contains a leading space, and the plus sign is implied. A negative number will include the minus sign (-) and no
leading space.
Use the Format function to convert numeric values you want formatted as dates, times, or currency or in other user-defined
formats. Unlike the Str function, the Format function does not include a leading space for the sign of Number.
Note
The Str function recognizes only the period (.) as a valid decimal separator. If different decimal separators are used (for exam
ple, in international applications), use the CStr or Format functions to convert a number to a string. To get the string represe
ntation of a number in a particular culture, use the number's ToString(IFormatProvider) method. For example, use
ToString when converting a value of type Double to a string.
Example
This example uses the Str function to return a String representation of a number. When a positive number is converted to a
string, a leading space is always reserved for its sign.
VB
Dim TestString As String
' Returns " 459".
TestString = Str(459)
' Returns "-459.65".
TestString = Str(-459.65)
' Returns " 459.001".
TestString = Str(459.001)
Requirements
Namespace: Microsoft.VisualBasic
Module: Conversion
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Conversion Summary
Format Function
Type Conversion Functions
Format Function
Val Function
ArgumentNullException
InvalidCastException
Visual Basic Language Reference
Parameters
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.
Settings
The Compare argument settings are:
Consta Description
nt
Binary Performs a binary comparison, based on a sort order derived from the internal binary representations of the characte
rs.
Text Performs a text comparison, based on a case-insensitive text sort order determined by your application's current cult
ure information.
Return Value
The StrComp function has the following return values.
If StrComp returns
String1 sorts ahead of String2 -1
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The strings are compared by alphanumeric sort values beginning with the first character. For further information on binary
comparisons, textual comparisons, and sort order, see Option Compare Statement.
Security Note
If your application makes security decisions based on the result of a comparison or case-change operation, then the operatio
n should use the System.String.Compare(System.String,System.String,System.StringComparison) method, and pass Ordinal
or OrdinalIgnoreCase for the comparisonType argument. For more information, see
How Culture Affects Strings in Visual Basic.
Example
This example uses the StrComp function to return the results of a string comparison. If the third argument is omitted, the
comparison type defined in the Option Compare statement or project defaults is performed.
VB
' Defines variables.
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)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
InStr Function (Visual Basic)
ArgumentException
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference
StrConv Function
Returns a string converted as specified.
Parameters
str
Required. String expression to be converted.
Conversion
Required. VbStrConv Enumeration member. The enumeration value specifying the type of conversion to perform.
LocaleID
Optional. The LocaleID value, if different from the application's current culture value. For more information about locale IDs
and culture information, see CultureInfo. (The application's current culture value is the default.)
Settings
The Conversion argument settings are:
Enumeration member Description
VbStrConv.None Performs no conversion
VbStrConv.LinguisticC Uses linguistic rules for casing, rather than File System (default). Valid with VbStrConv.UpperCase
asing and VbStrConv.LowerCase only.
VbStrConv.Wide * Converts narrow (half-width) characters in the string to wide (full-width) characters.
VbStrConv.Narrow * Converts wide (full-width) characters in the string to narrow (half-width) characters.
The following are valid word separators for proper casing: Null (Chr$(0)), horizontal tab (Chr$(9)), line feed (Chr$(10)),
vertical tab (Chr$(11)), form feed (Chr$(12)), carriage return (Chr$(13)), space (single-byte character set) (Chr$(32)). The
actual value for a space, which can be full or half width, varies by country/region for East Asian cultures.
Exceptions
Exception type Error numbe Condition
r
ArgumentException 5 Unsupported LocaleID, Conversion < 0 or > 2048, or unsupported conversion for specified l
ocale.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The constants VbStrConv.Wide, VbStrConv.Narrow, VbStrConv.SimplifiedChinese, VbStrConv.TraditionalChinese,
VbStrConv.Katakana, and VbStrConv.Hiragana can cause run-time errors when used in locales where they do not apply,
but not always: the constants VbStrConv.Katakana and VbStrConv.Hiragana can be used in a non-Japanese system with
the Japanese Language Pack installed. In addition, use of the constants VbStrConv.Wide and VbStrConv.Narrow is
supported on any system with an East Asian language installed.
This function uses the application's culture information when manipulating the string so that the case changes are appropriate
for the locale in which the application is being used.
Security Note
If your application makes security decisions based on the result of a comparison or case-change operation, then the operatio
n should use the System.String.Compare(System.String,System.String,System.StringComparison) method, and pass Ordinal
or OrdinalIgnoreCase for the comparisonType argument. For more information, see
How Culture Affects Strings in Visual Basic.
Example
This example converts text into all lowercase letters.
VB
Dim sText As String = "Hello World"
' Returns "hello world".
Dim sNewText As String = StrConv(sText, VbStrConv.LowerCase)
StrDup Function
Returns a string or object consisting of the specified character repeated the specified number of times.
Parameters
Number
Required. Integer expression. The length to the string to be returned.
Character
Required. Any valid Char, String, or Object expression. Only the first character of the expression will be used. If Character is
of type Object, it must contain either a Char or a String value.
Exceptions
Exception type Error number Condition
ArgumentException 5 Number is less than 0 or Character type is not valid.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
This function returns a String made up of repeated characters. The character that makes up the string is the first character in
the Character argument, and it is duplicated Number number of times.
Example
This example uses the StrDup function to return a string of duplicated characters.
VB
Dim aString As String = "Wow! What a string!"
Dim aObject As New Object
Dim TestString As String
aObject = "This is a String contained within an Object"
' Returns "PPPPP"
TestString = StrDup(5, "P")
' Returns "WWWWWWWWWW"
TestString = StrDup(10, aString)
' Returns "TTTTTT"
TestString = CStr(StrDup(6, aObject))
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
SPC Function
ArgumentException
ArgumentNullException
Visual Basic Language Reference
Parameters
Expression
Required. String expression whose characters are to be reversed. If Expression is a zero-length string (""), a zero-length string
is returned.
Remarks
The StrReverse function returns a string that contains the same characters as Expression, but in the opposite order.
Example
VB
Dim TestString As String = "ABCDEFG"
' Returns "GFEDCBA".
Dim revString As String = StrReverse(TestString)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
InStrRev Function (Visual Basic)
Visual Basic Language Reference
Switch Function
Evaluates a list of expressions and returns an Object value corresponding to the first expression in the list that is True.
Parameters
VarExpr
Required. Object parameter array. Must have an even number of elements. You can supply a list of Object variables or
expressions separated by commas, or a single-dimensional array of Object elements.
Exceptions
Exception type Error number Condition
ArgumentException 5 Number of arguments is odd.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The argument supplied to VarExpr consists of paired expressions and values. The Switch function evaluates the odd-
numbered expressions from lowest to highest index in VarExpr, and returns the even-numbered value associated with the first
expression that evaluates to True. For example, if VarExpr(0) is True, Switch returns VarExpr(1), and if VarExpr(0) is False but
VarExpr(2) is True, Switch returns VarExpr(3), and so on.
If you do not supply the VarExpr argument, Switch returns Nothing.
Note
The expressions in the argument list can include function calls. As part of preparing the argument list for the call to Switch, t
he Visual Basic compiler calls every function in every expression. This means that you cannot rely on a particular function not
being called if an expression earlier in the argument list is True.
Example
The following example uses the Switch function to return the name of a language that matches the name of a city. It requires
that Option Strict be Off.
VB
Function matchLanguage(ByVal cityName As String) As String
Return CStr(Microsoft.VisualBasic.Switch( _
cityName = "London", "English", _
cityName = "Rome", "Italian", _
cityName = "Paris", "French"))
End Function
Because the System.Diagnostics namespace also contains a class called Switch, a call to the Switch function must be qualified
with the Microsoft.VisualBasic namespace.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Choose Function
IIf Function
Select...Case Statement (Visual Basic)
Concepts
Parameter Arrays
Visual Basic Language Reference
SYD Function
Returns a Double specifying the sum-of-years digits depreciation of an asset for a specified period.
Function SYD( _
ByVal Cost As Double, _
ByVal Salvage As Double, _
ByVal Life As Double, _
ByVal Period As Double _
) As Double
Parameters
Cost
Required. Double specifying the initial cost of the asset.
Salvage
Required. Double specifying the value of the asset at the end of its useful life.
Life
Required. Double specifying the length of the useful life of the asset.
Period
Required. Double specifying the period for which asset depreciation is calculated.
Exceptions
Exception type Error number Condition
ArgumentException 5 Salvage < 0, Period > Life, or Period <=0.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Life and Period arguments must be expressed in the same units. For example, if Life is given in months, Period must also
be given in months. All arguments must be positive numbers.
Example
This example uses the SYD function to return the depreciation of an asset for a specified period given the asset's initial cost
(InitCost), the salvage value at the end of the asset's useful life (SalvageVal), and the total life of the asset in years (LifeTime).
VB
Dim InitCost, SalvageVal, LifeTime, DepYear As Double
Dim Fmt As String = "###,##0.00"
' Use the SLN function to calculate the deprecation per year.
Dim SlnDepr As Double = SLN(InitCost, SalvageVal, LifeTime)
Dim msg As String = "The depreciation per year: " & Format(SlnDepr, Fmt)
msg &= vbCrLf & "Year" & vbTab & "Linear" & vbTab & "Doubling" & vbCrLf
' Use the SYD and DDB functions to calculate the deprecation for each year.
For DepYear = 1 To LifeTime
msg &= DepYear & vbTab & _
Format(SYD(InitCost, SalvageVal, LifeTime, DepYear), Fmt) & vbTab & _
Format(DDB(InitCost, SalvageVal, LifeTime, DepYear), Fmt) & vbCrLf
Next
MsgBox(msg)
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DDB Function
SLN Function
Financial Summary
ArgumentException
Visual Basic Language Reference
SystemTypeName Function
Returns a String value containing the system data type name of a variable.
Parameters
VbName
Required. A String variable containing a Visual Basic type name.
Remarks
SystemTypeName returns the fully qualified common language runtime (CLR) type name corresponding to the Visual Basic
type name. For example, if VbName contains "Date", SystemTypeName returns "System.DateTime". If SystemTypeName
does not recognize the value of VbName, it returns Nothing (not the string "Nothing").
Example
The following example uses the SystemTypeName function to return data type names for several variables.
VB
Dim vbLongName As String = "Long"
Dim vbDateName As String = "Date"
Dim vbBadName As String = "Number"
Dim testSysName As String
testSysName = SystemTypeName(vbLongName)
' The preceding call returns "System.Int64".
testSysName = SystemTypeName(vbDateName)
' The preceding call returns "System.DateTime".
testSysName = SystemTypeName(vbBadName)
' The preceding call returns Nothing.
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Data Type Summary (Visual Basic)
String Data Type (Visual Basic)
VbTypeName Function
Visual Basic Language Reference
TAB Function
Used with the Print or PrintLine functions to position output.
Parameters
Column
Optional. The column number moved to before displaying or printing the next expression in a list. If omitted, TAB moves the
insertion point to the beginning of the next print zone.
Remarks
If the current print position on the current line is greater than Column, TAB skips to the column value equal to Column on the
next output line. If Column is less than 1, TAB moves the print position to column 1. If Column is greater than the output line
width, TAB calculates the next print position using the formula:
Column Mod width
For example, if width is 80 and you specify TAB(90), the next print will start at column 10 (the remainder of 90/80). If Column
is less than the current print position, printing begins on the next line at the calculated print position. If the calculated print
position is greater than the current print position, printing begins at the calculated print position on the same line.
The leftmost print position on an output line is always 1. When you use the Print or PrintLine functions to print to files, the
rightmost print position is the current width of the output file, which you can set using the FileWidth function.
The TAB function can also be used with the WriteLine function. It cannot be used with System.Diagnostics.Debug.WriteLine or
System.Console.WriteLine.
Note
Make sure your tabular columns are wide enough to accommodate wide letters.
Example
This example uses the TAB function to position output in a file and in the Output window.
VB
FileOpen(1, "TESTFILE", OpenMode.Output) ' Open file for output.
' The second word prints at column 20.
Print(1, "Hello", TAB(20), "World.")
' If the argument is omitted, cursor is moved to the next print zone.
Print(1, "Hello", TAB(), "World")
FileClose(1)
Parameters
Hour
Required. Integer expression from 0 through 23. However, values outside this range are also accepted.
Minute
Required. Integer expression from 0 through 59. However, values outside this range are also accepted. The value of Minute
is added to the calculated hour, so a negative value specifies minutes before that hour.
Second
Required. Integer expression from 0 through 59. However, values outside this range are also accepted. The value of Second
is added to the calculated minute, so a negative value specifies seconds before that minute.
Exceptions
Exception type Error number Condition
ArgumentException 5 Argument is outside the range -2,147,483,648 through 2,147,483,647
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The following example demonstrates negative, zero, and positive argument values. The TimeSerial function returns a time
representing 15 minutes before three hours before noon, or 8:45:00 AM.
If either Minute or Second exceeds its normal range, it is applied to the next larger unit as appropriate. For example, if you
specify 75 minutes, it is evaluated as one hour and 15 minutes.
TimeSerial reduces the total seconds modulo 86,400, which is the number of seconds in a day. Therefore, the returned time is
always between 00:00:00 and 23:59:59.
The Date data type includes date components. TimeSerial sets all of these to 1, so the returned value represents the first day
of the year 1. However, if the values of the arguments cause the calculated time to exceed 24 hours, the day is incremented as
necessary. In the following example, the values of Hour and Minute result in a combined time of more than 24 hours.
If the values of the arguments result in a negative calculated time, the date information is set to 1/1/0001 and the time
information is adjusted to be between 00:00:00 and 23:59:59. However, if the calculated time is less than negative 24 hours, an
ArgumentOutOfRangeException error occurs.
Since every Date value is supported by a System.DateTime structure, its methods give you additional options in assembling a
Date value. For example, you can employ one of the overloaded DateTime constructors to populate a Date variable using the
desired combination of components. The following example sets newDateTime to May 6, 1978 at one tenth of a second before
8:30 in the morning:
Example
The following example uses the TimeSerial function to return a time for the specified hour, minute, and second.
VB
Dim thisTime As Date
thisTime = TimeSerial(16, 35, 17)
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateSerial Function (Visual Basic)
DateValue Function (Visual Basic)
Hour Function (Visual Basic)
Minute Function
Now Property
Second Function (Visual Basic)
TimeValue Function (Visual Basic)
Visual Basic Language Reference
Parameters
StringTime
Required. String expression representing a date/time value from 00:00:00 on January 1 of the year 1 through 23:59:59 on
December 31, 9999.
Exceptions
Exception type Error number Condition
InvalidCastException 13 StringTime includes invalid date information.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
You can enter valid times using a 12-hour or 24-hour clock. For example, "2:24 P.M." and "14:24" are both valid StringTime
arguments.
If the StringTime argument includes date information, TimeValue does not include it in the returned value. However, if
StringTime includes invalid date information, for example "January 32," an InvalidCastException error occurs.
Example
The following example uses the TimeValue function to convert a string to a time. You can also use date literals to directly
assign a time to a Date variable.
VB
Dim thisTime As Date
thisTime = TimeValue("4:35:17 PM")
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateSerial Function (Visual Basic)
DateValue Function (Visual Basic)
Hour Function (Visual Basic)
Minute Function
Now Property
Second Function (Visual Basic)
TimeSerial Function (Visual Basic)
DateTime
Visual Basic Language Reference
Parameters
str
Required. Any valid String expression.
Remarks
The LTrim, RTrim, and Trim functions remove spaces from the ends of strings. To remove other forms of white space, such as
tab characters, use the System.String.Trim method.
Example
This example uses the LTrim function to strip leading spaces and the RTrim function to strip trailing spaces from a string
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)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Left Function (Visual Basic)
Right Function (Visual Basic)
Trim
Visual Basic Language Reference
Parameters
VarName
Required. Object variable. If Option Strict is Off, you can pass a variable of any data type except a structure.
Remarks
The following table shows the String values returned by TypeName for different contents of VarName.
VarName contents String returned
16-bit True or False value type "Boolean"
Reference type pointing to a specialized object created from class objectclass "objectclass"
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Data Type Summary (Visual Basic)
IsArray Function (Visual Basic)
IsDate Function (Visual Basic)
IsDBNull Function
IsError Function
IsNothing Function
IsNumeric Function (Visual Basic)
IsReference Function
Visual Basic Language Reference
Parameters
Array
Required. Array of any data type. The array in which you want to find the highest possible subscript of a dimension.
Rank
Optional. Integer. The dimension for which the highest possible subscript is to be returned. Use 1 for the first dimension, 2
for the second, and so on. If Rank is omitted, 1 is assumed.
Return Value
Integer. The highest value the subscript for the specified dimension can contain. If Array has only one element, UBound
returns 0. If Array has no elements, for example if it is a zero-length string, UBound returns -1.
Exceptions
Exception type Error number Condition
ArgumentNullException 9 Array is Nothing
RankException 9 Rank is less than 1 or Rank is greater than the rank of Array.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Since array subscripts start at 0, the length of a dimension is greater by one than the highest available subscript for that
dimension.
For an array with the following dimensions, UBound returns the values in the following table:
UBound(a, 2) 5
UBound(a, 3) 4
You can use UBound to determine the total number of elements in an array, but you must adjust the value it returns to
account for the fact that the subscripts start at 0. The following example calculates the total size of the array a in the preceding
example:
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
LBound Function (Visual Basic)
Dim Statement (Visual Basic)
ReDim Statement (Visual Basic)
ArgumentException
RankException
Visual Basic Language Reference
Parameters
Value
Required. Any valid String or Char expression.
Remarks
Only lowercase letters are converted to uppercase; all uppercase letters and nonletter characters remain unchanged.
This function uses the application's culture information when manipulating the string so that the case changes are appropriate
for the locale in which the application is being used.
Security Note
If your application makes security decisions based on the result of a comparison or case-change operation, then the operatio
n should use the System.String.Compare(System.String,System.String,System.StringComparison) method, and pass Ordinal
or OrdinalIgnoreCase for the comparisonType argument. For more information, see
How Culture Affects Strings in Visual Basic.
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)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
LCase Function (Visual Basic)
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference
Val Function
Returns the numbers contained in a string as a numeric value of appropriate type.
Parameters
Expression, InputStr
Required. Any valid String expression, Object variable, or Char value. If Expression is of type Object, its value must be
convertible to String or an ArgumentException error occurs.
Exceptions
Exception type Error number Condition
OverflowException 6 InputStr is too large.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Val function stops reading the string at the first character it cannot recognize as part of a number. Symbols and characters
that are often considered parts of numeric values, such as dollar signs and commas, are not recognized. However, the function
recognizes the radix prefixes &O (for octal) and &H (for hexadecimal). Blanks, tabs, and linefeed characters are stripped from the
argument.
The following call returns the value 1615198.
Val("&HFFFF")
Note
The Val function recognizes only the period (.) as a valid decimal separator. When different decimal separators are used, as i
n international applications, use CDbl or CInt instead to convert a string to a number. To convert the string representation of
a number in a particular culture to a numeric value, use the numeric type's Parse(String, IFormatProvider) method. For e
xample, use System.Double.Parse(System.String,System.IFormatProvider) when converting a string to a Double.
Example
The following example uses the Val function to return the numbers contained in each string. Val stops converting at the first
character that cannot be interpreted as a numeric digit, numeric modifier, numeric punctuation, or white space.
VB
Dim valResult As Double
' The following line of code sets valResult to 2457.
valResult = Val("2457")
' The following line of code sets valResult to 2457.
valResult = Val(" 2 45 7")
' The following line of code sets valResult to 24.
valResult = Val("24 and 57")
Requirements
Namespace: Microsoft.VisualBasic
Module: Conversion
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Str Function
Type Conversion Functions
OverflowException
InvalidCastException
ArgumentException
Visual Basic Language Reference
Parameters
VarName
Required. Object variable. If Option Strict is Off, you can pass a variable of any data type except a structure.
Remarks
The integer value returned by VarType is a member of the VariantType Enumeration.
The following table shows the values returned by VarType for special cases of VarName.
Data type represented by VarNam Value returned by VarType
e
Nothing (Visual Basic) VariantType.Object
DBNull VariantType.Null
Enumeration Underlying data type (SByte, Byte, Short, UShort, Integer, UInteger, Long, or ULong
)
Exception VariantType.Error
Unknown VariantType.Object
Example
The following example uses the VarType function to return data type classification information about several variables.
VB
Dim testString As String = "String for testing"
Dim testObject As New Object
Dim testNumber, testArray(5) As Integer
Dim testVarType As VariantType
testVarType = VarType(testVarType)
' Returns VariantType.Integer.
testVarType = VarType(testString)
' Returns VariantType.String.
testVarType = VarType(testObject)
' Returns VariantType.Object.
testVarType = VarType(testNumber)
' Returns VariantType.Integer.
testVarType = VarType(testArray)
' Returns the bitwise OR of VariantType.Array and VariantType.Integer.
VbTypeName Function
Returns a String value containing the Visual Basic data type name of a variable.
Parameters
UrtName
Required. String variable containing a type name used by the common language runtime.
Remarks
VbTypeName returns the Visual Basic type name corresponding to the common language runtime type name. For example, if
UrtName contains "Int32" or "System.Int32", VbTypeName returns "Integer". If VbTypeName does not recognize the value
of UrtName, it returns Nothing (not the string "Nothing").
The type name in UrtName can be obtained from various sources, for example from the Name property in the MemberInfo
array of the Type class.
Example
The following example uses the VbTypeName function to return data type names for several variables.
VB
Dim sysDateName As String = "System.DateTime"
Dim sysShortName As String = "Int16"
Dim sysBadName As String = "Nonsense"
Dim testVbName As String
testVbName = VbTypeName(sysDateName)
' Returns "Date".
testVbName = VbTypeName(sysShortName)
' Returns "Short".
testVbName = VbTypeName(sysBadName)
' Returns Nothing.
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Data Type Summary (Visual Basic)
String Data Type (Visual Basic)
SystemTypeName Function
Visual Basic Language Reference
Parameters
DateValue
Required. Date value for which you want to determine the day of the week.
DayOfWeek
Optional. A value chosen from the FirstDayOfWeek enumeration that specifies the first day of the week. If not specified,
FirstDayOfWeek.Sunday is used.
Settings
The DayOfWeek argument can have one of the following settings.
Enumeration value Value Description
FirstDayOfWeek.System 0 First day of week specified in system settings
FirstDayOfWeek.Tuesday 3 Tuesday
FirstDayOfWeek.Wednesday 4 Wednesday
FirstDayOfWeek.Thursday 5 Thursday
FirstDayOfWeek.Friday 6 Friday
FirstDayOfWeek.Saturday 7 Saturday
Exceptions
Exception type Error number Condition
ArgumentException 5 DayOfWeek is less than 0 or more than 7.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The value returned by the Weekday function is the day of the week that the DateValue corresponds to, relative to the first day
of the week defined by the DayOfWeek value. For example, if the date refers to a Wednesday and the first day of the week is
specified as Monday, the function returns 3.
Note
Weekday uses the current calendar setting from the CurrentCulture property of the CultureInfo class in the
System.Globalization namespace. The default CurrentCulture values are determined by Control Panel settings.
Example
The following example uses the Weekday function to obtain the day of the week from a specified date.
VB
Dim oldDate As Date
Dim oldWeekDay As Integer
oldDate = #2/12/1969#
oldWeekDay = Weekday(oldDate)
' oldWeekDay now contains 4 because thisDate represents a Wednesday.
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Month Function (Visual Basic)
Now Property
WeekdayName Function (Visual Basic)
Year Function (Visual Basic)
DatePart Function (Visual Basic)
DateTime
Visual Basic Language Reference
Parameters
Weekday
Required. Integer. The numeric designation for the weekday, from 1 through 7; 1 indicates the first day of the week and 7
indicates the last day of the week. The identities of the first and last days depend on the setting of FirstDayOfWeekValue.
Abbreviate
Optional. Boolean value that indicates if the weekday name is to be abbreviated. If omitted, the default is False, which
means the weekday name is not abbreviated.
FirstDayOfWeekValue
Optional. A value chosen from the FirstDayOfWeek enumeration that specifies the first day of the week. If not specified,
FirstDayOfWeek.System is used.
Settings
The FirstDayOfWeekValue argument can have one of the following settings.
Enumeration value Value Description
FirstDayOfWeek.System 0 First day of week specified in system settings (default)
FirstDayOfWeek.Sunday 1 Sunday
FirstDayOfWeek.Tuesday 3 Tuesday
FirstDayOfWeek.Wednesday 4 Wednesday
FirstDayOfWeek.Thursday 5 Thursday
FirstDayOfWeek.Friday 6 Friday
FirstDayOfWeek.Saturday 7 Saturday
Exceptions
Exception type Error numb Condition
er
ArgumentException 5 Weekday is less than 1 or greater than 7, or FirstDayOfWeekValue is less than 0 or greater t
han 7.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The string returned by WeekdayName depends not only on the input arguments, but also on the Regional Options settings
specified in the Windows Control Panel.
Note
WeekdayName uses the current calendar setting from the CurrentCulture property of the CultureInfo class in the
System.Globalization namespace. The default CurrentCulture values are determined by Control Panel settings.
Example
The following example uses the Weekday function to obtain the day of the week from a specified date, and then the
WeekDayName function to obtain the name of the weekday from its number.
VB
Dim oldDate As Date
Dim oldWeekDayName As String
oldDate = #2/12/1969#
oldWeekDayName = WeekdayName(Weekday(oldDate))
' oldWeekDayName now contains "Wednesday".
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Month Function (Visual Basic)
Now Property
Weekday Function (Visual Basic)
MonthName Function (Visual Basic)
Year Function (Visual Basic)
DatePart Function (Visual Basic)
DateTime
Visual Basic Language Reference
Parameters
FileNumber
Required. An Integer expression containing any valid file number.
Output
Optional. One or more comma-delimited expressions to write to a file.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Write and WriteLine functions are provided for backward compatibility and may have an impact on performance. For
non-legacy applications, the My.Computer.FileSystem object provides better performance. For more information, see
File Access with Visual Basic.
If you omit Output, a blank line is printed to the file. Multiple expressions can be separated with a comma.
Unlike the Print function, the Write function inserts commas between items and quotation marks around strings as they are
written to the file. You do not have to put explicit delimiters in the list. When Write is used to write data to a file, only numeric,
Boolean, date, null, and Error data formats are supported. The following universal assumptions are followed so the data can
always be read and correctly interpreted using Input, regardless of locale:
Numeric data is always written using the period as the decimal separator.
For Boolean data, either #TRUE# or #FALSE# is printed. The True and False keywords are not translated, regardless of
locale.
Date data is written to the file using the universal date format. When either the date or the time component is missing or
zero, only the part provided gets written to the file.
Nothing is written to the file if Output data is empty. However, for null data, #NULL# is written.
For Error data, the output appears as #ERROR errorcode#. The Error keyword is not translated, regardless of locale.
WriteLine inserts a newline character (that is, a carriage return/line feed, or Chr(13) + Chr(10)), after it has written the final
character in Output to the file.
You can embed quotation marks in a string by using double quotation marks, or "". For example,
VB
Dim x As String = "Double quotation marks aren't ""difficult"" to handle."
returns a string with the value of Double quotation marks aren't "difficult" to handle.
Writing to a file with the Write or WriteLine functions requires Append access from the FileIOPermissionAccess
enumeration. For more information, see FileIOPermissionAccess Enumeration.
Example
This example uses the Write function to write raw data to a sequential file.
VB
FileOpen(1, "TESTFILE", OpenMode.Output) ' Open file for output.
Write(1, "This is a test.") ' Print text to file.
WriteLine(1) ' Print blank line to file.
WriteLine(1, "Zone 1", TAB(), "Zone 2") ' Print in two print zones.
WriteLine(1, "Hello", " ", "World") ' Separate strings with space.
WriteLine(1, SPC(5), "5 leading spaces ") ' Print five leading spaces.
WriteLine(1, TAB(10), "Hello") ' Print word at column 10.
' Assign Boolean, Date, and Error values.
Dim aBool As Boolean
Dim aDate As DateTime
aBool = False
aDate = DateTime.Parse("February 12, 1969")
' Dates and Booleans are translated using locale settings of
' your system.
WriteLine(1, aBool, " is a Boolean value")
WriteLine(1, aDate, " is a date")
FileClose(1) ' Close file.
Parameters
DateValue
Required. Date value from which you want to extract the year.
Remarks
You can also obtain the year by calling DatePart and specifying DateInterval.Year for the Interval argument.
Example
The following example uses the Year function to obtain the year from a specified date. In the development environment, the
date literal is displayed in short date format using the locale settings of your code.
VB
Dim thisDate As Date
Dim thisYear As Integer
thisDate = #2/12/1969#
thisYear = Year(thisDate)
' thisYear now contains 1969.
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Month Function (Visual Basic)
Now Property
Weekday Function (Visual Basic)
DatePart Function (Visual Basic)
DateTime
ArgumentOutOfRangeException
Visual Basic Language Reference
A-E Keywords
The following table contains a listing of Visual Basic language keywords.
Alias
Indicates that an external procedure has another name in its DLL.
Remarks
The Alias keyword can be used in this context:
Declare Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
AddHandler
AddHandler associates an event with an event handler at run time, or declares what code to execute when adding an event
handler.
Remarks
The AddHandler keyword is used in these contexts:
Event Statement
The AddHandler keyword declares a custom AddHandler accessor.
AddHandler Statement
The AddHandler keyword associates an event with an event handler.
See Also
Tasks
How to: Declare Events That Avoid Blocking
How to: Declare Events That Conserve Memory Use
Visual Basic Language Reference
Ansi
Specifies that Visual Basic should marshal all strings to American National Standards Institute (ANSI) values regardless of the
name of the external procedure being declared.
When you call a procedure defined outside your project, the Visual Basic compiler does not have access to the information it
needs to call the procedure correctly. This information includes where the procedure is located, how it is identified, its calling
sequence and return type, and the string character set it uses. The Declare Statement creates a reference to an external
procedure and supplies this necessary information.
The charsetmodifier part in the Declare statement supplies the character set information for marshaling strings during a call
to the external procedure. It also affects how Visual Basic searches the external file for the external procedure name. The Ansi
modifier specifies that Visual Basic should marshal all strings to ANSI values and should look up the procedure without
modifying its name during the search.
If no character set modifier is specified, Ansi is the default.
Remarks
The Ansi modifier can be used in this context:
Declare Statement
Smart Device Developer Notes
This keyword is not supported.
See Also
Reference
Auto
Unicode (Visual Basic)
Visual Basic Language Keywords
Visual Basic Language Reference
As (Visual Basic)
Introduces an As clause, which identifies a data type in a declaration statement or a constraint list on a generic type parameter.
Remarks
The As keyword can be used in these contexts:
Class Statement
Const Statement
Declare Statement
Delegate Statement
Dim Statement
Enum Statement
Event Statement
For...Next Statements
For Each...Next Statements
Function Statement
Interface Statement
Operator Statement
Property Statement
Structure Statement
Sub Statement
Try...Catch...Finally Statements
See Also
Tasks
How to: Create a New Variable
Reference
Type List
Visual Basic Language Keywords
Concepts
Data Types in Visual Basic
Variable Declaration in Visual Basic
Generic Types in Visual Basic
Visual Basic Language Reference
Assembly
Specifies that an attribute at the beginning of a source file applies to the entire assembly.
Remarks
Many attributes pertain to an individual programming element, such as a class or property. You apply such an attribute by
attaching the attribute block, within angle brackets (< >), directly to the declaration statement.
If an attribute pertains not only to the following element but to the entire assembly, you place the attribute block at the
beginning of the source file and identify the attribute with the Assembly keyword. If it applies to the current assembly module,
you use the Module keyword.
You can also apply an attribute to an assembly in the AssemblyInfo.vb file, in which case you do not have to use an attribute
block in your main source-code file.
See Also
Reference
Module (Visual Basic)
Concepts
Application of Attributes
Visual Basic Language Reference
Auto
Specifies that Visual Basic should marshal strings according to .NET Framework rules based on the external name of the
external procedure being declared.
When you call a procedure defined outside your project, the Visual Basic compiler does not have access to the information it
needs to call the procedure correctly. This information includes where the procedure is located, how it is identified, its calling
sequence and return type, and the string character set it uses. The Declare Statement creates a reference to an external
procedure and supplies this necessary information.
The charsetmodifier part in the Declare statement supplies the character set information for marshaling strings during a call
to the external procedure. It also affects how Visual Basic searches the external file for the external procedure name. The Auto
modifier specifies that Visual Basic should marshal strings according to .NET Framework rules, and that it should determine the
base character set of the run-time platform and possibly modify the external procedure name if the initial search fails. For
more information, see "Character Sets" in Declare Statement.
If no character set modifier is specified, Ansi is the default.
Remarks
The Auto modifier can be used in this context:
Declare Statement
Smart Device Developer Notes
This keyword is not supported.
See Also
Reference
Ansi
Unicode (Visual Basic)
Visual Basic Language Keywords
Visual Basic Language Reference
Binary
Sets the string comparison method to a strict binary sort order.
Remarks
The Option Compare statement must appear in a source file before any other statements. It affects string comparison for all
code generated by that source file.
When to Use Binary
You might need to compare string elements based on their true binary value, particularly if the strings can contain characters
that are not to be interpreted as text. In such a case you do not want to bias comparisons with alphabetic equivalences such as
case insensitivity. To specify a pure binary comparison, set Option Compare to Binary.
The Binary keyword can be used in this context:
Option Compare Statement
See Also
Reference
Text
Visual Basic Language Keywords
Visual Basic Language Reference
ByRef
Specifies that an argument is passed in such a way that the called procedure can change the value of a variable underlying the
argument in the calling code.
Remarks
The ByRef modifier can be used in these contexts:
Declare Statement
Function Statement
Sub Statement
See Also
Reference
Visual Basic Language Keywords
Concepts
Argument Passing By Value and By Reference
Visual Basic Language Reference
ByVal
Specifies that an argument is passed in such a way that the called procedure or property cannot change the value of a variable
underlying the argument in the calling code.
Remarks
The ByVal modifier can be used in these contexts:
Declare Statement
Function Statement (Visual Basic)
Operator Statement
Property Statement
Sub Statement (Visual Basic)
See Also
Reference
Visual Basic Language Keywords
Concepts
Argument Passing By Value and By Reference
Visual Basic Language Reference
Custom
Specifies that an event has additional, specialized code for adding handlers, removing handlers, and raising events.
Remarks
The Custom keyword can be used in this context:
Event Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
DirectCast
Introduces a type conversion operation based on inheritance or implementation.
Remarks
DirectCast does not use the Visual Basic run-time helper routines for conversion, so it can provide somewhat better
performance than CType when converting to and from data type Object.
You use the DirectCast keyword the same way you use the CType Function and the TryCast keyword. You supply an
expression as the first argument and a type to convert it to as the second argument. DirectCast requires an inheritance or
implementation relationship between the data types of the two arguments. This means that one type must inherit from or
implement the other.
Errors and Failures
DirectCast generates a compiler error if it detects that no inheritance or implementation relationship exists. But the lack of a
compiler error does not guarantee a successful conversion. If the desired conversion is narrowing, it could fail at run time. If
this happens, the runtime throws an InvalidCastException error.
Conversion Keywords
A comparison of the type conversion keywords is as follows.
Keyword Data types Argument relationship Run-time failure
CType Function Any data types Widening or narrowing conversion must be defined between the t Throws InvalidCastExce
wo data types ption
DirectCast Any data types One type must inherit from or implement the other type Throws InvalidCastExce
ption
TryCast Reference types One type must inherit from or implement the other type Returns
only Nothing (Visual Basic)
Example
The following example demonstrates two uses of DirectCast, one that fails at run time and one that succeeds.
VB
Dim q As Object = 2.37
Dim i As Integer = CType(q, Integer)
' The following conversion fails at run time
Dim j As Integer = DirectCast(q, Integer)
Dim f As New System.Windows.Forms.Form
Dim c As System.Windows.Forms.Control
' The following conversion succeeds.
c = DirectCast(f, System.Windows.Forms.Control)
In the preceding example, the run-time type of q is Double. CType succeeds because Double can be converted to Integer.
However, the first DirectCast fails at run time because the run-time type of Double has no inheritance relationship with
Integer, even though a conversion exists. The second DirectCast succeeds because it converts from type Form to type Control,
from which Form inherits.
See Also
Concepts
Widening and Narrowing Conversions
Implicit and Explicit Conversions
Visual Basic Language Reference
Each
Specifies the loop variable to be used in a For Each loop.
Remarks
The Each keyword is used in this context:
For Each...Next Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
End AddHandler
End Class
End Enum
End Event
End Function
End Get
End If
End Interface
End Module
End Namespace
End Operator
End Property
End RaiseEvent
End RemoveHandler
End Select
End Set
End Structure
End Sub
End SyncLock
End Try
End While
End With
Parts
End
Required. Terminates the definition of the programming element.
AddHandler
Required to terminate an AddHandler accessor begun by a matching AddHandler statement in a custom Event Statement.
Class
Required to terminate a class definition begun by a matching Class Statement (Visual Basic).
Enum
Required to terminate an enumeration definition begun by a matching Enum Statement (Visual Basic).
Event
Required to terminate a Custom event definition begun by a matching Event Statement.
Function
Required to terminate a Function procedure definition begun by a matching Function Statement (Visual Basic). If execution
encounters an End Function statement, control returns to the calling code.
Get
Required to terminate a Property procedure definition begun by a matching Get Statement. If execution encounters an End
Get statement, control returns to the statement requesting the property's value.
If
Required to terminate an If...Then...Else block definition begun by a matching If statement. See
If...Then...Else Statement (Visual Basic).
Interface
Required to terminate an interface definition begun by a matching Interface Statement (Visual Basic).
Module
Required to terminate a module definition begun by a matching Module Statement.
Namespace
Required to terminate a namespace definition begun by a matching Namespace Statement.
Operator
Required to terminate an operator definition begun by a matching Operator Statement.
Property
Required to terminate a property definition begun by a matching Property Statement.
RaiseEvent
Required to terminate a RaiseEvent accessor begun by a matching RaiseEvent statement in a custom Event Statement.
RemoveHandler
Required to terminate a RemoveHandler accessor begun by a matching RemoveHandler statement in a custom
Event Statement.
Select
Required to terminate a Select...Case block definition begun by a matching Select statement. See
Select...Case Statement (Visual Basic).
Set
Required to terminate a Property procedure definition begun by a matching Set Statement (Visual Basic). If execution
encounters an End Set statement, control returns to the statement setting the property's value.
Structure
Required to terminate a structure definition begun by a matching Structure Statement.
Sub
Required to terminate a Sub procedure definition begun by a matching Sub Statement (Visual Basic). If execution encounters
an End Sub statement, control returns to the calling code.
SyncLock
Required to terminate a SyncLock block definition begun by a matching SyncLock statement. See SyncLock Statement.
Try
Required to terminate a Try...Catch...Finally block definition begun by a matching Try statement. See
Try...Catch...Finally Statement (Visual Basic).
While
Required to terminate a While loop definition begun by a matching While statement. See
While...End While Statement (Visual Basic).
With
Required to terminate a With block definition begun by a matching With statement. See
With...End With Statement (Visual Basic).
Remarks
The End Statement, without an additional keyword, terminates execution immediately.
When preceded by a number sign (#), the End keyword terminates a preprocessing block introduced by the corresponding
directive.
#End
Required. Terminates the definition of the preprocessing block.
#ExternalSource
Required to terminate an external source block begun by a matching #ExternalSource Directive.
#If
Required to terminate a conditional compilation block begun by a matching #If directive. See #If...Then...#Else Directives.
#Region
Required to terminate a source region block begun by a matching #Region Directive.
Smart Device Developer Notes
The End statement, without an additional keyword, is not supported.
See Also
Reference
End Statement
Visual Basic Language Reference
F-O Keywords
The following table contains a listing of Visual Basic language keywords.
Is Lib Loop Me
Global
Allows you to access a .NET Framework programming element when you have blocked it with your namespace structure.
Remarks
If you have defined a nested hierarchy of namespaces, code inside that hierarchy might be blocked from accessing the System
namespace of the .NET Framework. The following example illustrates a hierarchy in which the SpecialSpace.System
namespace blocks access to System.
Namespace SpecialSpace
Namespace System
Class abc
Function getValue() As System.Int32
Dim n As System.Int32
Return n
End Function
End Class
End Namespace
End Namespace
As a result, the Visual Basic compiler cannot successfully resolve the reference to System.Int32, because SpecialSpace.System
does not define Int32. You can use the Global keyword to start the qualification chain at the outermost level of the .NET
Framework class library. This allows you to specify the System namespace or any other namespace in the class library. The
following example illustrates this.
Namespace SpecialSpace
Namespace System
Class abc
Function getValue() As Global.System.Int32
Dim n As Global.System.Int32
Return n
End Function
End Class
End Namespace
End Namespace
You can use Global to access other root-level namespaces, such as Microsoft.VisualBasic, and any namespace associated with
your project.
The Global keyword can be used in these contexts:
Class Statement (Visual Basic)
Const Statement (Visual Basic)
Declare Statement
Delegate Statement
Dim Statement (Visual Basic)
Enum Statement (Visual Basic)
Event Statement
For...Next Statement (Visual Basic)
For Each...Next Statement (Visual Basic)
Function Statement (Visual Basic)
Interface Statement (Visual Basic)
Operator Statement
Property Statement
Structure Statement
Sub Statement (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
Using Statement (Visual Basic)
See Also
Reference
Namespace Statement
.NET Framework Class Library Reference
System
Microsoft.VisualBasic
Visual Basic Language Reference
Handles
Declares that a procedure handles a specified event.
Parts
proceduredeclaration
The Sub procedure declaration for the procedure that will handle the event.
eventlist
List of the events for proceduredeclaration to handle. The events must be raised by either the base class for the current class,
or by an object declared using the WithEvents keyword.
Remarks
Use the Handles keyword at the end of a procedure declaration to cause it to handle events raised by an object variable
declared using the WithEvents keyword. The Handles keyword can also be used in a derived class to handle events from a
base class.
The signature of the procedure must match the signatures of each event in eventlist.
The Handles keyword and the AddHandler statement both allow you to specify that particular procedures handle particular
events, but there are differences. Use the Handles keyword when defining a procedure to specify that it handles a particular
event. The AddHandler statement connects procedures to events at run time. For more information, see
AddHandler Statement.
For custom events, the application invokes the event's AddHandler accessor when it adds the procedure as an event handler.
For more information on custom events, see Event Statement.
Example
VB
Public Class ContainerClass
' Module or class level declaration.
WithEvents Obj As New Class1
The following example demonstrates how a derived class can use the Handles statement to handle an event from a base class.
VB
Public Class BaseClass
' Declare an event.
Event Ev1()
End Class
Class DerivedClass
Inherits BaseClass
Sub TestEvents() Handles MyBase.Ev1
' Add code to handle this event.
End Sub
End Class
See Also
Reference
WithEvents
AddHandler Statement
RemoveHandler Statement
Event Statement
RaiseEvent Statement
Concepts
Events and Event Handlers
Visual Basic Language Reference
In (Visual Basic)
Specifies the group that the loop variable is to traverse in a For Each loop.
Remarks
The In keyword can be used in this context:
For Each...Next Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
Is (Visual Basic)
Introduces an Is clause that makes a comparison.
Remarks
The Is keyword is used with the TypeOf keyword in a TypeOf...Is expression to test whether the run-time type of an
expression is compatible with a given type.
The Is keyword can be used in these contexts:
Is Operator
Select...Case Statement
See Also
Reference
TypeOf Operator (Visual Basic)
Visual Basic Language Keywords
Visual Basic Language Reference
Lib
Introduces a Lib clause, which identifies the external file (DLL or code resource) containing an external procedure.
Remarks
The Lib keyword can be used in this context:
Declare Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
Loop
Terminates a loop introduced with a Do statement.
Remarks
The Loop keyword can be used in this context:
Do...Loop Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
Me
Provides a way to refer to the specific instance of a class or structure in which the code is currently executing.
Remarks
The Me keyword behaves like either an object variable or a structure variable referring to the current instance. Using Me is
particularly useful for passing information about the currently executing instance of a class or structure to a procedure in
another class, structure, or module. For example, suppose you have the following procedure in a module.
You can call this procedure and pass the current instance of the Form class as an argument using the following statement.
ChangeFormColor(Me)
MustInherit
Specifies that a class can be used only as a base class and that you cannot create an object directly from it.
Remarks
The purpose of a base class (also known as an abstract class) is to define functionality that is common to all the classes derived
from it. This saves the derived classes from having to redefine the common elements. In some cases, this common functionality
is not complete enough to make a usable object, and each derived class defines the missing functionality. In such a case, you
want the consuming code to create objects only from the derived classes. You use MustInherit on the base class to enforce
this.
Another use of a MustInherit class is to restrict a variable to a set of related classes. You can define a base class and derive all
these related classes from it. The base class does not need to provide any functionality common to all the derived classes, but it
can serve as a filter for assigning values to variables. If your consuming code declares a variable as the base class, Visual Basic
allows you to assign only an object from one of the derived classes to that variable.
The .NET Framework defines several MustInherit classes, among them Array, Enum, and ValueType. ValueType is an example
of a base class that restricts a variable. All value types derive from ValueType. If you declare a variable as ValueType, you can
assign only value types to that variable.
Rules
Declaration Context. You can use MustInherit only in a Class statement.
Combined Modifiers. You cannot specify MustInherit together with NotInheritable in the same declaration.
Example
The following example illustrates both forced inheritance and forced overriding. The base class shape defines a variable
acrossLine. The classes circle and square derive from shape. They inherit the definition of acrossLine, but they must define
the function area because that calculation is different for each kind of shape.
VB
Public MustInherit Class shape
Public acrossLine As Double
Public MustOverride Function area() As Double
End Class
Public Class circle : Inherits shape
Public Overrides Function area() As Double
Return Math.PI * acrossLine
End Function
End Class
Public Class square : Inherits shape
Public Overrides Function area() As Double
Return acrossLine * acrossLine
End Function
End Class
Public Class consumeShapes
Public Sub makeShapes()
Dim shape1, shape2 As shape
shape1 = New circle
shape2 = New square
End Sub
End Class
You can declare shape1 and shape2 to be of type shape. However, you cannot create an object from shape because it lacks the
functionality of the function area and is marked MustInherit.
Because they are declared as shape, the variables shape1 and shape2 are restricted to objects from the derived classes circle
and square. Visual Basic does not allow you to assign any other object to these variables, which gives you a high level of type
safety.
Usage
The MustInherit modifier can be used in this context:
Class Statement
See Also
Reference
Inherits Statement
NotInheritable
Visual Basic Language Keywords
Other Resources
Inheritance in Visual Basic
Visual Basic Language Reference
MustOverride
Specifies that a property or procedure is not implemented in this class and must be overridden in a derived class before it can
be used.
Remarks
You can use MustOverride only in a property or procedure declaration statement. The property or procedure specifying
MustOverride must be a member of a class, and the class must be marked MustInherit.
Rules
Incomplete Declaration. When you specify MustOverride, you do not supply any additional lines of code for the
property or procedure, not even the End Function, End Property, or End Sub statement.
Combined Modifiers. You cannot specify MustOverride together with NotOverridable, Overridable, or Shared in
the same declaration.
Shadowing and Overriding. Both shadowing and overriding redefine an inherited element, but there are significant
differences between the two approaches. For more information, see Shadowing in Visual Basic.
Alternate Terms. An element that cannot be used except in an override is sometimes called a pure virtual element.
The MustOverride modifier can be used in these contexts:
Function Statement (Visual Basic)
Property Statement
Sub Statement (Visual Basic)
See Also
Reference
NotOverridable
Overridable
Overrides
MustInherit
Visual Basic Language Keywords
Concepts
Shadowing in Visual Basic
Visual Basic Language Reference
MyBase
Provides a way to refer to the base class of the current class instance.
Remarks
The MyBase keyword behaves like an object variable referring to the base class of the current instance of a class. MyBase is
commonly used to access base class members that are overridden or shadowed in a derived class. In particular, MyBase.New
is used to explicitly call a base class constructor from a derived class constructor.
It is invalid to use MyBase to call MustOverride base methods.
For more information and an example, see How to: Access a Variable Hidden by a Derived Class.
See Also
Reference
Me
MyClass
New (Visual Basic)
Concepts
Inheritance Basics
Visual Basic Language Reference
MyClass
Provides a way to refer to the current class instance members without them being replaced by any derived class overrides.
Remarks
The MyClass keyword behaves like an object variable referring to the current instance of a class as originally implemented.
MyClass is similar to Me, but every method and property call on MyClass is treated as if the method or property were
NotOverridable. Therefore, the method or property is not affected by overriding in a derived class. The following example
compares Me and MyClass.
Class baseClass
Public Overridable Sub testMethod()
MsgBox("Base class string")
End Sub
Public Sub useMe()
' The following call uses the calling class's version, even if
' that version is an override.
Me.testMethod()
End Sub
Public Sub useMyClass()
' The following call uses this version and not any override.
MyClass.testMethod()
End Sub
End Class
Class derivedClass : Inherits baseClass
Public Overrides Sub testMethod()
MsgBox("Derived class string")
End Sub
End Class
Class testClasses
Sub startHere()
Dim testObj As derivedClass = New derivedClass()
' The following call displays "Derived class string".
testObj.useMe()
' The following call displays "Base class string".
testObj.useMyClass()
End Sub
End Class
Even though derivedClass overrides testMethod, the MyClass keyword in useMyClass nullifies the effects of overriding, and
the compiler resolves the call to the base class version of testMethod.
You cannot use MyClass inside a Shared (Visual Basic) method, but you can use it inside an instance method to access a
shared member of a class.
See Also
Reference
Me
MyBase
Concepts
Inheritance Basics
Visual Basic Language Reference
Narrowing
Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the
possible values of the original class or structure.
Converting with the Narrowing Keyword
The conversion procedure must specify Public Shared in addition to Narrowing.
Narrowing conversions do not always succeed at run time, and can fail or incur data loss. Examples are Long to Integer,
String to Date, and a base type to a derived type. This last conversion is narrowing because the base type might not contain all
the members of the derived type and thus is not an instance of the derived type.
If Option Strict is On, the consuming code must use CType for all narrowing conversions.
The Narrowing keyword can be used in this context:
Operator Statement
See Also
Tasks
How to: Define an Operator
Reference
Operator Statement
Widening
CType Function
Option Strict Statement
Concepts
Widening and Narrowing Conversions
Visual Basic Language Reference
Since arrays are classes, New can create a new array instance, as shown in the following example.
The common language runtime (CLR) throws an OutOfMemoryException error if there is insufficient memory to create the
new instance.
The New keyword can be used in these contexts:
Dim Statement (Visual Basic)
Of
See Also
Reference
Visual Basic Language Keywords
Type List
Using Constructors and Destructors
OutOfMemoryException
Concepts
Generic Types in Visual Basic
Object Lifetime: How Objects Are Created and Destroyed
Visual Basic Language Reference
Next
Terminates a loop that is iterated with different values of a loop variable, or specifies that execution should continue with the
statement following the statement that generated an error.
Remarks
The Next keyword can be used in these contexts:
For...Next Statement
For Each...Next Statement
On Error Statement
Resume Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
If the variable is of a reference type — that is, an object variable — Nothing means the variable is not associated with any
object. The following example demonstrates this.
When you assign Nothing to an object variable, it no longer refers to any object instance. If the variable had previously
referred to an instance, setting it to Nothing does not terminate the instance itself. The instance is terminated, and the
memory and system resources associated with it are released, only after the garbage collector (GC) detects that there are no
active references remaining.
See Also
Reference
Dim Statement (Visual Basic)
Concepts
Object Lifetime: How Objects Are Created and Destroyed
Lifetime in Visual Basic
Visual Basic Language Reference
NotInheritable
Specifies that a class cannot be used as a base class.
Remarks
Alternate Terms. A class that cannot be inherited is sometimes called a sealed class.
The NotInheritable modifier can be used in this context:
Class Statement (Visual Basic)
See Also
Reference
Inherits Statement
MustInherit
Visual Basic Language Keywords
Visual Basic Language Reference
NotOverridable
Specifies that a property or procedure cannot be overridden in a derived class.
Remarks
NotOverridable is the default setting for a property or procedure that does not itself override a base class property or
procedure.
An element that cannot be overridden is sometimes called a sealed element.
Rules
Declaration Context. You can use NotOverridable only in a property or procedure declaration statement. You can
specify NotOverridable only on a property or procedure that overrides another property or procedure, that is, only in
combination with Overrides.
Combined Modifiers. You cannot specify NotOverridable together with MustOverride, Overridable, or Shared in
the same declaration.
The NotOverridable modifier can be used in these contexts:
Function Statement (Visual Basic)
Property Statement
Sub Statement (Visual Basic)
See Also
Reference
MustOverride
Overridable
Overrides
Visual Basic Language Keywords
Concepts
Shadowing in Visual Basic
Visual Basic Language Reference
Of
Introduces an Of clause, which identifies a type parameter on a generic class, structure, interface, delegate, or procedure. For
information on generic types, see Generic Types in Visual Basic.
Using the Of Keyword
The following code example uses the Of keyword to define the outline of a class that takes two type parameters. It constrains
the keyType parameter by the IComparable interface, which means the consuming code must supply a type argument that
implements IComparable. This is necessary so that the add procedure can call the
System.IComparable.CompareTo(System.Object) method. For more information on constraints, see Type List.
If you complete the preceding class definition, you can construct a variety of dictionary classes from it. The types you supply
to entryType and keyType determine what type of entry the class holds and what type of key it associates with each entry.
Because of the constraint, you must supply to keyType a type that implements IComparable.
The following code example creates an object that holds String entries and associates an Integer key with each one. Integer
implements IComparable and therefore satisfies the constraint on keyType.
Off
Turns a compiler option off.
Remarks
The Off keyword can be used in these contexts:
Option Explicit Statement
Option Strict Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
On
Introduces a response to a run-time error or turns a compiler option on.
Remarks
The On keyword is used in these contexts:
On Error Statement
Option Explicit Statement
Option Strict Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
Overloads
Specifies that a property or procedure redeclares one or more existing properties or procedures with the same name.
Remarks
Overloading is the practice of supplying more than one definition for a given property or procedure name in the same scope.
Redeclaring a property or procedure with a different signature is sometimes called hiding by signature.
Rules
Declaration Context. You can use Overloads only in a property or procedure declaration statement.
Combined Modifiers. You cannot specify Overloads together with Shadows in the same procedure declaration.
Required Differences. The signature in this declaration must be different from the signature of every property or
procedure that it overloads. The signature comprises the property or procedure name together with the following:
the number of parameters
the order of the parameters
the data types of the parameters
the number of type parameters (for a generic procedure)
the return type (only for a conversion operator procedure)
All overloads must have the same name, but each must differ from all the others in one or more of the preceding
respects. This allows the compiler to distinguish which version to use when code calls the property or procedure.
Disallowed Differences. Changing one or more of the following is not valid for overloading a property or procedure,
because they are not part of the signature:
whether or not it returns a value (for a procedure)
the data type of the return value (except for a conversion operator)
the names of the parameters or type parameters
the constraints on the type parameters (for a generic procedure)
parameter modifier keywords (such as ByRef or Optional)
property or procedure modifier keywords (such as Public or Shared)
Optional Modifier. You do not have to use the Overloads modifier when you are defining multiple overloaded
properties or procedures in the same class. However, if you use Overloads in one of the declarations, you must use it in
all of them.
Shadowing and Overloading. Overloads can also be used to shadow an existing member, or set of overloaded
members, in a base class. When you use Overloads in this way, you declare the property or method with the same name
and the same parameter list as the base class member, and you do not supply the Shadows keyword.
The Overloads modifier can be used in these contexts:
Function Statement
Operator Statement
Property Statement
Sub Statement
See Also
Tasks
How to: Define a Conversion Operator
Reference
Shadows
Concepts
Procedure Overloading
Generic Types in Visual Basic
Operator Procedures
Visual Basic Language Reference
Overridable
Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.
Remarks
Overridable is the default setting for a property or procedure that itself overrides a base class property or procedure.
Both shadowing and overriding redefine an inherited element, but there are significant differences between the two
approaches. For more information, see Shadowing in Visual Basic.
An element that can be overridden is sometimes called a virtual element. If it can be overridden, but does not have to be, it is
sometimes also called a concrete element.
Rules
Declaration Context. You can use Overridable only in a property or procedure declaration statement.
Combined Modifiers. You cannot specify Overridable together with MustOverride, NotOverridable, or Shared in
the same declaration. Because an overriding element is implicitly overridable, you cannot combine Overridable with
Overrides.
The Overridable modifier can be used in these contexts:
Function Statement (Visual Basic)
Property Statement
Sub Statement (Visual Basic)
See Also
Reference
MustOverride
NotOverridable
Overrides
Visual Basic Language Keywords
Concepts
Shadowing in Visual Basic
Visual Basic Language Reference
Overrides
Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class.
Remarks
Rules
Declaration Context. You can use Overrides only in a property or procedure declaration statement.
Combined Modifiers. You cannot specify Overrides together with Shadows or Shared in the same declaration.
Because an overriding element is implicitly overridable, you cannot combine Overridable with Overrides.
Matching Signatures. The signature of this declaration must exactly match the signature of the property or procedure
that it overrides. This means the parameter lists must have the same number of parameters, in the same order, with the
same data types.
In addition to the signature, the overriding declaration must also exactly match the following:
The access level
The return type, if any
Generic Signatures. For a generic procedure, the signature includes the number of type parameters. Therefore, the
overriding declaration must match the base class version in that respect as well.
Additional Matching. In addition to matching the signature of the base class version, this declaration must also match
it in the following respects:
Access-level modifier (such as Public (Visual Basic))
Passing mechanism of each parameter (ByVal or ByRef)
Constraint lists on each type parameter of a generic procedure
Shadowing and Overriding. Both shadowing and overriding redefine an inherited element, but there are significant
differences between the two approaches. For more information, see Shadowing in Visual Basic.
The Overrides modifier can be used in these contexts:
Function Statement
Property Statement
Sub Statement
See Also
Reference
MustOverride
NotOverridable
Overridable
Visual Basic Language Keywords
Type List
Concepts
Shadowing in Visual Basic
Generic Types in Visual Basic
Visual Basic Language Reference
P-Z Keywords
The following table contains a listing of Visual Basic language keywords.
WithEvents WriteOnly
Smart Device Developer Notes
The following is not supported in smart device applications: Unicode.
See Also
Reference
A-E Keywords
F-O Keywords
Other Resources
Visual Basic Reference
Visual Basic Language Reference
ParamArray
Specifies that a procedure parameter takes an optional array of elements of the specified type. ParamArray can be used only
on the last parameter of a parameter list.
Remarks
ParamArray allows you to pass an arbitrary number of arguments to the procedure. A ParamArray parameter is always
declared using ByVal.
You can supply one or more arguments to a ParamArray parameter by passing an array of the appropriate data type, a
comma-separated list of values, or nothing at all. For details, see "Calling a ParamArray" in Parameter Arrays.
Security Note
Whenever you deal with an array which can be indefinitely large, there is a risk of overrunning some internal capacity of you
r application. If you accept a parameter array from the calling code, you should test its length and take appropriate steps if it i
s too large for your application.
Parts
attrlist
Optional. List of attributes that apply to this class or structure. You must enclose the Attribute List in angle brackets (< >).
accessmodifier
Optional. Specifies what code can access this class or structure. See Access Levels in Visual Basic.
Shadows
Optional. See Shadows.
MustInherit
Optional. See MustInherit.
NotInheritable
Optional. See NotInheritable.
name
Required. Name of this class or structure. Must match the name defined in all other partial declarations of the same class or
structure.
Of
Optional. Specifies that this is a generic class or structure. See Generic Types in Visual Basic.
typelist
Required if you use Of. See Type List.
Inherits
Optional. See Inherits Statement.
classname
Required if you use Inherits. The name of the class or interface from which this class derives.
Implements
Optional. See Implements Statement.
interfacenames
Required if you use Implements. The names of the interfaces this class or structure implements.
variabledeclarations
Optional. Statements which declare additional variables and events for the class or structure.
proceduredeclarations
Optional. Statements which declare and define additional procedures for the class or structure.
End Class or End Structure
Ends this partial Class or Structure definition.
Remarks
You can divide the definition of a class or structure among several declarations with the Partial keyword. You can use as many
partial declarations as desired, in as many different source files as desired. However, all the declarations must be in the same
assembly and the same namespace.
Note
Visual Basic uses partial-class definitions to separate generated code from user-authored code in separate source files. For ex
ample, the Windows Form Designer defines partial classes for controls such as Form. You should not modify the generated
code in these controls.
Under normal circumstances, you should not split the development of a single class or structure across two or more
declarations. Therefore, in most cases you do not need the Partial keyword.
All the rules for class and structure creation, such as those for modifier usage and inheritance, apply when creating a partial
class or structure.
Best Practices
Keyword Usage. For readability, every partial declaration of a class or structure should include the Partial keyword. The
compiler allows at most one partial declaration to omit the keyword; if two or more omit it the compiler signals an error.
Behavior
Union of Declarations. The compiler treats the class or structure as the union of all its partial declarations. Every
modifier from every partial definition applies to the entire class or structure, and every member from every partial
definition is available to the entire class or structure.
Type Promotion Not Allowed For Partial Types in Modules. If a partial definition is inside a module, type promotion
of that class or structure is automatically defeated. In such a case, a set of partial definitions can cause unexpected results
and even compiler errors. For more information, see Type Promotion.
The compiler merges partial definitions only when their fully qualified paths are identical.
The Partial keyword can be used in these contexts:
Class Statement
Structure Statement
Example
The following example splits the definition of class sampleClass into two declarations, each of which defines a different Sub
procedure.
VB
Partial Public Class sampleClass
Public Sub sub1()
End Sub
End Class
Partial Public Class sampleClass
Public Sub sub2()
End Sub
End Class
The two partial definitions in the preceding example could be in the same source file or in two different source files.
See Also
Reference
Class Statement (Visual Basic)
Structure Statement
Shadows
Concepts
Type Promotion
Generic Types in Visual Basic
Visual Basic Language Reference
Preserve
Prevents the contents of an array from being cleared when the array is redimensioned.
Remarks
The Preserve keyword can be used in this context:
ReDim Statement (Visual Basic)
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
RaiseEvent
Raises an event at run time, or declares what code to execute when raising an event.
Remarks
The RaiseEvent keyword can be used in these contexts:
Event Statement
The RaiseEvent keyword declares a custom RaiseEvent accessor.
RaiseEvent Statement
The RaiseEvent keyword raises an event.
See Also
Tasks
How to: Raise an Event (Visual Basic)
How to: Declare Events That Avoid Blocking
How to: Declare Events That Conserve Memory Use
Visual Basic Language Reference
When initialized, the array pointed to by characterArray() holds "x", "y", and "z". Because the variable characterArray is
ReadOnly, you cannot change its value once it is initialized; that is, you cannot assign a new array to it. However, you can
change the values of one or more of the array members. Following a call to the procedure changeArrayElement, the array
pointed to by characterArray() holds "x", "M", and "z".
Note that this is similar to declaring a procedure parameter to be ByVal, which prevents the procedure from changing the
calling argument itself but allows it to change its members.
Example
The following example defines a ReadOnly property for the date on which an employee was hired. The class stores the
property value internally as a Private variable, and only code inside the class can change that value. However, the property is
Public, and any code that can access the class can read the property.
VB
Class employee
' Only code inside class employee can change the value of hireDateValue.
Private hireDateValue As Date
' Any code that can access class employee can read property dateHired.
Public ReadOnly Property dateHired() As Date
Get
Return hireDateValue
End Get
End Property
End Class
RemoveHandler
Removes the association between an event and an event handler, or declares which code to execute when adding an event
handler.
Remarks
The RemoveHandler keyword can be used in these contexts:
Event Statement
The RemoveHandler keyword declares a custom RemoveHandler accessor.
RemoveHandler Statement
The RemoveHandler keyword removes the association between an event and an event handler.
See Also
Tasks
How to: Declare Events That Avoid Blocking
How to: Declare Events That Conserve Memory Use
Visual Basic Language Reference
Resume
Specifies where execution should continue after an error has been handled.
Remarks
The Resume keyword can be used in these contexts:
On Error Statement (Visual Basic)
Resume Statement
See Also
Reference
Visual Basic Language Keywords
Other Resources
Exception and Error Handling in Visual Basic
Visual Basic Language Reference
Shadows
Specifies that a declared programming element redeclares and hides an identically named element, or set of overloaded
elements, in a base class.
Remarks
The main purpose of shadowing (which is also known as hiding by name) is to preserve the definition of your class members.
The base class might undergo a change that creates an element with the same name as one you have already defined. If this
happens, the Shadows modifier forces references through your class to be resolved to the member you defined, instead of to
the new base class element.
Both shadowing and overriding redefine an inherited element, but there are significant differences between the two
approaches. For more information, see Shadowing in Visual Basic.
Rules
Declaration Context. You can use Shadows only at class level. This means the declaration context for a Shadows
element must be a class, and cannot be a source file, namespace, interface, module, structure, or procedure.
You can declare only one shadowing element in a single declaration statement.
Combined Modifiers. You cannot specify Shadows together with Overloads, Overrides, or Static in the same
declaration.
Element Types. You can shadow any kind of declared element with any other kind. If you shadow a property or
procedure with another property or procedure, the parameters and the return type do not have to match those in the
base class property or procedure.
Accessing. The shadowed element in the base class is normally unavailable from within the derived class that shadows
it. However, the following considerations apply.
If the shadowing element is not accessible from the code referring to it, the reference is resolved to the shadowed
element. For example, if a Private element shadows a base class element, code that does not have permission to
access the Private element accesses the base class element instead.
If you shadow an element, you can still access the shadowed element through an object declared with the type of
the base class. You can also access it through MyBase.
The Shadows modifier can be used in these contexts:
Class Statement
Const Statement
Declare Statement
Delegate Statement
Dim Statement
Enum Statement
Event Statement
Function Statement
Interface Statement
Property Statement
Structure Statement
Sub Statement
See Also
Reference
Shared (Visual Basic)
Static (Visual Basic)
Private (Visual Basic)
MyBase
MustOverride
NotOverridable
Overloads
Overridable
Overrides
Concepts
Shadowing in Visual Basic
Visual Basic Language Reference
Implicit Sharing. You cannot use the Shared modifier in a Const Statement (Visual Basic), but constants are implicitly
shared. Similarly, you cannot declare a member of a module or an interface to be Shared, but they are implicitly shared.
Behavior
Storage. A shared variable or event is stored in memory only once, no matter how many or few instances you create of
its class or structure. Similarly, a shared procedure or property holds only one set of local variables.
Accessing through an Instance Variable. It is possible to access a shared element by qualifying it with the name of a
variable that contains a specific instance of its class or structure. Although this usually works as expected, the compiler
generates a warning message and makes the access through the class or structure name instead of the variable.
Accessing through an Instance Expression. If you access a shared element through an expression that returns an
instance of its class or structure, the compiler makes the access through the class or structure name instead of evaluating
the expression. This produces unexpected results if you intended the expression to perform other actions as well as
returning the instance. The following example illustrates this.
Sub main()
shareTotal.total = 10
' The preceding line is the preferred way to access total.
Dim instanceVar As New shareTotal
instanceVar.total += 100
' The preceding line generates a compiler warning message and
' accesses total through class shareTotal instead of through
' the variable instanceVar. This works as expected and adds
' 100 to total.
returnClass().total += 1000
' The preceding line generates a compiler warning message and
' accesses total through class shareTotal instead of calling
' returnClass(). This adds 1000 to total but does not work as
' expected, because the MsgBox in returnClass() does not run.
MsgBox("Value of total is " & CStr(shareTotal.total))
End Sub
Public Function returnClass() As shareTotal
MsgBox("Function returnClass() called")
Return New shareTotal
End Function
Public Class shareTotal
Public Shared total As Integer
End Class
In the preceding example, the compiler generates a warning message both times the code accesses the shared variable
total through an instance. In each case it makes the access directly through the class shareTotal and does not make use
of any instance. In the case of the intended call to the procedure returnClass, this means it does not even generate a call
to returnClass, so the additional action of displaying "Function returnClass() called" is not performed.
The Shared modifier can be used in these contexts:
Dim Statement
Event Statement
Function Statement
Operator Statement
Property Statement
Sub Statement
See Also
Reference
Shadows
Static (Visual Basic)
Concepts
Lifetime in Visual Basic
Procedures in Visual Basic
Shared Members in Visual Basic
Other Resources
Structures: Your Own Data Types
Understanding Classes
Visual Basic Language Reference
The Static variable totalSales is initialized to 0 only once. Each time you enter updateSales, totalSales still has the most
recent value you calculated for it.
The Static modifier can be used in this context:
Dim Statement (Visual Basic)
See Also
Reference
Shadows
Shared (Visual Basic)
Concepts
Lifetime in Visual Basic
Variable Declaration in Visual Basic
Other Resources
Structures: Your Own Data Types
Understanding Classes
Visual Basic Language Reference
Step
Specifies an increment value for a loop counter.
Remarks
The Step keyword can be used in this context:
For...Next Statement (Visual Basic)
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
Text
Sets the string comparison method to sort equivalent text characters as equal.
Remarks
The Option Compare statement must appear in a source file before any other statements. It affects string comparison for all
code generated by that source file.
When to Use Text
If your strings contain all text characters, you often want to compare them, taking into account alphabetic equivalences such as
case insensitivity and closely related letters. For example, you might want to consider A and a to be equal, and Ä and ä to come
before B and b. To specify a text comparison, set Option Compare to Text.
The Text keyword can be used in this context:
Option Compare Statement
See Also
Reference
Binary
Visual Basic Language Keywords
Visual Basic Language Reference
Then
Introduces a statement block to be compiled or executed if a tested condition is true.
Remarks
The Then keyword can be used in these contexts:
#If...Then...#Else Directive
If...Then...Else Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
To
Separates the beginning and ending values of a loop counter or of a value match range.
Remarks
The To keyword can be used in these contexts:
For...Next Statement
Select...Case Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
TryCast
Introduces a type conversion operation that does not throw an exception.
Remarks
If an attempted conversion fails, CType and DirectCast both throw an InvalidCastException error. This can adversely affect the
performance of your application. TryCast returns Nothing (Visual Basic), so that instead of having to handle a possible
exception, you need only test the returned result against Nothing.
You use the TryCast keyword the same way you use the CType Function and the DirectCast keyword. You supply an
expression as the first argument and a type to convert it to as the second argument. TryCast operates only on reference types,
such as classes and interfaces. It requires an inheritance or implementation relationship between the two types. This means
that one type must inherit from or implement the other.
Errors and Failures
TryCast generates a compiler error if it detects that no inheritance or implementation relationship exists. But the lack of a
compiler error does not guarantee a successful conversion. If the desired conversion is narrowing, it could fail at run time. If
this happens, TryCast returns Nothing (Visual Basic).
Conversion Keywords
A comparison of the type conversion keywords is as follows.
Keyword Data types Argument relationship Run-time failure
CType Function Any data types Widening or narrowing conversion must be defined between the t Throws InvalidCastExce
wo data types ption
DirectCast Any data types One type must inherit from or implement the other type Throws InvalidCastExce
ption
TryCast Reference types One type must inherit from or implement the other type Returns
only Nothing (Visual Basic)
Example
The following example shows how to use TryCast.
VB
Function PrintTypeCode(ByVal obj As Object) As String
Dim objAsConvertible As IConvertible = TryCast(obj, IConvertible)
If objAsConvertible Is Nothing Then
Return obj.ToString() & " does not implement IConvertible"
Else
Return "Type code is " & objAsConvertible.GetTypeCode()
End If
End Function
See Also
Concepts
Widening and Narrowing Conversions
Implicit and Explicit Conversions
Visual Basic Language Reference
Until
Specifies a condition that terminates the execution of a Do loop.
Remarks
The Until keyword can be used in this context:
Do...Loop Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
When
Adds a conditional test to a Catch statement.
Remarks
The When keyword can be used in this context:
Try...Catch...Finally Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference
Widening
Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the
original class or structure.
Converting with the Widening Keyword
The conversion procedure must specify Public Shared in addition to Widening.
Widening conversions always succeed at run time and never incur data loss. Examples are Single to Double, Char to String,
and a derived type to its base type. This last conversion is widening because the derived type contains all the members of the
base type and thus is an instance of the base type.
The consuming code does not have to use CType for widening conversions, even if Option Strict is On.
The Widening keyword can be used in this context:
Operator Statement
See Also
Tasks
How to: Define an Operator
Reference
Operator Statement
Narrowing
CType Function
Option Strict Statement
Concepts
Widening and Narrowing Conversions
Visual Basic Language Reference
WithEvents
Specifies that one or more declared member variables refer to an instance of a class that can raise events.
Remarks
When a variable is defined using WithEvents, you can declaratively specify that a method handles the variable's events using
the Handles keyword.
You can use WithEvents only at class or module level. This means the declaration context for a WithEvents variable must be
a class or module and cannot be a source file, namespace, structure, or procedure.
You cannot use WithEvents on a structure member.
You can declare only individual variables—not arrays—with WithEvents.
Rules
Element Types. You must declare WithEvents variables to be object variables so that they can accept class instances.
However, you cannot declare them as Object. You must declare them as the specific class that can raise the events.
The WithEvents modifier can be used in this context: Dim Statement (Visual Basic)
See Also
Reference
Handles
Visual Basic Language Keywords
Concepts
WithEvents and the Handles Clause
Other Resources
Events in Visual Basic
Visual Basic Language Reference
WriteOnly
Specifies that a property can be written but not read.
Remarks
Rules
Declaration Context. You can use WriteOnly only at module level. This means the declaration context for a WriteOnly
property must be a class, structure, or module, and cannot be a source file, namespace, or procedure.
You can declare a property as WriteOnly, but not a variable.
When to Use WriteOnly
Sometimes you want the consuming code to be able to set a value but not discover what it is. For example, sensitive data, such
as a social registration number or a password, needs to be protected from access by any component that did not set it. In these
cases, you can use a WriteOnly property to set the value.
Security Note
When you define and use a WriteOnly property, consider the following additional protective measures:
Overriding. If the property is a member of a class, allow it to default to NotOverridable, and do not declare it
Overridable or MustOverride. This prevents a derived class from making undesired access through an override.
Access Level. If you hold the property's sensitive data in one or more variables, declare them Private (Visual Basic) so
that no other code can access them.
Encryption. Store all sensitive data in encrypted form rather than in plain text. If malicious code somehow gains access
to that area of memory, it is more difficult to make use of the data. Encryption is also useful if it is necessary to serialize
the sensitive data.
Resetting. When the class, structure, or module defining the property is being terminated, reset the sensitive data to
default values or to other meaningless values. This gives extra protection when that area of memory is freed for general
access.
Persistence. Do not persist any sensitive data, for example on disk, if you can avoid it. Also, do not write any sensitive
data to the Clipboard.
The WriteOnly modifier can be used in this context:
Property Statement
See Also
Reference
ReadOnly (Visual Basic)
Private (Visual Basic)
Visual Basic Language Keywords
Visual Basic Language Reference
vbYesNo vbYesNoCancel
See Also
Reference
AppWinStyle Enumeration
BuiltInRole Enumeration
CallType Enumeration
CompareMethod Enumeration
DateFormat Enumeration
DateInterval Enumeration
DueDate Enumeration
FileAttribute Enumeration
FirstDayOfWeek Enumeration
FirstWeekOfYear Enumeration
MsgBoxResult Enumeration
MsgBoxStyle Enumeration
OpenAccess Enumeration
OpenMode Enumeration
OpenShare Enumeration
Print and Display Constants
TriState Enumeration
VariantType Enumeration
VbStrConv Enumeration
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
Tab VerticalTab
See Also
Reference
Print and Display Constants
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
See Also
Reference
Conversion Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
WeekDayName Year
Example
This example uses the Today property to return the current system date.
See Also
Reference
Dates and Times Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
Raise Source
Example
This example uses the properties of the Err object in constructing an error-message dialog box. Notice what happens when you
use the Clear method first: When you then generate a Visual Basic error with the Raise method, Visual Basic's default values
become the properties of the Err object.
See Also
Reference
Err Object (Visual Basic)
Conversion Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
Write WriteLine
Example
This example uses the GetAttr function to determine the attributes of a file and directory or folder.
VB
Dim MyAttr As FileAttribute
' Assume file TESTFILE is normal and readonly.
MyAttr = GetAttr("C:\TESTFILE.txt") ' Returns vbNormal.
SYD
Example
This example uses the Rate function to calculate the interest rate of a loan, given the total number of payments (TotPmts), the
amount of the loan payment (Payment), the present value or principal of the loan (PVal), the future value of the loan (FVal), a
number that indicates whether the payment is due at the beginning or end of the payment period (PayType), and an
approximation of the expected interest rate (Guess).
VB
Sub TestRate()
Dim PVal, Payment, TotPmts, APR As Double
Dim PayType As DueDate
MsgBox("Your interest rate is " & Format(CInt(APR), Fmt) & " percent.")
End Sub
See Also
Reference
Financial Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
See Also
Reference
ScriptEngine Property
ScriptEngineBuildVersion Property
ScriptEngineMajorVersion Property
ScriptEngineMinorVersion Property
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
See Also
Reference
Information and Interaction Summary
Data Types Summary
Declarations and Constants Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
Shell Switch
Example
The following example uses the Shell function to run an application specified by the user. Specifying
Microsoft.VisualBasic.AppWinStyle.NormalFocus as the second argument opens the application in normal size and gives it the
focus.
See Also
Reference
Information and Interaction Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
See Also
Reference
String Manipulation Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
See Also
Reference
Math Summary
Derived Math Functions (Visual Basic)
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference
Once you have created a collection, you can do any of the following:
Add an element with the Add Method.
Remove an element with the Remove Method.
Remove all elements with the Clear Method.
Find out how many elements the collection contains with the Count Property.
Check whether a specific element is present with the Contains Method.
Return a specific element from the collection with the Item Property.
Iterate through the entire collection with the For Each...Next Statement (Visual Basic).
Note
Although the Visual Basic Collection object has functionality identical to the Collection object in Visual Basic 6.0, the t
wo cannot interoperate in a COM environment.
Caution
Iterating through a Visual Basic Collection is not a thread-safe procedure. Even if the collection is synchronized, other t
hreads can still modify the collection, causing the enumerator to throw an exception. To guarantee thread safety during
enumeration, either lock the collection or catch the exceptions resulting from changes made by other threads. For more
information on locking a programming element, see SyncLock Statement.
Example
The following example creates the Collection object names and a dialog box with which a user can add objects (names) to the
collection. It then displays the names in the collection, and finally empties the collection without disposing of the Collection
object itself.
To see how this works, choose the Add Class command from the Project menu and declare a public variable called
instanceName at the module level of nameClass (type Public instanceName) to hold the names of each instance. Leave the
default name as nameClass. Copy and paste the following code into the General section of another module, and then start it
with the statement classNamer in another procedure. (This example works only with host applications that support classes.)
VB
Public Class nameClass
Public instanceName As String
End Class
Sub classNamer()
' Create a Visual Basic Collection object.
Dim names As New Microsoft.VisualBasic.Collection()
Dim key As Integer
Dim msg As String
Dim name As String
Dim nameList As String = ""
' 1. Get names from the user to add to the collection.
Do
Dim inst As New nameClass()
key += 1
msg = "Please enter a name for this object." & vbCrLf _
& "Press Cancel to see names in collection."
name = InputBox(msg, "Name the Collection items")
inst.instanceName = name
' If user entered a name, add it to the collection.
If inst.instanceName <> "" Then
names.Add(inst, CStr(key))
End If
Loop Until name = ""
' 2. Create and display a list of names from the collection.
For Each oneInst As nameClass In names
nameList &= oneInst.instanceName & vbCrLf
Next oneInst
MsgBox(nameList, , "Instance Names in names Collection")
' 3. Remove elements from the collection without disposing of the collection.
For count As Integer = 1 To names.Count
names.Remove(1)
' Since Visual Basic collections are reindexed automatically,
' remove the first member on each iteration.
Next count
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object Members
GetEnumerator Method (Collection Object)
Visual Basic Language Reference
Item Property Read-only. Returns a specific element of a Visual Basic Collection object either by position or by key.
Methods
Method Description
Add Method Adds an element to a Visual Basic Collection object.
Clear Method Removes all elements from a Visual Basic Collection object.
Contains Method (Collection Object) Returns a Boolean indicating whether a Visual Basic Collection object contains an elem
ent with a specific key.
GetEnumerator Method Returns an enumerator object for iterating over the collection.
Parameters
Item
Required. An object of any type that specifies the element to add to the collection.
Key
Optional. A unique String expression that specifies a key string that can be used instead of a positional index to access this
new element in the collection.
Before
Optional. An expression that specifies a relative position in the collection. The element to be added is placed in the collection
before the element identified by the Before argument. If Before is a numeric expression, it must be a number from 1 through
the value of the collection's Count Property (Collection Object). If Before is a String expression, it must correspond to the key
string specified when the element being referred to was added to the collection. You cannot specify both Before and After.
After
Optional. An expression that specifies a relative position in the collection. The element to be added is placed in the collection
after the element identified by the After argument. If After is a numeric expression, it must be a number from 1 through the
value of the collection's Count property. If After is a String expression, it must correspond to the key string specified when
the element referred to was added to the collection. You cannot specify both Before and After.
Exceptions/Error Codes
Exception type Error number Condition
ArgumentException 5 Both Before and After are specified.
The Before or After argument does not refer to an existing element of the collection.
The specified Key already exists.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Before or After argument must refer to an existing element of the collection; otherwise, an error occurs.
An error also occurs if a specified Key value matches the key for an existing element of the collection.
Example
The following example uses the Add method to add child objects — instances of a class called child containing a Public
property name — to a collection called family. To see how this works, create a Form with two Button controls and set their Text
properties to Add and List. Add the child class definition and the family declaration to the form code. Modify the _Click
event handlers for the Add and List buttons as shown. The Add button allows you to add children. The List button displays the
names of all the children.
VB
Public Class child
Public name As String
Sub New(ByVal newName As String)
name = newName
End Sub
End Class
' Create a Collection object.
Private family As New Collection()
Private Sub addChild_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim newName As String
newName = InputBox("Name of new family member: ")
If newName <> "" Then
family.Add(New child(newName), newName)
End If
End Sub
Private Sub listChild_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
For Each aChild As child In family
MsgBox(aChild.name)
Next
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Module: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Item Property (Collection Object)
Remove Method (Collection Object)
Visual Basic Language Reference
Remarks
The Clear method empties the collection and resets its Count property to 0.
Example
VB
Dim customers As New Microsoft.VisualBasic.Collection()
' Insert code that adds customers to collection.
customers.Clear()
Requirements
Namespace: Microsoft.VisualBasic
Module: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Item Property (Collection Object)
Count Property (Collection Object)
Contains Method (Collection Object)
Add Method (Collection Object)
Remove Method (Collection Object)
Visual Basic Language Reference
Parameters
Key
Required. A String expression that specifies the key for which to search the elements of the collection.
Exceptions/Error Codes
Exception type Error number Condition
ArgumentException 5 The specified Key is Nothing.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Contains returns True if the collection contains an element with a key exactly matching Key. Otherwise, Contains returns
False.
A Visual Basic Collection can hold some elements that have keys and other elements without keys. This depends on whether
the call to the Add Method (Collection Object) supplies an argument to the optional Key parameter.
Example
VB
Dim customers As New Microsoft.VisualBasic.Collection()
Dim accountNumber As String = "1234"
' Insert code that obtains new customer objects.
' Use the new customer's account number as the key.
customers.Add(newCustomer, accountNumber)
' The preceding statements can be repeated for several customers.
Dim searchNumber As String = "1234"
' Insert code to obtain an account number to search for.
If customers.Contains(searchNumber) Then
MsgBox("The desired customer is in the collection.")
Else
MsgBox("The desired customer is not in the collection.")
End If
If you intend to search the collection for elements using their keys, remember to supply the Key argument every time you call
the Add method.
Requirements
Namespace: Microsoft.VisualBasic
Module: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Item Property (Collection Object)
Count Property (Collection Object)
Add Method (Collection Object)
Remove Method (Collection Object)
Clear Method (Collection Object)
Visual Basic Language Reference
Remarks
Use the Count property to determine the number of elements in a Collection object.
Example
This example illustrates the use of the Count property to display the number of elements in a Collection Object (Visual Basic)
in the variable birthdays.
VB
Dim birthdays As New Collection()
birthdays.Add(New DateTime(2001, 1, 12), "Bill")
birthdays.Add(New DateTime(2001, 1, 13), "Joe")
birthdays.Add(New DateTime(2001, 1, 14), "Mike")
birthdays.Add(New DateTime(2001, 1, 15), "Pete")
... MsgBox("Number of birthdays in collection: " & CStr(birthdays.Count))
The Collection object is one-based, which means that the index values of the elements range from 1 through the value of the
Count property.
Requirements
Namespace: Microsoft.VisualBasic
Class: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Add Method (Collection Object)
Item Property (Collection Object)
Remove Method (Collection Object)
Visual Basic Language Reference
Remarks
The For Each...Next Statement (Visual Basic) calls GetEnumerator to obtain an enumerator object to support iteration over a
collection's elements. Normally, you use a For Each...Next loop to traverse a collection or array, and you do not need to call
GetEnumerator explicitly.
If you need closer control over the iteration than the For Each...Next statements provide, you can use the GetEnumerator
method to perform a customized traversal. The following are some cases in which you might need to do this.
You might want to return to the beginning of the collection and start the iteration again before it is finished.
You might want to skip over one or more elements for a variety of reasons.
You might need to change the elements of the collection in the middle of a traversal. In this case you must obtain a new
enumerator object because the previous one is invalidated.
Example
The following example shows how to use GetEnumerator to retrieve all the elements of a Collection object.
VB
Dim customers As New Collection
' Insert code to add elements to the customers collection.
Dim custEnum As IEnumerator = customers.GetEnumerator()
custEnum.Reset()
Dim thisCustomer As Object
While custEnum.MoveNext()
thisCustomer = custEnum.Current()
' Insert code to process this element of the collection.
End While
GetEnumerator constructs and returns an enumerator object, which implements the IEnumerator interface of the
System.Collections namespace. The enumerator object exposes the Current property and the MoveNext and Reset methods.
For more information, see For Each...Next Statement (Visual Basic).
Requirements
Namespace: Microsoft.VisualBasic
Module: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Visual Basic Language Reference
Parameters
Key
A unique String expression that specifies a key string that can be used, instead of a positional index, to access an element of
the collection. Key must correspond to the Key argument specified when the element was added to the collection.
Index
(A) A numeric expression that specifies the position of an element of the collection. Index must be a number from 1 through
the value of the collection's Count Property (Collection Object). Or (B) An Object expression that specifies the position or key
string of an element of the collection.
Exceptions
Exception type Error number Condition
ArgumentException 5 Key is invalid or does not match an existing element of the collection.
Index cannot be interpreted as character or numeric data.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If Index is of type Object, the Item property attempts to treat it as a String, Char, Char array, or integer value. If Item cannot
convert Index to String or Integer, it throws an ArgumentException exception.
The Item property is the default property for a collection. Therefore, the following lines of code are equivalent.
MsgBox(CStr(customers.Item(1)))
MsgBox(CStr(customers(1)))
Example
The following example uses the Item property to retrieve a reference to an object in a collection. It creates birthdays as a
Collection object and then retrieves the object representing Bill's birthday, using the key "Bill" as the Index argument.
VB
Dim birthdays As New Collection()
birthdays.Add(New DateTime(2001, 1, 12), "Bill")
birthdays.Add(New DateTime(2001, 1, 13), "Joe")
birthdays.Add(New DateTime(2001, 1, 14), "Mike")
birthdays.Add(New DateTime(2001, 1, 15), "Pete")
... Dim aBirthday As DateTime
aBirthday = birthdays.Item("Bill")
MsgBox(CStr(aBirthday))
aBirthday = birthdays("Bill")
MsgBox(CStr(aBirthday))
Note that the first call explicitly specifies the Item property, but the second does not. Both calls work because the Item
property is the default property for a Collection object.
Requirements
Namespace: Microsoft.VisualBasic
Module: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Add Method (Collection Object)
Count Property (Collection Object)
Remove Method (Collection Object)
Visual Basic Language Reference
Parameters
Key
A unique String expression that specifies a key string that can be used, instead of a positional index, to access an element of
the collection. Key must correspond to the Key argument specified when the element was added to the collection.
Index
A numeric expression that specifies the position of an element of the collection. Index must be a number from 1 through the
value of the collection's Count Property (Collection Object).
Exceptions
Exception type Error number Condition
ArgumentException 5 Key is invalid or not specified.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
When Remove deletes an element from a collection, it decrements the collection's Count Property (Collection Object) by one.
It also decrements the Index value of every element that formerly followed the deleted element in the collection.
If an element was added to the collection without a Key, you must use its Index to remove it.
Example
This example illustrates the use of the Remove method to remove objects from a Collection Object (Visual Basic) in the
variable birthdays.
VB
Dim birthdays As New Collection()
birthdays.Add(New DateTime(2001, 1, 12), "Bill")
birthdays.Add(New DateTime(2001, 1, 13), "Joe")
birthdays.Add(New DateTime(2001, 1, 14), "Mike")
birthdays.Add(New DateTime(2001, 1, 15), "Pete")
... birthdays.Remove(1)
birthdays.Remove("Mike")
Following the four calls to the Add method, the Count property contains 4, element "Bill" has index value 1, and element
"Pete" has index value 4.
Following the first call to Remove, Count is 3, element "Bill" is deleted, and element "Pete" has index value 3.
Following the second call to Remove, Count is 2, element "Mike" is deleted, and element "Pete" has index value 2.
Requirements
Namespace: Microsoft.VisualBasic
Module: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Add Method (Collection Object)
Visual Basic Language Reference
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Get Information about Visual Basic Run-Time Errors
How to: Retrieve Information from an Error Object
Reference
Err Object Members
Error Statement
On Error Statement (Visual Basic)
Exit Statement (Visual Basic)
Resume Statement
Visual Basic Language Reference
Erl Property Read-only. Returns an integer indicating the line number of the last executed statement.
HelpContext Property Read/write. Returns or sets an Integer containing the context ID for a topic in a Help file.
HelpFile Property Read/write. Returns or sets a String expression containing the fully qualified path to a Help file.
LastDLLError Property Read-only. Returns a system error code produced by a call to a dynamic-link library (DLL).
Source Property Read/write. Returns or sets a String expression specifying the name of the object or application that ori
ginally generated the error.
Methods
Clear Method Clears all property settings of the Err object.
Raise Method Generates a run-time error; can be used instead of the Error statement.
See Also
Tasks
How to: Retrieve Information from an Error Object
Reference
Err Object (Visual Basic)
Visual Basic Language Reference
object.Clear
Parameters
object
Always the Err object.
Remarks
Use Clear to explicitly clear the Err object after an error has been handled, such as when you use deferred error handling with
On Error Resume Next. The Clear method is called automatically whenever any of the following statements executes:
Any type of Resume statement
Exit Sub, Exit Function, or Exit Property
Any On Error statement
Any Try...Catch...Finally statement
Note
The On Error Resume Next construct may be preferable to On Error GoTo when handling errors generated during ac
cess to other objects. Checking Err after each interaction with an object removes ambiguity about which object was acc
essed by the code: You can be sure which object placed the error code in Err.Number, as well as which object originall
y generated the error (the object specified in Err.Source).
Example
This example uses the Err object's Clear method to reset the numeric properties of the Err object to zero and its string
properties to zero-length strings. Without the call to Clear, the second call to MsgBox would display the same error message.
VB
Sub ClearErr()
' Produce overflow error
On Error Resume Next
Dim zero As Integer = 0
Dim result As Integer = 8 / zero
MsgBox(Err.Description)
Err.Clear()
MsgBox(Err.Description)
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Retrieve Information from an Error Object
Reference
Err Object (Visual Basic)
Description Property (Err Object)
HelpContext Property (Err Object)
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
On Error Statement (Visual Basic)
Raise Method (Err Object)
Source Property (Err Object)
Visual Basic Language Reference
Remarks
The Description property setting consists of a short description of the error. Use this property to alert the user to an error that
you cannot or do not want to handle. When generating a user-defined error, assign a short description of your error to the
Description property. If the Description property is not filled in, and the value of the Number property corresponds to a
Visual Basic run-time error, then the string returned by the ErrorToString function is set in the Description property when the
error is generated.
Example
This example assigns a user-defined message to the Description property of the Err object.
VB
On Error Resume Next
Err.Raise(60000)
Err.Description = "Your Widget needs a new Frob!"
MsgBox(Err.Description)
Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
ErrorToString Function
HelpContext Property (Err Object)
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
Source Property (Err Object)
Visual Basic Language Reference
Remarks
If Visual Basic encounters no line numbers, it returns 0.
Example
This example uses the Erl property to indicate the line number.
VB
10: On Error Resume Next
20: Err.Raise(60000)
' Returns 20.
30: MsgBox(Erl())
Remarks
The HelpContext property is used to display context-sensitive Help for an application. If a Help file is specified in HelpFile, the
HelpContext property is used to automatically display the Help file identified. If both the HelpFile and HelpContext
properties are empty, the value of the Number property is checked. If the value of the Number property corresponds to a
Visual Basic run-time error value, then the Visual Basic Help context ID for the error is used. If the value of the Number
property does not correspond to a Visual Basic error, the contents screen for the Visual Basic Help file is displayed.
Note
You should write routines in your application to handle typical errors. When programming with an object, you can use the ob
ject's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error is n
ot recoverable.
Example
This example uses the HelpContext property of the Err object to show the Visual Basic Help topic for the Overflow error.
VB
Dim Msg As String
Err.Clear()
On Error Resume Next ' Suppress errors for demonstration purposes.
Err.Raise(6) ' Generate "Overflow" error.
If Err.Number <> 0 Then
Msg = "Press F1 or HELP to see " & Err.HelpFile & " topic for" & _
" the following HelpContext: " & Err.HelpContext
MsgBox(Msg, , "Error:")
End If
Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Description Property (Err Object)
ErrorToString Function
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
Source Property (Err Object)
Visual Basic Language Reference
Remarks
If a Help file is specified by the HelpFile property, it is automatically called when the user presses the Help key (or the F1 key)
in the error message dialog box. If the HelpContext property contains a valid context ID for the specified file, that topic is
automatically displayed. If no HelpFile is specified, the Visual Basic Help file is displayed.
Note
You should write routines in your application to handle typical errors. When programming with an object, you can use the ob
ject's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error is n
ot recoverable.
Example
This example uses the HelpFile property of the Err object to start the Help system. By default, the HelpFile property contains
the name of the Visual Basic Help file.
VB
Dim Msg As String
Err.Clear()
On Error Resume Next ' Suppress errors for demonstration purposes.
Err.Raise(6) ' Generate "Overflow" error.
If Err.Number <> 0 Then
Msg = "Press F1 or HELP to see " & Err.HelpFile & " topic for" & _
" the following HelpContext: " & Err.HelpContext
MsgBox(Msg, , "Error:")
End If
Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Description Property (Err Object)
HelpContext Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
Source Property (Err Object)
Visual Basic Language Reference
Remarks
The LastDllError property applies only to DLL calls made from Visual Basic code. When such a call is made, the called function
usually returns a code indicating success or failure, and the LastDllError property is filled. Check the documentation for the
DLL's functions to determine the return values that indicate success or failure. Whenever the failure code is returned, the Visual
Basic application should immediately check the LastDllError property. No exception is raised when the LastDllError property
is set.
Note
The LastDllError property requires unmanaged code permission, which may affect its execution in partial-trust situations. Fo
r more information, see SecurityPermission and Code Access Permissions.
Example
The following example shows how you can use the LastDllError property after calling a function in the Windows API. The
PrintWindowCoordinates procedure takes a handle to a window and calls the GetWindowRect function. GetWindowRect
fills the RECT data structure with the lengths of the sides of the rectangle that make up the window. If you pass an invalid
handle, an error occurs, and the error number is available through the LastDllError property.
VB
Declare Function GetWindowRect Lib "user32" _
(ByVal hwnd As Integer, ByRef lpRect As RECT) As Integer
...
Public Structure RECT
Public Left As Integer
Public Top As Integer
Public Right As Integer
Public Bottom As Integer
End Structure
...
Const ERROR_INVALID_WINDOW_HANDLE As Long = 1400
Const ERROR_INVALID_WINDOW_HANDLE_DESCR As String = _
"Invalid window handle."
VB
Private Sub PrintWindowCoordinates(ByVal hwnd As Integer)
' Prints left, right, top, and bottom positions
' of a window in pixels.
Remarks
When returning a user-defined error from an object, set Err.Number by adding the number you selected as an error code to
the VbObjectError constant. For example, you use the following code to return the number 1051 as an error code:
VB
Err.Raise(Number:=vbObjectError + 1051, Source:="SomeClass")
Example
This example illustrates a typical use of the Number property in an error-handling routine.
VB
' Typical use of Number property.
Sub test()
On Error GoTo out
Dim x, y As Integer
x = 1 / y ' Create division by zero error.
Exit Sub
out:
MsgBox(Err.Number)
MsgBox(Err.Description)
' Check for division by zero error.
If Err.Number = 11 Then
y = y + 1
End If
Resume Next
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Description Property (Err Object)
ErrorToString Function
HelpContext Property (Err Object)
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Source Property (Err Object)
Visual Basic Language Reference
Parameters
Number
Required. Long integer that identifies the nature of the error. Visual Basic errors are in the range 0–65535; the range 0–512
is reserved for system errors; the range 513–65535 is available for user-defined errors. When setting the Number property
to your own error code in a class module, you add your error code number to the vbObjectError constant. For example, to
generate the error number 513, assign vbObjectError + 513 to the Number property.
Source
Optional. String expression naming the object or application that generated the error. When setting this property for an
object, use the form project.class. If Source is not specified, the process ID of the current Visual Basic project is used.
Description
Optional. String expression describing the error. If unspecified, the value in the Number property is examined. If it can be
mapped to a Visual Basic run-time error code, the string that would be returned by the Error function is used as the
Description property. If there is no Visual Basic error corresponding to the Number property, the "Application-defined or
object-defined error" message is used.
HelpFile
Optional. The fully qualified path to the Help file in which help on this error can be found. If unspecified, Visual Basic uses the
fully qualified drive, path, and file name of the Visual Basic Help file.
HelpContext
Optional. The context ID identifying a topic within HelpFile that provides help for the error. If omitted, the Visual Basic Help-
file context ID for the error corresponding to the Number property is used, if it exists.
Exceptions
Exception type Error number Condition
ArgumentException 5 Number is greater than 65535.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
All of the Raise arguments except Number are optional. If you omit optional arguments, and the property settings of the Err
object contain values that have not been cleared, those values serve as the values for your error.
Because the Err object gives richer information than when you generate errors with the Error statement, Raise is useful for
generating errors when writing class modules. For example, with the Raise method, the source that generated the error can be
specified in the Source property, online Help for the error can be referenced, and so on.
Example
This example uses the Err object's Raise method to generate an error within a function written in Visual Basic. The calling
function can catch the error and report it to the user with a message box.
VB
Const WidthError As Integer = 1
Const WidthHelp As Object = 101
Sub CallingProcedure()
Try
TestWidth(2000)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Clear Method (Err Object)
Description Property (Err Object)
Error Statement
HelpContext Property (Err Object)
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
On Error Statement (Visual Basic)
Source Property (Err Object)
ArgumentException Class
Visual Basic Language Reference
Remarks
The Source property specifies a String expression representing the object that generated the error; the expression is usually
the object's class name or process ID. Use the Source property to provide information when your code is unable to handle an
error generated in an accessed object. For example, if you access Microsoft Excel and it generates a Division by zero error,
Microsoft Excel sets Err.Number to its error code for that error and sets Source to "Excel.Application".
When the application is generating an error from code, Source is your application's programmatic ID. Within a class, Source
should contain a name having the form project.class. When an unexpected error occurs in your code, the Source property is
automatically filled in. For errors in a module, Source contains the project name.
Example
This example demonstrates the use of the Source property in a typical error-handling routine. When an error is raised from
Class1, the string "Class1" is assigned to the Source property of the Err object. This string is then displayed in an informative
message indicating the source and number of the error.
VB
Public Class Class1
Public Sub MySub()
On Error Resume Next
Err.Raise(60000, "Class1")
MsgBox(Err.Source & " caused an error of type " & Err.Number)
End Sub
End Class
Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Description Property (Err Object)
ErrorToString Function
GetObject Function (Visual Basic)
HelpContext Property (Err Object)
HelpContext Property (Err Object)
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
On Error Statement (Visual Basic)
Visual Basic Language Reference
My.Application Object
Provides properties, methods, and events related to the current application.
Remarks
The properties exposed by the My.Application object return data that is associated only with the current application or DLL.
No system-level information can be altered with My.Application.
Some members are available only for Windows Forms or console applications.
Example
This example uses the My.Application.CommandLineArgs property to examine the application's command-line arguments.
If an argument is found that starts with /input=, the rest of that argument is displayed.
VB
Private Sub ParseCommandLineArgs()
Dim inputArgument As String = "/input="
Dim inputName As String = ""
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase (the base class ConsoleApplicationBase provides members available in console
applications, and its base class ApplicationBase provides the members that are available in all projects)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Application Object Members
My.Application.ApplicationContext Property
My.Application.Info Object
My.Application.Log Object
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
Microsoft.VisualBasic.ApplicationServices.ApplicationBase
Visual Basic Language Reference
CommandLineArgs Gets a collection containing the command-line arguments as strings for the current applic
ation.
Culture Gets the culture that the current thread uses for string manipulation and string formatting.
Deployment Gets the current application's ClickOnce deployment object, which provides support for u
pdating the current deployment programmatically and the on-demand download of files.
Info Returns the My.Application.Info Object, which provides properties for getting the informat
ion about the application's assembly, such as the version number, description, and so on.
IsNetworkDeployed Gets a Boolean that represents whether the application was network deployed.
Log Returns the My.Application.Log Object, which provides a property and methods for writin
g event and exception information to the application's event log listeners.
MinimumSplashScreenDisplayTime Gets or sets the minimum length of time, in milliseconds, for which the splash screen is di
splayed.
SaveMySettingsOnExit Determines whether the application saves the user settings on exit.
This property is available only for Windows Forms and console applications.
UICulture Gets the culture that the current thread uses for retrieving culture-specific resources.
Methods
Method Description
ChangeCulture Changes the culture that the current thread uses for string manipulation and string formatting.
ChangeUICulture Changes the culture that the current thread uses for retrieving culture-specific resources.
StartupNextInstance Occurs when attempting to start a single-instance application and the application is already activ
e.
This event is available only for Windows Forms applications.
My.Application.ApplicationContext Property
Gets the ApplicationContext object for the current thread of a Windows Forms application.
' Usage
Dim value As System.Windows.Forms.ApplicationContext = My.Application.ApplicationContext
' Declaration
Public ReadOnly Property ApplicationContext As System.Windows.Forms.ApplicationContext
Return Value
This property returns the ApplicationContext object for the current thread. That object contains contextual information about
the thread.
Remarks
This is an advanced member; it does not appear in IntelliSense unless you click the All tab.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Console Application No
Windows Service No
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
System.Windows.Forms.ApplicationContext
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.ApplicationContext
Visual Basic Language Reference
My.Application.ChangeCulture Method
Changes the culture used by the current thread for string manipulation and for string formatting.
' Usage
My.Application.ChangeCulture(cultureName)
' Declaration
Public Sub ChangeCulture( _
ByVal cultureName As String _
)
Parameters
cultureName
String. Name of the culture as a string. For a list of possible names, see CultureInfo.
Exceptions
The following conditions can cause an exception:
The cultureName argument is Nothing (ArgumentNullException).
The cultureName argument is not a valid culture name (ArgumentException).
Remarks
The My.Application.ChangeCulture method changes the current thread's CurrentCulture property. CurrentCulture
determines the default formats for dates, times, currency, numbers, sorting order of text, string comparisons, and casing for all
computations on that thread.
To retrieve the current culture, you can use the My.Application.Culture Property or the CurrentCulture property.
The CurrentCulture setting is different from a language setting. It contains only data related to the standard settings for a
geographical region. Therefore, the CurrentCulture property can only be set to a specific culture or to the InvariantCulture.
Use the My.Application.ChangeUICulture method to change the culture that the current thread uses for retrieving culture-
specific resources.
Security Note
The My.Application.ChangeCulture method requires a SecurityPermission with the ControlThread set. Manipulating threa
ds is dangerous because of the security state associated with threads. Therefore, this permission should be given only as nec
essary to trustworthy code. You cannot change a thread's culture in semi-trusted code.
Example
This example demonstrates how changing the culture changes the string representation of dates.
VB
Private Sub TestChangeCulture()
' Store the current culture.
Dim currentculture As String = My.Application.Culture.Name
MsgBox("Current culture is " & currentculture)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase, ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
The following permission may be necessary:
Permission Description
SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlThread.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
My.Application.Culture Property
My.Application.ChangeUICulture Method
Microsoft.VisualBasic.ApplicationServices.ApplicationBase.ChangeCulture(System.String)
CurrentCulture
Visual Basic Language Reference
My.Application.ChangeUICulture Method
Changes the culture that the current thread uses for retrieving culture-specific resources.
' Usage
My.Application.ChangeUICulture(cultureName)
' Declaration
Public Sub ChangeUICulture( _
ByVal cultureName As String _
)
Parameters
cultureName
String. Name of the culture as a string. For a list of possible names, see CultureInfo.
Exceptions
The following conditions can cause an exception:
The cultureName argument is Nothing (ArgumentNullException).
The cultureName argument is not a valid culture name (ArgumentException).
Remarks
The My.Application.ChangeUICulture method changes the current thread's CurrentUICulture property. The
CurrentUICulture property determines the culture used by the Resource Manager and the My.Resources object; it uses this
information to look up culture-specific resources at run time.
To retrieve the current UI culture, you can use the My.Application.UICulture Property or the CurrentUICulture property.
Use the My.Application.ChangeCulture method to change the culture that the current thread uses for string manipulation
and string formatting.
Example
This example uses the My.Application.ChangeUICulture method to set the culture that the My.Resources Object uses for
retrieving resources.
VB
Sub ShowLocalizedMessage()
Dim culture As String = My.Application.UICulture.Name
My.Application.ChangeUICulture("fr-FR")
MsgBox(My.Resources.Message)
My.Application.ChangeUICulture(culture)
End Sub
For this example to work, your application must have a string named Message in the application's resource file, and the
application should have the French-culture version of that resource file, Resources.fr-FR.resx. For more information, see
How to: Add or Remove Resources.
If the application does not have the French-culture version of that resource file, the My.Resource object retrieves the resource
from the default-culture resource file.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase, ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Retrieve Localized Resources in Visual Basic
Reference
My.Application Object
My.Application.ChangeCulture Method
My.Resources Object
Microsoft.VisualBasic.ApplicationServices.ApplicationBase.ChangeUICulture(System.String)
Visual Basic Language Reference
My.Application.Culture Property
Gets the culture that the current thread uses for string manipulation and string formatting.
' Usage
Dim value As System.Globalization.CultureInfo = My.Application.Culture
' Declaration
Public ReadOnly Property Culture As System.Globalization.CultureInfo
Return Value
Returns a CultureInfo object that represents the culture the current thread uses for string manipulation and string formatting.
Remarks
The My.Application.CurrentCulture property gets the CultureInfo object that the current thread uses for string
manipulation and string formatting. This object is identical to the one returned by the CurrentCulture property, which controls
many of the string-related computations on that thread. The CurrentCulture property determines the default formats for
dates, times, currency, and numbers. It also determines how to sort, compare, and capitalize strings.
To change the culture, you can use the My.Application.ChangeCulture Method or assign a different CultureInfo object to the
CurrentCulture property.
The CurrentCulture setting is different from a language setting. It contains only data related to the standard settings for a
geographical region.
Use the My.Application.CurrentUICulture property to get the culture that the current thread uses for retrieving culture-
specific resources.
Example
This example demonstrates how the culture affects the string representation of dates.
VB
Private Sub TestChangeCulture()
' Store the current culture.
Dim currentculture As String = My.Application.Culture.Name
MsgBox("Current culture is " & currentculture)
Dim jan1 As New Date(2005, 1, 1, 15, 15, 15)
My.Application.ChangeCulture("en-US")
MsgBox("Date represented in en-US culture: " & jan1)
' 1/1/2005 3:15:15 PM
My.Application.ChangeCulture("")
MsgBox("Date represented in invariant culture" & jan1)
' 01/01/2005 15:15:15
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase, ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
My.Application.ChangeCulture Method
My.Application.UICulture Property
System.Globalization.CultureInfo
CurrentCulture
Microsoft.VisualBasic.ApplicationServices.ApplicationBase.Culture
Visual Basic Language Reference
My.Application.CommandLineArgs Property
Gets a collection containing the command-line arguments as strings for the current application.
' Usage
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Application.
CommandLineArgs
' Declaration
Public ReadOnly Property CommandLineArgs As System.Collections.ObjectModel.ReadOnlyCollecti
on(Of String)
Return Value
A ReadOnlyCollection of String, containing the command-line arguments as strings for the current application.
Remarks
The My.Application.CommandLineArgs property provides read-only access to the current application's command-line
arguments for applications that are not ClickOnce deployed.
For a single-instance application, the My.Application.CommandLineArgs property returns the command-line arguments for
the first instance of an application. To access the arguments for subsequent attempts to start a single-instance application, you
must handle the My.Application.StartupNextInstance Event and examine the CommandLine property of the StartupEventArgs
argument.
Note
The My.Application.CommandLineArgs property returns only the command-line arguments. This is different from the be
havior of the CommandLine property, which returns the application name in addition to the arguments.
Note
In an application that is ClickOnce deployed, use the ActivationUri property of the My.Application.Deployment object to g
et the command-line arguments. For more information, see My.Application.Deployment Property.
Tasks
The following table lists examples of tasks involving the My.Application.CommandLineArgs property.
To See
Check if the application started with the string /batch as an argu How to: Enable a Batch Mode for Window Forms Applications
ment
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: ConsoleApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Web Site No
Permissions
The following permission may be necessary:
Permission Description
EnvironmentPermission Controls the ability to access the PATH environment variable. Associated enumeration: Read.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
My.Application.StartupNextInstance Event
ReadOnlyCollection
Microsoft.VisualBasic.ApplicationServices.ConsoleApplicationBase.CommandLineArgs
StartupEventArgs
CommandLine
Visual Basic Language Reference
My.Application.Deployment Property
Gets the current application's ClickOnce deployment object, which provides support for updating the current deployment
programmatically and support for the on-demand download of files.
' Usage
Dim value As System.Deployment.Application.ApplicationDeployment = My.Application.Deploymen
t
' Declaration
Public ReadOnly Property Deployment As System.Deployment.Application.ApplicationDeployment
Return Value
Returns the ApplicationDeployment object for the application's ClickOnce deployment.
Exceptions
The following condition can cause an exception:
The application is not deployed as a ClickOnce application (InvalidDeploymentException).
Remarks
The My.Application.Deployment property returns the application's ClickOnce ApplicationDeployment object. The
ApplicationDeployment object provides support for updating the current deployment programmatically as well as support
for the on-demand download of files. For more information on ClickOnce applications and how to deploy them, see
ClickOnce Deployment and Publishing ClickOnce Applications.
Check the My.Application.IsNetworkDeployed Property before accessing the My.Application.Deployment property.
Otherwise, if the application is not deployed using ClickOnce, reading the My.Application.Deployment property results in an
InvalidDeploymentException exception. For more information on deploying a ClickOnce application, see
How to: Publish a ClickOnce Application.
For more information on using the My.Application.Deployment property, see
Overview of the Visual Basic Application Model.
Tasks
The following table lists examples of tasks involving the My.Application.Deployment property.
To See
Check for an application update How to: Check for ClickOnce Application Updates
Only applications that are ClickOnce deployed can be updated using the My.Application.Deployment object. For more
information on deploying a ClickOnce application, see How to: Publish a ClickOnce Application.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: ConsoleApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Check for ClickOnce Application Updates
How to: Download ClickOnce Application Updates
How to: Publish a ClickOnce Application
Reference
My.Application Object
My.Application.IsNetworkDeployed Property
System.Deployment.Application.ApplicationDeployment
Microsoft.VisualBasic.ApplicationServices.ConsoleApplicationBase.Deployment
Concepts
Overview of the Visual Basic Application Model
Other Resources
Publishing ClickOnce Applications
Visual Basic Language Reference
My.Application.DoEvents Method
Processes all Windows messages currently in the message queue.
' Usage
My.Application.DoEvents()
' Declaration
Public Sub DoEvents()
Remarks
The My.Application.DoEvents method allows your application to handle other events that might be raised while you code
runs. The My.Application.DoEvents method has the same behavior as the DoEvents method.
When you run a Windows Forms application, it creates a new form, which then waits for events to be handled. Each time the
form handles an event, such as a button click, it processes all the code associated with that event. All other events wait in the
queue. While your code handles the event, your application does not respond. For example, the window does not repaint if
another window is dragged on top.
If you call My.Application.DoEvents in your code, your application can handle the other events. For example, if your code
adds data to a ListBox in a loop, and after each step of the loop it calls My.Application.DoEvents, your form repaints when
another window is dragged over it. If you remove My.Application.DoEvents from your code, your form will not repaint until
the click event handler of the button is finished executing.
Typically, you use this method in a loop to process messages.
Note
The My.Application.DoEvents method does not process events in exactly the same way as the form does. Use multithreadi
ng to make the form directly handle the events. For more information, see Multithreading in Visual Basic.
Caution
If a method that handles a user interface (UI) event calls the My.Application.DoEvents method, the method might be re-en
tered before it finishes. This can happen because the My.Application.DoEvents method processes Windows messages, and
Windows messages can raise events.
Tasks
The following table lists an example of a task involving the My.Application.DoEvents method.
To See
Allow a form to respond to UI input while busy Walkthrough: Handling Events
Example
This example uses the My.Application.DoEvents method to allow the UI for TextBox1 to update.
VB
Private Sub TestDoEvents()
For i As Integer = 0 To 10000
TextBox1.Text = i.ToString
My.Application.DoEvents()
Next
End Sub
This code should be in a form that has a TextBox1 component with a Text property.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Console Application No
Windows Service No
Web Site No
Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration: AllWindows.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoEvents
DoEvents
Visual Basic Language Reference
My.Application.GetEnvironmentVariable Method
Returns the value of the specified environment variable.
' Usage
Dim value As String = My.Application.GetEnvironmentVariable(name)
' Declaration
Public Function GetEnvironmentVariable( _
ByVal name As String _
) As String
Parameters
name
A String containing the name of the environment variable.
Return Value
A String containing the value of the environment variable with the name name.
Exceptions
The following conditions can cause an exception:
The name argument is Nothing (ArgumentNullException).
The environment variable specified by name does not exist (ArgumentException).
The calling code does not have EnvironmentPermission with Read access (SecurityException).
Remarks
The My.Application.GetEnvironmentVariable method returns the environment variable with the name name. This method
is similar to System.Environment.GetEnvironmentVariable(System.String), except that this method raises an exception if the
environment variable specified by name does not exist.
Example
This example uses the My.Application.GetEnvironmentVariable method to get and display the value of the PATH
environment variable, if available. Otherwise, it displays a message indicating that the PATH environment variable does not
exist.
VB
Private Sub TestGetEnvironmentVariable()
Try
MsgBox("PATH = " & My.Application.GetEnvironmentVariable("PATH"))
Catch ex As System.ArgumentException
MsgBox("Environment variable 'PATH' does not exist.")
End Try
End Sub
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase, ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
GetEnvironmentVariable
GetEnvironmentVariable
Visual Basic Language Reference
My.Application.Info Property
Gets an object that provides properties for getting information about the application's assembly, such as the version number,
description, and so on.
' Usage
Dim value As Microsoft.VisualBasic.ApplicationServices.AssemblyInfo = My.Application.Info
' Declaration
Public ReadOnly Property Info As AssemblyInfo
Return Value
This property returns the My.Application.Info object for the current application.
Remarks
This property provides easy access to the My.Application.Info. For more information, see My.Application.Info Object.
Example
This example uses the My.Application.Info.Version property to display the version of the application.
VB
MsgBox("Application version: " & My.Application.Info.Version.ToString)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
My.Application.Info Object
Visual Basic Language Reference
My.Application.IsNetworkDeployed Property
Gets a Boolean that represents whether the application was deployed from a network using ClickOnce.
' Usage
Dim value As Boolean = My.Application.IsNetworkDeployed
' Declaration
Public ReadOnly Property IsNetworkDeployed As Boolean
Return Value
A Boolean that represents whether the application was deployed from a network. The value is True if the current application
was deployed from a network; otherwise the value is False.
Remarks
The My.Application.IsNetworkDeployed property indicates whether the application was deployed from a network using
ClickOnce. For more information on ClickOnce applications, see ClickOnce Deployment.
You should check that this property is True before accessing the My.Application.Deployment Property. Otherwise, if the
application is not deployed from a network using ClickOnce, reading the My.Application.Deployment property results in an
InvalidDeploymentException exception.
For more information on configuring ClickOnce, see Publishing ClickOnce Applications. For more information on deploying a
ClickOnce application, see How to: Publish a ClickOnce Application.
For more information on using the My.Application.IsNetworkDeployed property, see
Overview of the Visual Basic Application Model.
Tasks
The following table lists examples of tasks involving the My.Application.IsNetworkDeployed property.
To See
Check for an application update. How to: Check for ClickOnce Application Updates
Only applications that are ClickOnce-deployed can be updated using the My.Application.Deployment object. For more
information on deploying a ClickOnce application, see How to: Publish a ClickOnce Application.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: ConsoleApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Check for ClickOnce Application Updates
How to: Download ClickOnce Application Updates
How to: Publish a ClickOnce Application
Reference
My.Application Object
My.Application.Deployment Property
IsNetworkDeployed
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Reference
My.Application.Log Property
Gets an object that provides properties and methods for writing event and exception information to the application's log
listeners.
' Usage
Dim value As Microsoft.VisualBasic.Logging.Log = My.Application.Log
' Declaration
Public ReadOnly Property Log As MyLog
Return Value
This property returns the My.Application.Log object for the current application.
Remarks
This property provides easy access to the My.Application.Log object. For more information, see My.Application.Log Object.
Example
This example shows how to use the My.Application.Log.WriteEntry method to log tracing information. For more
information, see How to: Write Log Messages.
VB
Public Sub TracingTest(ByVal fileName As String)
My.Application.Log.WriteEntry( _
"Entering TracingTest with argument " & _
fileName & ".")
' Code to trace goes here.
My.Application.Log.WriteEntry( _
"Exiting TracingTest with argument " & _
fileName & ".")
End Sub
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
My.Application.Log Object
Visual Basic Language Reference
My.Application.MinimumSplashScreenDisplayTime Property
Determines the minimum length of time, in milliseconds, for which the splash screen is displayed.
' Usage
Dim value As Integer = My.Application.MinimumSplashScreenDisplayTime
' Declaration
Public Property MinimumSplashScreenDisplayTime As Integer
Return Value
Integer. The minimum length of time, in milliseconds, for which the splash screen is displayed.
Remarks
The My.Application.MinimumSplashScreenDisplayTime property allows you to specify the minimum length of time you
want the application's splash screen to be displayed. If the main form finishes initializing in less time than what is specified by
this property, the splash screen remains until the requested amount of time passes, at which time the main form is displayed. If
your application takes longer to start, the splash screen is closed once the main form becomes active.
When you add a splash screen to your application using the Project Designer, it sets the
My.Application.MinimumSplashScreenDisplayTime property to 2000, giving a minimum display time of two seconds.
This property supports the Visual Basic Application model. For more information, see
Overview of the Visual Basic Application Model.
You should set the My.Application.MinimumSplashScreenDisplayTime property in a method that overrides the
OnInitialize or OnCreateSplashScreen method. Code that overrides methods of the WindowsFormsApplicationBase class
should be entered in the ApplicationEvents.vb file, which is hidden by default.
To access the Code Editor window for overriding members
1. With a project selected in Solution Explorer, click Properties on the Project menu.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
For more information, see How to: Handle Application Events (Visual Basic).
Example
This example demonstrates how to set the My.Application.MinimumSplashScreenDisplayTime property by overriding the
OnInitialize property.
VB
Protected Overrides Function OnInitialize( _
ByVal commandLineArgs As _
System.Collections.ObjectModel.ReadOnlyCollection(Of String) _
) As Boolean
' Set the display time to 5000 milliseconds (5 seconds).
Me.MinimumSplashScreenDisplayTime = 5000
Return MyBase.OnInitialize(commandLineArgs)
End Function
Class Library No
Console Application No
Windows Service No
Web Site No
See Also
Reference
My.Application Object
My.Application.SplashScreen Property
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.MinimumSplashScreenDisplayTime
OnInitialize
OnCreateSplashScreen
WindowsFormsApplicationBase
Concepts
Extending the Visual Basic Application Model
Visual Basic Language Reference
My.Application.NetworkAvailabilityChanged Event
Occurs when the network availability changes.
' Usage
Public Sub Me_NetworkAvailabilityChanged( _
ByVal sender As Object, _
ByVal e As NetworkAvailableEventArgs _
) Handles Me.NetworkAvailabilityChanged
End Sub
' Declaration
Public Event NetworkAvailabilityChanged( _
ByVal sender As Object, _
ByVal e As NetworkAvailableEventArgs _
)
Parameters
sender
Required. The Object that raised the event.
e
Required. A NetworkAvailableEventArgs object that contains information about the availability of the network.
Remarks
An application raises the NetworkAvailabilityChanged event every time the availability of the network changes. You can use
the IsNetworkAvailable property of the e parameter to get the new state of the network connection. To get the current state of
the network connection, use the My.Computer.Network.IsAvailable Property.
This event is raised on the application's main thread with the other user-interface events. This allows the event handler to
access directly the application's UI. However, if the application is busy handling another user-interface event when this event is
raised, this event cannot be processed until the other event handler finishes or calls the My.Application.DoEvents Method.
The My.Computer.Network.NetworkAvailabilityChanged Event provides the same functionality as this event but is available for
all application types.
The code for the NetworkAvailabilityChanged event handler is stored in the ApplicationEvents.vb file, which is hidden by
default.
To access the Code Editor window for application events
1. Have a project selected in Solution Explorer. Click Properties on the Project menu.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
For more information, see How to: Handle Application Events (Visual Basic).
Note
Many network hubs will provide a network connection even if the hub is disconnected from a larger network. Consequently,
for wired connections, this event indicates change in the connection between the computer and a hub.
Note
The NetworkAvailabilityChanged event is not raised by applications when run on Windows 95 and Windows 98, or when
run by a non-administrator on Windows 2000. If your application might run on those platforms, use the
My.Computer.Network.IsAvailable Property to check for network availability.
Example
This example calls the SetConnectionStatus method of the default Form1 class when the network availability changes.
You must enter the code in the Code Editor window for application events. To access this window, follow the instructions from
this topic's Remarks section.
VB
Private Sub MyApplication_NetworkAvailabilityChanged( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.Devices.NetworkAvailableEventArgs _
) Handles Me.NetworkAvailabilityChanged
My.Forms.Form1.SetConnectionStatus(e.IsNetworkAvailable)
End Sub
Class Library No
Console Application No
Windows Service No
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
My.Forms Object
My.Computer.Network.NetworkAvailabilityChanged Event
Microsoft.VisualBasic.Devices.NetworkAvailableEventArgs
Visual Basic Language Reference
My.Application.OpenForms Property
Gets a collection of all the application's open forms.
' Usage
Dim value As System.Windows.Forms.FormCollection = My.Application.OpenForms
' Declaration
Public ReadOnly Property OpenForms As System.Windows.Forms.FormCollection
Return Value
A FormCollection object that contains all of the application's open forms.
Remarks
The My.Application.OpenForms property gets a collection of all the application's open forms. The behavior is identical to the
System.Windows.Forms.Application.OpenForms property.
Note
The My.Application.OpenForms property returns all open forms, regardless of which thread opened them. You should che
ck the InvokeRequired property of each form before accessing it; otherwise, it might throw an InvalidOperationException exc
eption. For more information, see How to: Access All Open Forms of an Application.
Tasks
The following table lists examples of tasks involving the My.Application.OpenForms property.
To See
Display the titles of all the application's open forms How to: Access All Open Forms of an Application
Example
This example loops over the application's open forms, selects the ones directly accessible by the current thread, and displays
their titles in a ListBox control. To access the open forms, see How to: Access All Open Forms of an Application.
VB
Private Sub GetOpenFormTitles()
Dim formTitles As New Collection
Try
For Each f As Form In My.Application.OpenForms
If Not f.InvokeRequired Then
' Can access the form directly.
formTitles.Add(f.Text)
End If
Next
Catch ex As Exception
formTitles.Add("Error: " & ex.Message)
End Try
Form1.ListBox1.DataSource = formTitles
End Sub
This example requires that your Windows Forms application have a form named Form1 that contains a list box named
ListBox1.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Console Application No
Windows Service No
Web Site No
Permissions
The following permission may be necessary:
Permission Description
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration: AllWindows.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
System.Windows.Forms.FormCollection
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OpenForms
System.Windows.Forms.Application.OpenForms
Visual Basic Language Reference
My.Application.Run Method
Sets up and starts the Visual Basic Application model.
' Usage
My.Application.Run(commandLine)
' Declaration
Public Sub Run( _
ByVal commandLine As String() _
)
Parameters
commandLine
Array of type String. The command line from Sub Main.
Remarks
The My.Application.Run method provides support for the Visual Basic Application model. This method should be called only
from the application's Sub Main. By default, the Sub Main of a Windows Forms application calls this method. For more
information, see Overview of the Visual Basic Application Model.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Console Application No
Windows Service No
Web Site No
Permissions
The following permissions may be necessary:
Permission Description
EnvironmentPermission Controls the ability to access all environment variables. Associated enumeration: Unrestricted.
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
RegistryPermission Controls the ability to access registry variables. Associated enumeration: Unrestricted.
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration
: AllWindows.
WebPermission Controls rights to access HTTP Internet resources. Associated enumeration: Unrestricted.
SocketPermission Controls rights to make or accept connections on a transport address. Associated enumeratio
n: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(System.String[])
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Reference
My.Application.SaveMySettingsOnExit Property
Determines whether the application saves the user settings on exit.
' Usage
Dim value As Boolean = My.Application.SaveMySettingsOnExit
' Declaration
Public Property SaveMySettingsOnExit As Boolean
Return Value
Boolean. True indicates that the application saves the user settings on exit. Otherwise, the settings are not implicitly saved.
Remarks
The SaveMySettingsOnExit property allows the user to change how the application saves settings, at run time. You can
explicitly save setting changes by using the Save method of the My.Settings object. For more information about changing and
saving settings, see My.Settings Object.
The changes to this property are not persisted when the application closes. To change the SaveMySettingsOnExit property
permanently, you must change the setting in the Project Designer:
To change the setting in the Project Designer
1. Have a project selected in Solution Explorer. Click Properties on the Project menu.
2. Click the Application tab.
3. Select Save My.Settings on Shutdown.
For more information, see Managing Application Properties.
Example
This example has two parts.
The InitializeSaveMySettingsOnExit subroutine, which initializes the checked state of a CheckBox control to the
current value of the SaveMySettingsOnExit property.
The SaveMySettingsOnExit_CheckedChanged subroutine, which handles changes to a CheckBox control to update the
My.Application.SaveMySettingsOnExit property.
VB
Private Sub InitializeSaveMySettingsOnExit()
SaveMySettingsOnExit.Checked = _
My.Application.SaveMySettingsOnExit
End Sub
Private Sub SaveMySettingsOnExit_CheckedChanged( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles SaveMySettingsOnExit.CheckedChanged
My.Application.SaveMySettingsOnExit = _
SaveMySettingsOnExit.Checked
End Sub
For this example to work, your application must have a CheckBox control named SaveMySettingsOnExit.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Console Application No
Windows Service No
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
My.Settings Object
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.SaveMySettingsOnExit
Save
Visual Basic Language Reference
My.Application.Shutdown Event
Occurs when the application shuts down.
' Usage
Public Sub Me_Shutdown( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
) Handles Me.Shutdown
End Sub
' Declaration
Public Event Shutdown( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
)
Parameters
sender
The Object that raised the event.
e
An EventArgs object that contains Empty.
Remarks
An application raises the Shutdown event before it exits. This allows you to control how the application closes its resources.
This event is part of the Visual Basic Application model. For more information, see
Overview of the Visual Basic Application Model.
The code for the Shutdown event handler is stored in the ApplicationEvents.vb file, which is hidden by default.
To access the Code Editor window for application events
1. With a project selected in Solution Explorer, click Properties on the Project menu.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
For more information, see How to: Handle Application Events (Visual Basic).
Tasks
The following table lists examples of tasks involving the My.Application.Shutdown event.
To See
Use the events provided by the Visual Basic Application mo How to: Run Code When the Application Starts or Ends
del to run code
Log a message when the application shuts down How to: Log Messages When the Application Starts or Shuts Down
Example
This example logs messages when the application shuts down.
VB
Private Sub MyApplication_Shutdown( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
) Handles Me.Shutdown
My.Application.Log.WriteEntry("Application Shut Down.")
End Sub
You must enter the code in the Code Editor window for application events. To access this window, follow the instructions from
this topic's Remarks section. For more information, see How to: Log Messages When the Application Starts or Shuts Down.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Console Application No
Windows Service No
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Log Messages When the Application Starts or Shuts Down
How to: Handle Application Events (Visual Basic)
Reference
My.Application Object
System.EventArgs
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Shutdown
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Reference
My.Application.SplashScreen Property
Gets or sets the splash screen for this application.
' Usage
Dim value As System.Windows.Forms.Form = My.Application.SplashScreen
' Declaration
Public Property SplashScreen As System.Windows.Forms.Form
Return Value
A Form object that the application uses as the splash screen.
Exceptions
The following condition can cause an exception:
The same value assigned to this property and the My.Application.MainForm property (ArgumentNullException).
Remarks
The My.Application.SplashScreen property allows you to get or set the Form object that the application uses as the splash
screen, the first graphic form that is displayed while an application is being started.
This property supports the Visual Basic Application model. For more information, see
Overview of the Visual Basic Application Model.
The changes to this property are not persisted when the application closes. To change the splash screen permanently, you must
change the setting in the Project Designer. For more information, see
How to: Specify a Splash Screen for an Application (Visual Basic).
Example
This example uses the My.Application.SplashScreen property and the My.Application.Startup event to update the splash
screen with status information as the application starts.
VB
Private Sub MyApplication_Startup( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs _
) Handles Me.Startup
' Get the splash screen.
Dim splash As SplashScreen1 = CType(My.Application.SplashScreen, SplashScreen1)
' Display current status information.
splash.Status = "Current user: " & My.User.Name
End Sub
This example requires that the project have a splash screen named SplashScreen1. The splash screen needs to have a property
named Status that updates its user interface.
You must enter this code in the Code Editor window for application events. For more information, see
How to: Handle Application Events (Visual Basic).
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Console Application No
Windows Service No
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
My.Application.MinimumSplashScreenDisplayTime Property
System.Windows.Forms.Form
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.SplashScreen
Visual Basic Language Reference
My.Application.Startup Event
Occurs when the application starts.
' Usage
Public Sub Me_Startup( _
ByVal sender As Object, _
ByVal e As StartupEventArgs _
) Handles Me.Startup
End Sub
' Declaration
Public Event Startup( _
ByVal sender As Object, _
ByVal e As StartupEventArgs _
)
Parameters
sender
The Object that raised the event.
e
A StartupEventArgs object that contains the application's command-line arguments.
Remarks
A normal (non-single-instance) application raises the Startup event every time it starts. A single-instance application raises the
Startup event when it starts only if the application is not already active; otherwise, it raises the StartupNextInstance event.
For more information, see My.Application.StartupNextInstance Event and
How to: Specify Instancing Behavior for an Application.
This event is part of the Visual Basic Application model. For more information, see
Overview of the Visual Basic Application Model.
You can use the Cancel property of the e parameter to control the loading of an application's startup form. When the Cancel
property is set to True, the startup form does not start. In that case, your code should call an alternate startup code path. For
example, see How to: Enable a Batch Mode for Window Forms Applications.
You can use the CommandLine property of the e parameter or the My.Application.CommandLineArgs Property to access the
application's command-line arguments.
The code for the Startup event handler is stored in the ApplicationEvents.vb file, which is hidden by default.
To access the Code Editor window for application events
1. With a project selected in Solution Explorer, click Properties on the Project menu.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
For more information, see How to: Handle Application Events (Visual Basic).
Tasks
The following table lists examples of tasks involving the My.Application.Startup event.
To See
Use the events provided by the Visual Basic Application model t How to: Run Code When the Application Starts or Ends
o run code
Check if the application started with the string /batch as an argu How to: Enable a Batch Mode for Window Forms Applications
ment
Example
This example uses the My.Application.SplashScreen property and the My.Application.Startup event to update the splash
screen with status information as the application starts.
VB
Private Sub MyApplication_Startup( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs _
) Handles Me.Startup
' Get the splash screen.
Dim splash As SplashScreen1 = CType(My.Application.SplashScreen, SplashScreen1)
' Display current status information.
splash.Status = "Current user: " & My.User.Name
End Sub
This example requires that the project have a splash screen named SplashScreen1. The splash screen needs to have property
named Status that updates its user interface.
You must enter the code in the Code Editor window for application events. To access this window, follow the instructions from
this topic's Remarks section. For more information, see How to: Handle Application Events (Visual Basic).
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Console Application No
Windows Service No
Web Site No
Permissions
The following permissions may be necessary:
Permission Description
SecurityPermission Controls the ability to add an event handler for this event. Associated enumeration:
System.Security.Permissions.SecurityPermissionFlag.ControlAppDomain.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Enable a Batch Mode for Window Forms Applications
How to: Handle Application Events (Visual Basic)
How to: Specify Instancing Behavior for an Application
Reference
My.Application Object
My.Application.StartupNextInstance Event
My.Application.CommandLineArgs Property
Microsoft.VisualBasic.ApplicationServices.StartupEventArgs
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Startup
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Reference
My.Application.StartupNextInstance Event
Occurs when attempting to start a single-instance application and the application is already active.
' Usage
Public Sub Me_StartupNextInstance( _
ByVal sender As Object, _
ByVal e As StartupNextInstanceEventArgs _
) Handles Me.StartupNextInstance
End Sub
' Declaration
Public Event StartupNextInstance( _
ByVal sender As Object, _
ByVal e As StartupNextInstanceEventArgs _
)
Parameters
sender
The Object that raised the event.
e
A StartupEventArgs object that contains the application's command-line arguments.
Remarks
A single-instance application raises the StartupNextInstance event when you attempt to restart the application when it is
already active. When a single-instance application starts for the first time, it raises the Startup event. For more information, see
My.Application.Startup Event and How to: Specify Instancing Behavior for an Application.
This event is part of the Visual Basic Application model. For more information, see
Overview of the Visual Basic Application Model.
This event is raised on the application's main thread with the other user-interface events. This allows the event handler to
access directly the application's user interface. However, if the application is busy handling another user-interface event when
this event is raised, this event cannot be processed until the other event handler finishes or calls the
My.Application.DoEvents Method.
Note
The StartupNextInstance event is raised only in single-instance applications. To enable single-instance behavior for your a
pplication, you must check the Make single instance application check box in the Project Designer. For more information,
see How to: Specify Instancing Behavior for an Application.
You must use the CommandLine property of the e parameter to access the arguments for subsequent attempts to start a
single-instance application. The My.Application.CommandLineArgs Property provides the arguments used to start the first
instance of a single-instance application.
The code for the StartupNextInstance event handler is stored in the ApplicationEvents.vb file, which is hidden by default.
To access the Code Editor window for application events
1. With a project selected in Solution Explorer, click Properties on the Project menu.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
For more information, see How to: Handle Application Events (Visual Basic).
Tasks
The following table lists examples of tasks involving the My.Application.StartupNextInstance event.
To See
Use the events provided by the Visual Basic Application model to run c How to: Run Code When the Application Starts or Ends
ode
Check the command-line arguments of the first application instance My.Application.CommandLineArgs Property
Example
This example uses the e parameter of the StartupNextInstance event handler to examine the application's command-line
arguments. If an argument is found that starts with /input=, the rest of that argument is displayed.
VB
Private Sub MyApplication_StartupNextInstance( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs _
) Handles Me.StartupNextInstance
Dim inputArgument As String = "/input="
Dim inputName As String = ""
For Each s As String In e.CommandLine
If s.ToLower.StartsWith(inputArgument) Then
inputName = s.Remove(0, inputArgument.Length)
End If
Next
You must enter the code in the Code Editor window for application events. To access this window, follow the instructions from
this topic's Remarks section. For more information, see How to: Handle Application Events (Visual Basic).
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Console Application No
Windows Service No
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Handle Application Events (Visual Basic)
How to: Specify Instancing Behavior for an Application
How to: Specify Instancing Behavior for an Application
Reference
My.Application Object
My.Application.Startup Event
My.Application.CommandLineArgs Property
StartupEventArgs
CommandLine
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.StartupNextInstance
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Reference
My.Application.UICulture Property
Gets the culture that the current thread uses for retrieving culture-specific resources.
' Usage
Dim value As System.Globalization.CultureInfo = My.Application.UICulture
' Declaration
Public ReadOnly Property UICulture As System.Globalization.CultureInfo
Return Value
Returns a CultureInfo object that represents the culture that the current thread uses for retrieving culture-specific resources.
Remarks
The My.Application.CurrentUICulture property gets the CultureInfo object that the current thread uses for retrieving
culture-specific resources. This object is identical to the one returned by the CurrentUICulture property. The CurrentUICulture
property determines the culture used by the Resource Manager and the My.Resources object, information it needs to look up
culture-specific resources at run time.
To change the culture, you can use the My.Application.ChangeUICulture Method or assign a different CultureInfo object to the
CurrentUICulture property.
The CurrentCulture setting is different from a language setting. It contains only data related to the standard settings for a
geographical region.
Use the My.Application.CurrentCulture property to get the culture that the current thread uses for string manipulation and
string formatting.
Example
This example uses the My.Application.CurrentCulture property to cache the current culture, before changing it with the
My.Application.ChangeUICulture Method. The My.Application.ChangeUICulture method sets the culture that the
My.Resources Object uses for retrieving resources.
VB
Sub ShowLocalizedMessage()
Dim culture As String = My.Application.UICulture.Name
My.Application.ChangeUICulture("fr-FR")
MsgBox(My.Resources.Message)
My.Application.ChangeUICulture(culture)
End Sub
For this example to work, your application must have a string named Message in the application's resource file, and the
application should have the French-culture version of that resource file, Resources.fr-FR.resx. For more information, see
How to: Add or Remove Resources.
If the application does not have the French-culture version of that resource file, the My.Resource object retrieves the resource
from the default-culture resource file.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase, ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Retrieve Localized Resources in Visual Basic
Reference
My.Application Object
My.Application.ChangeUICulture Method
My.Application.Culture Property
System.Globalization.CultureInfo
CurrentUICulture
Microsoft.VisualBasic.ApplicationServices.ApplicationBase.UICulture
Visual Basic Language Reference
My.Application.UnhandledException Event
Occurs when the application encounters an unhandled exception.
' Usage
Public Sub Me_UnhandledException( _
ByVal sender As Object, _
ByVal e As UnhandledExceptionEventArgs _
) Handles Me.UnhandledException
End Sub
' Declaration
Public Event UnhandledException( _
ByVal sender As Object, _
ByVal e As UnhandledExceptionEventArgs _
)
Parameters
sender
The Object that raised the event.
e
An UnhandledExceptionEventArgs object that contains the unhandled exception and additional information.
Remarks
An application raises the UnhandledException event when it encounters an unhandled exception. This event is part of the
Visual Basic Application model. For more information, see Overview of the Visual Basic Application Model.
You can use the Exception property of the e parameter to access the unhandled exception that caused this event.
You can use the ExitApplication property of the e parameter to control whether the application exits. By default,
ExitApplication is True, so the application exits after completing the UnhandledException event handler. You can set the
value to True in the UnhandledException event handler to keep the application running, and have it return to a waiting state.
The code for the UnhandledException event handler is stored in the ApplicationEvents.vb file, which is hidden by default.
To access the Code Editor window for application events:
1. With a project selected in Solution Explorer, click Properties on the Project menu.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
For more information, see How to: Handle Application Events (Visual Basic).
Note
The Visual Basic compiler prevents applications that are built for debugging from raising this event, to allow a debugger to h
andle the unhandled exceptions. This means that if you are testing your application by running it under the Visual Studio Inte
grated Development Environment debugger, your UnhandledException event handler will not be called. For more informa
tion on building applications for debugging, see /debug (Visual Basic).
Tasks
The following table lists examples of tasks involving the My.Application.UnhandledException event.
To See
Use the events provided by the Visual Basic Application Model to run c How to: Run Code When the Application Starts or Ends
ode
Log unhandled exceptions How to: Log Exceptions in Visual Basic
Example
This example uses the My.Application.UnhandledException event to log any unhandled exceptions.
VB
Private Sub MyApplication_UnhandledException( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs _
) Handles Me.UnhandledException
My.Application.Log.WriteException(e.Exception, _
TraceEventType.Critical, _
"Unhandled Exception.")
End Sub
You must enter the code in the Code Editor window for application events. To access this window, follow the procedure found
in this topic's Remarks section. For more information, see How to: Handle Application Events (Visual Basic).
Because the UnhandledException event is not raised when a debugger is attached to the application, you need to run this
example outside of the Visual Studio Integrated Development Environment,
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Console Application No
Windows Service No
Web Site No
Permissions
The following permissions may be necessary:
Permission Description
SecurityPermission Controls the ability to add an event handler for this event. Associated enumeration:
System.Security.Permissions.SecurityPermissionFlag.ControlAppDomain.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Reference
My.Application.Info Object
Provides properties for getting the information about the application, such as the version number, description, loaded
assemblies, and so on.
Remarks
Some of the properties exposed by the My.Application.Info object return the application's assembly information. To set the
information in the application's assembly, you must use the Assembly Information dialog box, accessible from the
Application pane of the Project Designer. For more information, see How to: Specify Assembly Information.
The My.Application.Info object provides functionality similar to the FileVersionInfo class but is scoped to give quick access to
the most common properties.
Other properties, such as LoadedAssemblies, provide access to the current state of the application.
Example
This example uses the My.Application.Info.Version property to display the version of the application.
VB
MsgBox("Application version: " & My.Application.Info.Version.ToString)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Application.Info Object Members
My.Application Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo
FileVersionInfo
Visual Basic Language Reference
WorkingSet Gets the amount of physical memory mapped to the process context.
See Also
Reference
My.Application.Info Object
Visual Basic Language Reference
My.Application.Info.AssemblyName Property
Gets the name, without the extension, of the assembly file for the application.
' Usage
Dim value As String = My.Application.Info.AssemblyName
' Declaration
Public ReadOnly Property AssemblyName As String
Return Value
A String containing the file name.
Remarks
The My.Application.Info.AssemblyName property gets the name of the file containing the manifest.
Example
This example uses the My.Application.Info.AssemblyName property to display the name of the application.
VB
MsgBox("Application assembly name: " & My.Application.Info.AssemblyName)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application.Info Object
AssemblyName
Visual Basic Language Reference
My.Application.Info.CompanyName Property
Gets the company name associated with the application.
' Usage
Dim value As String = My.Application.Info.CompanyName
' Declaration
Public ReadOnly Property CompanyName As String
Return Value
A String that contains the company name associated with the application.
Exceptions
The following condition can cause an exception:
The assembly does not have an AssemblyCompanyAttribute (InvalidOperationException).
Remarks
The My.Application.Info.CompanyName property gets the company name associated with the application.
You can change the company name by changing the value for Company in the Assembly Information dialog box, accessible
from the Application pane of the Project Designer. For more information, see How to: Specify Assembly Information.
Example
This example uses the My.Application.Info.CompanyName property to display the company name associated with the
application.
VB
MsgBox("Application created by: " & My.Application.Info.CompanyName)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.CompanyName
Visual Basic Language Reference
My.Application.Info.Copyright Property
Gets the copyright notice associated with the application.
' Usage
Dim value As String = My.Application.Info.Copyright
' Declaration
Public ReadOnly Property Copyright As String
Return Value
A String containing the copyright notice associated with the application.
Exceptions
The following condition can cause an exception:
The assembly does not have an AssemblyCopyrightAttribute (InvalidOperationException).
Remarks
The My.Application.Info.CompanyName property gets the copyright notice associated with the application.
You can change the copyright notice by changing the value for Copyright in the Assembly Information dialog box,
accessible from the Application pane of the Project Designer. For more information, see
How to: Specify Assembly Information.
Example
This example uses the My.Application.Info.CompanyName property to display the company name associated with the
application.
VB
MsgBox("Application copyright: " & My.Application.Info.Copyright)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.Copyright
Visual Basic Language Reference
My.Application.Info.Description Property
Gets the description associated with the application.
' Usage
Dim value As String = My.Application.Info.Description
' Declaration
Public ReadOnly Property Description As String
Return Value
A String containing the description associated with the application.
Exceptions
The following condition can cause an exception:
The assembly does not have an AssemblyDescriptionAttribute (InvalidOperationException).
Remarks
The My.Application.Info.Description property gets the description associated with the application.
You can change the description by changing the value for Description in the Assembly Information dialog box, accessible
from the Application pane of the Project Designer. For more information, see How to: Specify Assembly Information.
Example
This example uses the My.Application.Info.Description property to display the description associated with the application.
VB
MsgBox("Application description: " & My.Application.Info.Description)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.Description
Visual Basic Language Reference
My.Application.Info.DirectoryPath Property
Gets the directory where the application is stored.
' Usage
Dim value As String = My.Application.Info.DirectoryPath
' Declaration
Public ReadOnly Property DirectoryPath As String
Return Value
A String that contains the directory where the application is stored.
Remarks
The My.Application.Info.DirectoryPath property gets the directory where the application is stored.
Example
This example uses the My.Application.Info.DirectoryPath property to display the directory path where the application is
stored.
VB
MsgBox("Application directory path: " & My.Application.Info.DirectoryPath)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.DirectoryPath
Visual Basic Language Reference
My.Application.Info.LoadedAssemblies Property
Gets a collection of all assemblies loaded by the application.
' Usage
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of System.Reflection.Assembl
y) = My.Application.Info.LoadedAssemblies
' Declaration
Public ReadOnly Property LoadedAssemblies As System.Collections.ObjectModel.ReadOnlyCollect
ion(Of System.Reflection.Assembly)
Return Value
A ReadOnlyCollection of Assembly containing all the assemblies loaded by the application.
Exceptions
The following condition can cause an exception:
The application domain is not loaded (AppDomainUnloadedException).
Remarks
The My.Application.Info.LoadedAssemblies property is similar to the GetAssemblies method.
Example
This example uses the My.Application.Info.LoadedAssemblies property to display the assemblies loaded by the application.
VB
ListBox1.DataSource = My.Application.Info.LoadedAssemblies
This example requires that your Windows Forms application has a ListBox control named ListBox1.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application.Info Object
ReadOnlyCollection
System.Reflection.Assembly
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.LoadedAssemblies
Visual Basic Language Reference
My.Application.Info.ProductName Property
Gets the product name associated with the application.
' Usage
Dim value As String = My.Application.Info.ProductName
' Declaration
Public ReadOnly Property ProductName As String
Return Value
A String containing the product name associated with the application.
Exceptions
The following condition can cause an exception:
The assembly does not have an AssemblyProductAttribute (InvalidOperationException).
Remarks
The My.Application.Info.ProductName property gets the product name associated with the application.
You can change the product name by changing the value for Product in the Assembly Information dialog box, accessible
from the Application pane of the Project Designer. For more information, see How to: Specify Assembly Information.
Example
This example uses the My.Application.Info.ProductName property to display the product name associated with the
application.
VB
MsgBox("Application product name: " & My.Application.Info.ProductName)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.ProductName
Visual Basic Language Reference
My.Application.Info.StackTrace Property
Gets the current stack-trace information.
' Usage
Dim value As String = My.Application.Info.StackTrace
' Declaration
Public ReadOnly Property StackTrace As String
Return Value
A String containing the current stack-trace information. The return value can be Empty.
Exceptions
The following condition can cause an exception:
The requested stack-trace information is out of range (ArgumentOutOfRangeException).
Remarks
The My.Application.Info.StackTrace property lists method calls in reverse chronological order—that is, it describes the most
recent method call first, and it lists each method call on the stack on a separate line. However, the
My.Application.Info.StackTrace property might not report as many method calls as expected, due to code transformations
that occur during optimization.
Typically, the stack-trace information is used for debugging applications.
The stack-trace information for each method call is formatted as follows:
"at FullClassName.MethodName(MethodParams) in FileName:line LineNumber "
The literal "at" is preceded by three spaces, and the literals "in" and ":line" are omitted if debug symbols are not available. The
placeholders FullClassName, MethodName, MethodParams, FileName, and LineNumber are replaced by actual values, defined
as follows:
Part Description
FullClass The full name of the class, including the namespace.
Name
MethodP The list of parameter type/name pairs. Each pair is separated by a comma (,). This information is omitted if MethodN
arams ame takes zero parameters.
FileNam The name of the source file where the MethodName method is declared. This information is omitted if debug symbol
e s are not available.
LineNum The number of the line in FileName that contains the source code from MethodName for the instruction that is on th
ber e call stack. This information is omitted if debug symbols are not available.
Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access information in the file paths. Associated enumeration: PathDiscovery.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application.Info Object
StackTrace
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.StackTrace
Visual Basic Language Reference
My.Application.Info.Title Property
Gets the title associated with the application.
' Usage
Dim value As String = My.Application.Info.Title
' Declaration
Public ReadOnly Property Title As String
Return Value
A String containing the AssemblyTitleAttribute associated with the application.
Exceptions
The following condition can cause an exception:
The assembly does not have an AssemblyTitleAttribute (InvalidOperationException).
Remarks
The My.Application.Info.Title property gets the title associated with the application.
You can change the title by changing the value for Title in the Assembly Information dialog box, accessible from the
Application pane of the Project Designer. For more information, see How to: Specify Assembly Information.
Example
This example uses the My.Application.Info.Title property to display the title associated with the application.
VB
MsgBox("Application title: " & My.Application.Info.Title)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.Title
Visual Basic Language Reference
My.Application.Info.Trademark Property
Gets the trademark notice associated with the application.
' Usage
Dim value As String = My.Application.Info.Trademark
' Declaration
Public ReadOnly Property Trademark As String
Return Value
A String containing the trademark notice associated with the application.
Exceptions
The following condition can cause an exception:
The assembly does not have an AssemblyTrademarkAttribute (InvalidOperationException).
Remarks
The My.Application.Info.Trademark property gets the trademark notice associated with the application.
You can change the trademark notice by changing the value for Trademark in the Assembly Information dialog box,
accessible from the Application pane of the Project Designer. For more information, see
How to: Specify Assembly Information.
Example
This example uses the My.Application.Info.Trademark property to display the trademark information associated with the
application.
VB
MsgBox("Application trademark: " & My.Application.Info.Trademark)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.Trademark
Visual Basic Language Reference
My.Application.Info.Version Property
Gets the version number of the application.
' Usage
Dim value As System.Version = My.Application.Info.Version
' Declaration
Public ReadOnly Property Version As System.Version
Return Value
A Version object containing the version number of the application.
Exceptions
The following condition can cause an exception:
The application does not have sufficient permissions to access the assembly version (SecurityException).
Remarks
The My.Application.Info.Version property gets a Version object containing the version number of the application. You can
use the Major, Minor, Build, and Revision properties of the Version object to access specific version information about the
application.
ClickOnce-deployed applications should use the CurrentVersion property of the My.Application.Deployment Property.
Example
This example uses the My.Application.Info.Version property to display the version of the application.
VB
MsgBox("Application version: " & My.Application.Info.Version.ToString)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application.Info Object
My.Application.Deployment Property
CurrentVersion
System.Version
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.Version
Visual Basic Language Reference
My.Application.Info.WorkingSet Property
Gets the amount of physical memory mapped to the process context.
' Usage
Dim value As Long = My.Application.Info.WorkingSet
' Declaration
Public ReadOnly Property WorkingSet As Long
Return Value
A Long containing the number of bytes of physical memory mapped to the process context.
Exceptions
The following condition can cause an exception:
A situation in which partial trust exists and the user lacks necessary permissions (SecurityException).
Remarks
The My.Application.Info.WorkingSet property has the same behavior as the WorkingSet property.
Note
This property always returns zero for Windows 98 and Windows Millennium Edition.
Example
This example uses the My.Application.Info.WorkingSet property to display the number of bytes of physical memory
mapped to the application.
VB
MsgBox("Application working set: " & My.Application.Info.WorkingSet)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
The following permission may be necessary:
Permission Description
EnvironmentPermission Controls the ability to access all environment variables. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application.Info Object
WorkingSet
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.WorkingSet
Visual Basic Language Reference
My.Application.Log Object
Provides a property and methods for writing event and exception information to the application's log listeners.
Remarks
The My.Application.Log object provides a straightforward entry point from which to access the .NET Framework's logging
services. The WriteEntry and WriteException methods write messages to the application's log listeners. The listeners can be
configured by the application's configuration file. For more information, see
Walkthrough: Changing Where My.Application.Log Writes Information and Working with Application Logs in Visual Basic.
The My.Application.Log object is available only for client applications. For Web applications, use My.Log. For more
information, see My.Log Object.
Tasks
The following table lists examples of tasks involving the My.Application.Log object.
To See
Write event information to the application's log liste How to: Write Log Messages
ners
Write exception information to the application's log l How to: Log Exceptions in Visual Basic
isteners
Determine where My.Application.Log writes infor Walkthrough: Determining Where My.Application.Log Writes Information
mation
Example
This example shows how to use the My.Application.Log.WriteEntry method to log tracing information. For more
information, see How to: Write Log Messages.
VB
Public Sub TracingTest(ByVal fileName As String)
My.Application.Log.WriteEntry( _
"Entering TracingTest with argument " & _
fileName & ".")
' Code to trace goes here.
My.Application.Log.WriteEntry( _
"Exiting TracingTest with argument " & _
fileName & ".")
End Sub
Requirements
Namespace: Microsoft.VisualBasic.Logging
Class: Log
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
See Also
Reference
My.Application.Log Object Members
My.Application Object
Visual Basic Language Reference
' Usage
Dim value As Logging.FileLogTraceListener = My.Application.Log.DefaultFileLogWriter
' Web usage
Dim value As Logging.FileLogTraceListener = My.Log.DefaultFileLogWriter
' Declaration
Public ReadOnly Property DefaultFileLogWriter As Logging.FileLogTraceListener
Return Value
Returns the FileLogTraceListener object that the Log object uses.
Remarks
You can use this property to determine the current configuration of the Log object's FileLogTraceListener object.
In client applications, the Log object is available through the My.Application.Log object. In Web applications, the Log object
is available through the My.Log object.
Requirements
Namespace: Microsoft.VisualBasic.Logging
Class: Log
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
Troubleshooting: Log Listeners
Reference
My.Application.Log Object
My.Log Object
FileLogTraceListener
Visual Basic Language Reference
' Usage
Dim value As System.Diagnostics.TraceSource = My.Application.Log.TraceSource
' Web usage
Dim value As System.Diagnostics.TraceSource = My.Log.TraceSource
' Declaration
Public ReadOnly Property TraceSource As System.Diagnostics.TraceSource
Return Value
Returns the TraceSource object that underlies the Log object.
Remarks
You can use this property to determine the current configuration of the Log object.
In client applications, the Log object is available through the My.Application.Log object. In Web applications, the Log object
is available through the My.Log object.
This is an advanced member; it does not show in IntelliSense unless you select the All tab.
Tasks
The following table lists an example of a task involving the TraceSource property.
To See
Get information for each of the Log object's log listeners. Troubleshooting: Log Listeners
Requirements
Namespace: Microsoft.VisualBasic.Logging
Class: Log
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
' Usage
My.Application.Log.WriteEntry(message)
My.Application.Log.WriteEntry(message ,severity)
My.Application.Log.WriteEntry(message ,severity ,id)
' Web usage
My.Log.WriteEntry(message)
My.Log.WriteEntry(message ,severity)
My.Log.WriteEntry(message ,severity ,id)
' Declaration
Public Sub WriteEntry( _
ByVal message As String _
)
' -or-
Public Sub WriteEntry( _
ByVal message As String, _
ByVal severity As System.Diagnostics.TraceEventType _
)
' -or-
Public Sub WriteEntry( _
ByVal message As String, _
ByVal severity As System.Diagnostics.TraceEventType, _
ByVal id As Integer _
)
Parameters
message
Required. The message to log. If message is Nothing, an empty string is used.
severity
The type of message. By default, TraceEventType.Information.
id
Message identifier, typically used for correlation. By default, related to entryType as described in the table.
Exceptions
The following conditions cause an exception:
The exception or message type is Nothing (ArgumentNullException).
The message type is not one of the TraceEventType enumeration values (InvalidEnumArgumentException).
Code with partial trust calls the method, but writes to an event log listener that requires full trust (SecurityException).
Remarks
The WriteEntry method writes a message to the application's event log listeners.
In client applications, the Log object is available through the My.Application.Log object. In Web applications, the Log object
is available through the My.Log object.
To learn which log listeners receive the WriteEntry method's messages, see
Walkthrough: Determining Where My.Application.Log Writes Information. You can change default log listeners. For more
information, see Working with Application Logs in Visual Basic.
For overloads that do not take the id argument, the id written to the log is defined by the following table.
severity Default id
Information 0
Warning 1
Error 2
Critical 3
Start 4
Stop 5
Suspend 6
Resume 7
Verbose 8
Transfer 9
Tasks
The following table lists examples of tasks involving the WriteEntry method.
To See
Write event information to the application's log liste How to: Write Log Messages
ners
Determine where Log writes information Walkthrough: Determining Where My.Application.Log Writes Information
Example
This example shows how to use the My.Application.Log.WriteEntry method to log tracing information. For more
information, see How to: Write Log Messages.
VB
Public Sub TracingTest(ByVal fileName As String)
My.Application.Log.WriteEntry( _
"Entering TracingTest with argument " & _
fileName & ".")
' Code to trace goes here.
My.Application.Log.WriteEntry( _
"Exiting TracingTest with argument " & _
fileName & ".")
End Sub
This code example can run only within a client application. Change My.Application.Log.WriteEntry to My.Log.WriteEntry
for Web applications.
Requirements
Namespace: Microsoft.VisualBasic.Logging
Class: Log
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Write Log Messages
Walkthrough: Determining Where My.Application.Log Writes Information
Reference
My.Application.Log Object
My.Log Object
System.Diagnostics.TraceEventType
Microsoft.VisualBasic.Logging.Log.WriteEntry(System.String)
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Reference
' Usage
My.Application.Log.WriteException(ex)
My.Application.Log.WriteException(ex ,severity ,additionalInfo)
My.Application.Log.WriteException(ex ,severity ,additionalInfo ,id)
' Web usage
My.Log.WriteException(ex)
My.Log.WriteException(ex ,severity ,additionalInfo)
My.Log.WriteException(ex ,severity ,additionalInfo ,id)
' Declaration
Public Sub WriteException( _
ByVal ex As System.Exception _
)
' -or-
Public Sub WriteException( _
ByVal ex As System.Exception, _
ByVal severity As System.Diagnostics.TraceEventType, _
ByVal additionalInfo As String _
)
' -or-
Public Sub WriteException( _
ByVal ex As System.Exception, _
ByVal severity As System.Diagnostics.TraceEventType, _
ByVal additionalInfo As String, _
ByVal id As Integer _
)
Parameters
ex
Required. Exception to log.
severity
The type of message. By default, Error.
additionalInfo
String to append to the message. By default, this is an empty string.
id
Message identifier, typically used for correlation. By default, related to entryType as described in the table in the Remarks
section.
Exceptions
The following conditions will cause an exception:
The exception or message type is Nothing (ArgumentNullException).
The message type is not one of the TraceEventType enumeration values (InvalidEnumArgumentException).
Code with partial trust calls the method, but writes to an event log listener that requires full trust (SecurityException).
Remarks
The WriteException method writes the information contained in an exception to the application's event log listeners.
In client applications, the Log object is available through the My.Application.Log object. In Web applications, the Log object
is available through the My.Log object.
To learn which log listeners receive the WriteException method's messages, see
Walkthrough: Determining Where My.Application.Log Writes Information. You can change default log listeners. For more
information, see Working with Application Logs in Visual Basic.
For overloads that do not take the id argument, the identifier written to the log is defined by the following table.
severity Default id
Information 0
Warning 1
Error 2
Critical 3
Start 4
Stop 5
Suspend 6
Resume 7
Verbose 8
Transfer 9
Tasks
The following table lists examples of tasks involving the WriteException method.
To See
Write exception information to the application's eve How to: Log Exceptions in Visual Basic
nt log listeners.
Determine where Log writes information. Walkthrough: Determining Where My.Application.Log Writes Information
Example
This example shows how to use the My.Application.Log.WriteException method to log exceptions. Uncomment the Dim and
MsgBox lines to cause a NullReferenceException exception. For more information, see How to: Log Exceptions in Visual Basic.
VB
Public Sub ExceptionLogTest(ByVal fileName As String)
Try
' Code that might generate an exception goes here.
' For example:
' Dim x As Object
' MsgBox(x.ToString)
Catch ex As Exception
My.Application.Log.WriteException(ex, _
TraceEventType.Error, _
"Exception in ExceptionLogTest " & _
"with argument " & fileName & ".")
End Try
End Sub
This code example can run only within a client application. Change My.Application.Log.WriteException to
My.Log.WriteException for Web applications.
Requirements
Namespace: Microsoft.VisualBasic.Logging
Class: Log
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Log Exceptions in Visual Basic
Walkthrough: Determining Where My.Application.Log Writes Information
Reference
My.Application.Log Object
My.Log Object
System.Exception
System.Diagnostics.TraceEventType
Microsoft.VisualBasic.Logging.Log.WriteException(System.Exception)
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Reference
My.Computer Object
Provides properties for manipulating computer components such as audio, the clock, the keyboard, the file system, and so on.
Remarks
The properties exposed by the My.Computer object return information about the computer on which the application is
deployed, as determined at run time. Typically, this data differs from what was available on the development computer.
Some members, such as the My.Computer.Audio object, are available only for non-server applications.
Tasks
The following table lists examples of tasks involving the My.Computer object.
To See
Check connection status How to: Check Connection Status in Visual Basic
Determine if a remote computer is available How to: Determine if a Remote Computer is Available in Visual Basic
Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic
Clear the Clipboard How to: Clear the Clipboard in Visual Basic
Read from the Clipboard How to: Read from the Clipboard in Visual Basic
Determine what is stored on the Clipboard How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Save audio to the Clipboard How to: Save an Audio Stream to the Clipboard in Visual Basic
Get an image from the Clipboard How to: Retrieve an Image from the Clipboard in Visual Basic
Example
This example uses the My.Computer.Name property to display the name of the computer on which the code runs.
VB
MsgBox("Computer name: " & My.Computer.Name)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer (the base class ServerComputer provides the members that are available in all projects)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer Object Members
My.Computer.Audio Object
My.Computer.Clipboard Object
My.Computer.Clock Object
My.Computer.FileSystem Object
My.Computer.Info Object
My.Computer.Keyboard Object
My.Computer.Mouse Object
My.Computer.Network Object
My.Computer.Ports Object
My.Computer.Registry Object
Microsoft.VisualBasic.Devices.Computer
Microsoft.VisualBasic.Devices.ServerComputer
Visual Basic Language Reference
Clipboard Returns the My.Computer.Clipboard Object, which provides methods for manipulating the Clipboard.
This object is available only for non-server applications.
Clock Returns the My.Computer.Clock Object, which provides properties for accessing the current local time and Univers
al Coordinated Time (equivalent to Greenwich Mean Time) from the system clock.
FileSystem Returns the My.Computer.FileSystem Object, which provides properties and methods for working with drives, files,
and directories.
Info Returns the My.Computer.Info Object, which provides properties for getting information about the computer's me
mory, loaded assemblies, name, and operating system.
Keyboard Returns the My.Computer.Keyboard Object, which provides properties for accessing the current state of the keyboa
rd, such as what keys are pressed, and provides a method to send keystrokes to the active window.
This object is available only for non-server applications.
Mouse Returns the My.Computer.Mouse Object, which provides properties for getting information about the format and c
onfiguration of the mouse installed on the local computer.
This object is available only for non-server applications.
Network Returns the My.Computer.Network Object, which can be used to access network types and events.
Ports Returns the My.Computer.Ports Object, which provides a property and a method for accessing the computer's seria
l ports.
This object is available only for non-server applications.
Registry Returns the My.Computer.Registry Object, which can be used to read from and write to the registry.
Screen Gets the Screen object that represents the computer's primary display screen.
This property is available only for non-server applications.
See Also
Reference
My.Computer Object
Visual Basic Language Reference
My.Computer.Audio Property
Gets an object that provides properties for methods for playing sounds.
' Usage
Dim value As Microsoft.VisualBasic.Devices.Audio = My.Computer.Audio
' Declaration
Public ReadOnly Property Audio As MyAudio
Return Value
This property returns the My.Computer.Audio object for the computer.
Remarks
This property provides easy access to the My.Computer.Audio object. For more information, see My.Computer.Audio Object.
Example
The My.Computer.Audio.Play method plays the specified sound in the background when AudioPlayMode.Background is
specified.
VB
Sub PlayBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.Background)
End Sub
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Audio Object
Visual Basic Language Reference
My.Computer.Clipboard Property
Gets an object that provides methods for manipulating the Clipboard.
' Usage
Dim value As Microsoft.VisualBasic.MyServices.ClipboardProxy = My.Computer.Clipboard
' Declaration
Public ReadOnly Property Clipboard As ClipboardProxy
Return Value
This property returns the My.Computer.Clipboard Object for the computer.
Remarks
This property provides easy access to the My.Computer.Clipboard Object.
This property is available only for non-server applications.
Example
This example reads text from the Clipboard into the string textOnClipboard.
VB
Dim textOnClipboard As String = My.Computer.Clipboard.GetText()
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Clipboard Object
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clock Property
Gets an object that provides properties for accessing the current local time and Universal Coordinated Time (the equivalent to
Greenwich Mean Time) from the system clock.
' Usage
Dim value As Microsoft.VisualBasic.Devices.Clock = My.Computer.Clock
' Declaration
Public ReadOnly Property Clock As MyClock
Return Value
This property returns the My.Computer.Clock object for the computer.
Remarks
This property provides easy access to the My.Computer.Clock object. For more information, see My.Computer.Clock Object.
Example
The My.Computer.Audio.Play method plays the specified sound in the background when AudioPlayMode.Background is
specified.
VB
Sub PlayBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.Background)
End Sub
My.Computer.FileSystem Property
Gets an object that provides properties and methods for working with drives, files, and directories.
' Usage
Dim value As Microsoft.VisualBasic.MyServices.FileSystemProxy = My.Computer.FileSystem
' Declaration
Public ReadOnly Property FileSystem As FileSystemProxy
Return Value
This property returns the My.Computer.FileSystem Object for the computer.
Remarks
This property provides easy access to the My.Computer.FileSystem Object.
Example
This example checks to determine whether the folder C:\backup\logs exists and checks its properties.
VB
Dim logInfo As System.IO.DirectoryInfo
If My.Computer.FileSystem.DirectoryExists("C:\backup\logs") Then
logInfo = My.Computer.FileSystem.GetDirectoryInfo _
("C:\backup\logs")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer, ServerComputer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Info Property
Gets an object that provides properties for getting information about the computer's memory, loaded assemblies, name, and
operating system.
' Usage
Dim value As Microsoft.VisualBasic.Devices.ComputerInfo = My.Computer.Info
' Declaration
Public ReadOnly Property Info As MyComputerInfo
Return Value
This property returns the My.Computer.Info object for the computer.
Remarks
This property provides easy access to the My.Computer.Info object. For more information, see My.Computer.Info Object.
Example
This example uses the My.Computer.Info.AvailablePhysicalMemory property to display the amount of available physical
memory for the computer on which the code runs.
VB
MsgBox("Computer's available physical memory: " & _
My.Computer.Info.AvailablePhysicalMemory)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer, ServerComputer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Keyboard Property
Gets an object that provides properties for accessing the current state of the keyboard, such as what keys are currently pressed,
and provides a method to send keystrokes to the active window.
' Usage
Dim value As Microsoft.VisualBasic.Devices.Keyboard = My.Computer.Keyboard
' Declaration
Public ReadOnly Property Keyboard As Microsoft.VisualBasic.Devices.Keyboard
Return Value
This property returns the My.Computer.Keyboard object for the computer.
Remarks
This property provides easy access to the My.Computer.Keyboard object. For more information, see
My.Computer.Keyboard Object.
Example
This example uses the My.Computer.Keyboard.CtrlKeyDown property to determine if the computer's CTRL key is currently
pressed.
VB
If My.Computer.Keyboard.CtrlKeyDown Then
MsgBox("CTRL key down")
Else
MsgBox("CTRL key up")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Keyboard Object
Visual Basic Language Reference
My.Computer.Mouse Property
Gets an object that provides properties for getting information about the format and configuration of the mouse installed on
the local computer.
' Usage
Dim value As Microsoft.VisualBasic.Devices.Mouse = My.Computer.Mouse
' Declaration
Public ReadOnly Property Mouse As Microsoft.VisualBasic.Devices.Mouse
Return Value
This property returns the My.Computer.Mouse object for the computer.
Remarks
This property provides easy access to the My.Computer.Mouse object. For more information, see
My.Computer.Mouse Object.
This property is available only for non-server applications.
Example
This example uses the My.Computer.Mouse.WheelExists and My.Computer.Mouse.WheelScrollLines properties to
determine if the mouse has a scroll wheel and how much to scroll when it rotates.
VB
If My.Computer.Mouse.WheelExists Then
Dim lines As Integer = My.Computer.Mouse.WheelScrollLines
If lines > 0 Then
MsgBox("Application scrolls " & _
lines & " line(s) for each wheel turn.")
Else
MsgBox("Application scrolls " & _
(-lines) & " page(s) for each wheel turn.")
End If
Else
MsgBox("Mouse has no scroll wheel.")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Mouse Object
Visual Basic Language Reference
My.Computer.Name Property
Gets the computer name.
' Usage
Dim value As String = My.Computer.Name
' Declaration
Public ReadOnly Property Name As String
Return Value
A String containing the name of the computer.
Remarks
The My.Computer.Name property provides functionality similar to the MachineName property.
Example
This example uses the My.Computer.Name property to display the name of the computer on which the code runs.
VB
MsgBox("Computer name: " & My.Computer.Name)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer, ServerComputer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Network Property
Gets an object that provides a property and methods for interacting with the network to which the computer is connected.
' Usage
Dim value As Microsoft.VisualBasic.Devices.Network = My.Computer.Network
' Declaration
Public ReadOnly Property Network As MyNetwork
Return Value
This property returns the My.Computer.Network Object for the computer.
Remarks
This property provides easy access to the My.Computer.Network Object.
Example
This example uploads the file Order.txt to http://www.cohowinery.com/uploads.
VB
My.Computer.Network.UploadFile ( _
"C:\My Documents\Order.txt", _
"http://www.cohowinery.com/uploads.aspx")
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer, ServerComputer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Ports Property
Gets an object that provides a property and a method for accessing the computer's serial ports.
' Usage
Dim value As Microsoft.VisualBasic.Devices.Ports = My.Computer.Ports
' Declaration
Public ReadOnly Property Ports As MyPorts
Return Value
This property returns the My.Computer.Ports object.
Remarks
This property provides easy access to the My.Computer.Ports object. For more information, see My.Computer.Ports Object.
Example
This example describes how to send strings to the computer's COM1 serial port.
The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates the
serial port should appear within this block, or within a Try...Catch...Finally block with a call to use the Close method.
The WriteLine method sends the data to the serial port.
VB
Sub SendSerialData(ByVal data As String)
' Send strings to a serial port.
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1")
com1.WriteLine(data)
End Using
End Sub
For more information, see How to: Send Strings to Serial Ports in Visual Basic.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Ports Object
Visual Basic Language Reference
My.Computer.Registry Property
Gets an object that provides properties and methods for manipulating the registry.
' Usage
Dim value As Microsoft.VisualBasic.MyServices.RegistryProxy = My.Computer.Registry
' Declaration
Public ReadOnly Property Registry As RegistryProxy
Return Value
This property returns the My.Computer.Registry Object for the computer.
Remarks
This property provides easy access to the My.Computer.Registry Object.
Example
This example reads the value Name from HKEY_CURRENT_USER\Software\MyApp and displays it in a message box.
VB
Dim readValue As Object
readValue = My.Computer.Registry.GetValue _
("HKEY_CURRENT_USER\Software\MyApp", "Name", Nothing)
MsgBox("The value is " & CStr(readValue))
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer, ServerComputer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Registry Object
Concepts
Common Registry Tasks
Visual Basic Language Reference
My.Computer.Screen Property
Gets the Screen object that represents the computer's primary display screen.
' Usage
Dim value As System.Windows.Forms.Screen = My.Computer.Screen
' Declaration
Public ReadOnly Property Screen As System.Windows.Forms.Screen
Return Value
A Screen object that represents the computer's primary screen.
Remarks
The My.Computer.Screen property provides functionality similar to the PrimaryScreen property.
Example
This example uses the WorkingArea property of the My.Computer.Screen property to determine the working area of the
computer's primary display, and then resizes the form to fill the working area.
VB
Private Sub EnlargeForm()
Me.Size = My.Computer.Screen.WorkingArea.Size
Me.Location = New System.Drawing.Point(0, 0)
End Sub
Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer Object
System.Windows.Forms.Screen
PrimaryScreen
Microsoft.VisualBasic.Devices.Computer.Screen
Visual Basic Language Reference
My.Computer.Audio Object
Provides methods for playing sounds.
Remarks
You can use the My.Computer.Audio.Play and My.Computer.Audio.PlaySystemSound methods to play .wav sound files
and system sounds.
Tasks
The following table lists examples of tasks involving the My.Computer.Audio object.
To See
Play a sound in the background. How to: Play Sounds in Visual Basic
Play a sound once and wait for completion. How to: Play Sounds and Wait For Completion in Visual Basic
Play a sound many times. How to: Play Looping Sounds in Visual Basic
Stop a sound playing in the background. How to: Stop Playing Sounds in the Background in Visual Basic
Example
The My.Computer.Audio.Play method plays the specified sound in the background when AudioPlayMode.Background is
specified.
VB
Sub PlayBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.Background)
End Sub
Web Site No
See Also
Reference
My.Computer.Audio Object Members
My.Computer Object
Visual Basic Language Reference
My.Computer.Audio.Play Method
Plays a .wav sound file.
' Usage
My.Computer.Audio.Play(location)
My.Computer.Audio.Play(location ,playMode)
My.Computer.Audio.Play(data ,playMode)
My.Computer.Audio.Play(stream ,playMode)
' Declaration
Public Sub Play( _
ByVal location As String _
)
' -or-
Public Sub Play( _
ByVal location As String, _
ByVal playMode As AudioPlayMode _
)
' -or-
Public Sub Play( _
ByVal data As Byte(), _
ByVal playMode As AudioPlayMode _
)
' -or-
Public Sub Play( _
ByVal stream As System.IO.Stream, _
ByVal playMode As AudioPlayMode _
)
Parameters
location
A String containing the name of the sound file
data
Byte array that represents the sound file.
stream
Stream that represents the sound file.
playMode
AudioPlayMode Enumeration mode for playing the sound. By default, AudioPlayMode.Background.
Exceptions
The following conditions can cause an exception:
The data or stream is Nothing, or location is an empty string (ArgumentNullException).
The playMode argument is not one of the AudioPlayMode Enumeration values (InvalidEnumArgumentException).
The user does not have sufficient permissions to access the file named by location (IOException).
The file path is malformed in location (DirectoryNotFoundException)
The path name in location is too long (PathTooLongException)
A partial-trust situation exists in which the user lacks necessary permissions (SecurityException).
Remarks
The Play method plays the .wav sound file stored as a file at location, as a byte array in data, or as a stream in stream.
If the overload that takes only the location parameter is used, the Play method plays the sound in the background. Otherwise,
the playMode parameter determines how the sound will play.
playMode Description
AudioPlayMode.Backgrou Plays the sound in the background. The calling code continues to execute.
nd
AudioPlayMode.Backgrou Plays the sound in the background until the My.Computer.Audio.Stop Method is called. The callin
ndLoop g code continues to execute.
AudioPlayMode.WaitToC Plays the sound and waits until it completes before the calling code continues.
omplete
Background playing lets the application execute other code while the sound plays. For more information, see
How to: Play Looping Sounds in Visual Basic and How to: Play Sounds in Visual Basic.
Tasks
The following table lists examples of tasks involving the My.Computer.Audio.Play method.
To See
Play a sound once How to: Play Sounds and Wait For Completion in Visual Basic
Play a sound many times How to: Play Looping Sounds in Visual Basic
Play a sound in the background How to: Play Sounds in Visual Basic
Example
The My.Computer.Audio.Play method plays the specified sound in the background when PlayMode.Background is
specified.
VB
Sub PlayBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.Background)
End Sub
This code example can only run within a Windows Forms application.
The file name should reference a .wav sound file on your system.
To simplify the management of your sound files, consider storing the files as application resources. They can then be accessed
through the My.Resources Object.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Audio
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlThread.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Play Sounds and Wait For Completion in Visual Basic
How to: Play Looping Sounds in Visual Basic
How to: Play Sounds in Visual Basic
Reference
My.Computer.Audio Object
My.Computer.Audio.Stop Method
AudioPlayMode Enumeration
System.IO.Stream
Microsoft.VisualBasic.Devices.Audio.Play(System.String)
Visual Basic Language Reference
My.Computer.Audio.PlaySystemSound Method
Plays a system sound.
' Usage
My.Computer.Audio.PlaySystemSound(systemSound)
' Declaration
Public Sub PlaySystemSound( _
ByVal systemSound As System.Media.SystemSound _
)
Parameters
systemSound
SystemSound object representing the system sound to play.
Exceptions
The following condition can cause an exception:
The systemSound is Nothing (ArgumentNullException).
Remarks
The PlaySystemSound method plays the system sound described by systemSound; the sound is played once, in the
background.
The value of systemSound must be one of the shared members from the SystemSounds class:
Asterisk
Beep
Exclamation
Hand
Question
Tasks
The following table lists an example of a task involving the My.Computer.Audio.PlaySystemSound method.
To See
Play a system sound How to: Play System Sounds in Visual Basic
Example
This example uses the My.Computer.Audio.PlaySystemSound method to play a system sound.
VB
Sub PlaySystemSound()
My.Computer.Audio.PlaySystemSound( _
System.Media.SystemSounds.Asterisk)
End Sub
This code example can run only within a Windows Forms application.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Audio
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Play System Sounds in Visual Basic
Reference
My.Computer.Audio Object
System.Media.SystemSound
SystemSounds
Microsoft.VisualBasic.Devices.Audio.PlaySystemSound(System.Media.SystemSound)
Visual Basic Language Reference
My.Computer.Audio.Stop Method
Stops a sound playing in the background.
' Usage
My.Computer.Audio.Stop()
' Declaration
Public Sub Stop()
Remarks
The My.Computer.Audio.Stop method stops a sound playing in the background that was started by the
My.Computer.Audio.Play method.
Background playing lets the application execute other code while the sound plays. For more information, see
How to: Play Looping Sounds in Visual Basic and How to: Play Sounds in Visual Basic.
In general, when an application plays a looping sound, it should stop the sound at some point.
Tasks
The following table lists an example of a task involving the My.Computer.Audio.Stop method.
To See
Stop a sound playing in the background How to: Stop Playing Sounds in the Background in Visual Basic
Example
This example uses the My.Computer.Audio.Stop method to stop the application currently playing background or looping
sound and uses the My.Computer.Audio.Play method to play a looping sound in the background.
VB
Sub PlayLoopingBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.BackgroundLoop)
End Sub
Sub StopBackgroundSound()
My.Computer.Audio.Stop()
End Sub
This code example can run only within a Windows Forms application.
The file name should reference a .wav sound file on your system.
To simplify the management of your sound files, consider storing the files as application resources. These files can then be
accessed through the My.Resources Object.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Audio
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Stop Playing Sounds in the Background in Visual Basic
Reference
My.Computer.Audio Object
Microsoft.VisualBasic.Devices.Audio.Stop
Visual Basic Language Reference
My.Computer.Clipboard Object
Provides methods for manipulating the Clipboard.
Remarks
Items moved or copied to the Clipboard persist even after the application is shut down.
Data on the Clipboard can be in any data format, also called a Clipboard format. For a list of predefined formats to use with the
Clipboard, see DataFormats. When an item is moved or copied to the Clipboard, items in other formats are cleared. To make
other formats persist, use DataObject, which copies everything existing on the current Clipboard, including items pasted from
other applications. Place data on the Clipboard in multiple formats to maximize the possibility that a target application, whose
format requirements you might not know, can successfully retrieve the data.
Because all Windows applications share the system Clipboard, the contents may change when you switch to another
application.
A class must be serializable for it to be put on the Clipboard. See Serialization for more information.
When accessing the Clipboard remotely, a ThreadStateException is thrown unless the accessing thread operates in STA (single-
threaded apartment) mode. To resolve this issue, set the ThreadApartmentState to STA. For more information, see
STAThreadAttribute.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard object.
To See
Clear the Clipboard How to: Clear the Clipboard in Visual Basic
Read from the Clipboard How to: Read from the Clipboard in Visual Basic
Find out what is stored on the Clipboard How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Save audio to the Clipboard How to: Save an Audio Stream to the Clipboard in Visual Basic
Get an image from the Clipboard How to: Retrieve an Image from the Clipboard in Visual Basic
Store data to the Clipboard How to: Write to the Clipboard in Visual Basic
Example
This example reads text from the Clipboard into the string textOnClipboard.
VB
Dim textOnClipboard As String = My.Computer.Clipboard.GetText()
Web Site No
See Also
Reference
My.Computer.Clipboard Object Members
My.Computer Object
System.Windows.Forms.Clipboard
Visual Basic Language Reference
ContainsData Determines whether the clipboard contains data in the specified custom format.
This method is available only for non-server applications.
GetDataObject Retrieves a data object from the clipboard. This method is available only for non-server applications.
My.Computer.Clipboard.Clear Method
Clears the Clipboard.
' Usage
My.Computer.Clipboard.Clear()
' Declaration
Public Sub Clear()
Remarks
The UIPermission class controls access to the Clipboard, and the associated UIPermissionClipboard enumeration value
indicates the level of access. For more information, see Additional Security Considerations in Windows Forms.
Tasks
The following table lists an example of a task involving the My.Computer.Clipboard.Clear method.
To See
Clear the Clipboard How to: Clear the Clipboard in Visual Basic
Example
This example clears the Clipboard.
My.Computer.Clipboard.Clear()
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Clear the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard Object Members
System.Windows.Forms.Clipboard.Clear
Visual Basic Language Reference
My.Computer.Clipboard.ContainsAudio Method
Indicates whether the Clipboard contains audio data.
' Usage
Dim value As Boolean = My.Computer.Clipboard.ContainsAudio()
' Declaration
Public Function ContainsAudio() As Boolean
Return Value
True if audio data is stored on the Clipboard; otherwise False.
Remarks
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.ContainsAudio method.
To See
Determine what type of data is stored on the Cl How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
ipboard
Example
This example determines whether the Clipboard contains audio data and displays the result.
VB
If My.Computer.Clipboard.ContainsAudio() Then
MsgBox("The clipboard contains audio data.")
Else
MsgBox("The clipboard does not contain audio data.")
End If
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.GetAudioStream Method
My.Computer.Clipboard.SetAudio Method
System.Windows.Forms.Clipboard.ContainsAudio
Other Resources
Playing Sounds
Visual Basic Language Reference
My.Computer.Clipboard.ContainsData Method
Indicates whether the Clipboard contains data in the specified custom format.
' Usage
Dim value As Boolean = My.Computer.Clipboard.ContainsData(format)
' Declaration
Public Function ContainsData( _
ByVal format As String _
) As Boolean
Parameters
format
String. Name of the custom format to be checked. Required.
Return Value
True if data in the specified custom format is stored on the Clipboard; otherwise False.
Exceptions
This method throws no exceptions.
Remarks
If you have placed custom formatted data on the Clipboard, this method allows you to check the Clipboard for data in that
format.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.ContainsData method.
To See
Determine what type of data is stored on the Cl How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
ipboard
Example
This example checks for data in the custom format specialFormat.
VB
If My.Computer.Clipboard.ContainsData("specialFormat") Then
MsgBox("Data found.")
End If
Replace specialFormat with the name of the custom format you wish to check.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.GetData Method
My.Computer.Clipboard.GetDataObject Method
My.Computer.Clipboard.SetData Method
My.Computer.Clipboard.SetDataObject Method
ContainsData
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.ContainsFileDropList Method
Returns a Boolean indicating whether the Clipboard contains a file drop list.
' Usage
Dim value As Boolean = My.Computer.Clipboard.ContainsFileDropList()
' Declaration
Public Function ContainsFileDropList() As Boolean
Return Value
True if a file drop list is stored on the Clipboard; otherwise False.
Remarks
A file drop list is a collection of strings containing path information for files.
Example
This example determines if there is a file drop list on the Clipboard and adds the list to the ListBox lstFiles if they exist.
VB
If My.Computer.Clipboard.ContainsFileDropList Then
Dim filelist As System.Collections.Specialized.StringCollection
filelist = My.Computer.Clipboard.GetFileDropList()
For Each filePath As String In filelist
lstFiles.Items.Add(filePath)
Next
End If
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.GetFileDropList Method
My.Computer.Clipboard.SetFileDropList Method
System.Windows.Forms.Clipboard.ContainsFileDropList
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.ContainsImage Method
Returns a Boolean indicating whether an image is stored on the Clipboard.
' Usage
Dim value As Boolean = My.Computer.Clipboard.ContainsImage()
' Declaration
Public Function ContainsImage() As Boolean
Return Value
True if an image is stored on the Clipboard; otherwise False.
Exceptions
This method throws no exceptions.
Remarks
The method requires AllClipboard.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.ContainsImage method.
To See
Determine whether the Clipboard contains an image How to: Retrieve an Image from the Clipboard in Visual Basic
Example
This example checks to see if there is an image on the Clipboard and, if so, gets the image and adds it to PictureBox1.
VB
If My.Computer.Clipboard.ContainsImage() Then
Dim grabpicture As System.Drawing.Image
grabpicture = My.Computer.Clipboard.GetImage()
PictureBox1.Image = grabpicture
End If
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.GetImage Method
My.Computer.Clipboard.SetImage Method
System.Windows.Forms.Clipboard.ContainsImage
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.ContainsText Method
Determines if there is text on the Clipboard.
' Usage
Dim value As Boolean = My.Computer.Clipboard.ContainsText()
Dim value As Boolean = My.Computer.Clipboard.ContainsText(format)
' Declaration
Public Function ContainsText() As Boolean
' -or-
Public Function ContainsText( _
ByVal format As System.Windows.Forms.TextDataFormat _
) As Boolean
Parameters
format
TextDataFormat. If specified, identifies what text format to be checked for. Required.
Return Value
True if the Clipboard contains text; otherwise False.
Remarks
Possible formats are CommaSeparatedValue, Html, Rtf and UnicodeText.
The method requires AllClipboard.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.ContainsText method.
To See
Determine whether the Clipboard contains text How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Example
This example determines if HTML text is stored on the Clipboard and reads from the Clipboard if it does.
VB
If My.Computer.Clipboard.ContainsText _
(System.Windows.Forms.TextDataFormat.Html) Then
Dim clipText As String = My.Computer.Clipboard.GetText()
End If
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.GetText Method
My.Computer.Clipboard.SetText Method
System.Windows.Forms.TextDataFormat
System.Windows.Forms.Clipboard.ContainsText
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.GetAudioStream Method
Retrieves an audio stream from the Clipboard.
' Usage
Dim value As System.IO.Stream = My.Computer.Clipboard.GetAudioStream()
' Declaration
Public Function GetAudioStream() As System.IO.Stream
Return Value
Stream
Remarks
Example
This example retrieves an audio stream from the Clipboard and plays it.
VB
If My.Computer.Clipboard.ContainsAudio Then
Dim song As System.IO.Stream
song = My.Computer.Clipboard.GetAudioStream
My.Computer.Audio.Play(song, AudioPlayMode.WaitToComplete)
End If
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsAudio Method
My.Computer.Clipboard.SetAudio Method
System.IO.Stream
System.Windows.Forms.Clipboard.GetAudioStream
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.GetData Method
Retrieves data in a custom format from the Clipboard.
' Usage
Dim value As Object = My.Computer.Clipboard.GetData(format)
' Declaration
Public Function GetData( _
ByVal format As String _
) As Object
Parameters
format
String. Name of the data format. Required.
Return Value
Object.
Remarks
Example
This example reads data in the format specialformat from the Clipboard and writes it to file.
VB
Dim someData As Object
someData = My.Computer.Clipboard.GetData("specialformat")
My.Computer.FileSystem.WriteAllBytes("C:\\mylogfile", someData, True)
Replace specialformat with the custom data format you wish to retrieve.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsData Method
My.Computer.Clipboard.GetDataObject Method
My.Computer.Clipboard.SetData Method
My.Computer.Clipboard.SetDataObject Method
GetData
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.GetDataObject Method
Retrieves data from the Clipboard as an IDataObject.
' Usage
Dim value As System.Windows.Forms.IDataObject = My.Computer.Clipboard.GetDataObject()
' Declaration
Public Function GetDataObject() As System.Windows.Forms.IDataObject
Return Value
IDataObject
Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Example
This example reads data from the Clipboard in the form of an IDataObject and then writes it to a file.
VB
Dim someData As Object
someData = My.Computer.Clipboard.GetDataObject()
My.Computer.FileSystem.WriteAllBytes("C:\mylogfile", someData, True)
Replace C:\mylogfile with the name of the file to which you want to write.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsData Method
My.Computer.Clipboard.GetData Method
My.Computer.Clipboard.SetData Method
My.Computer.Clipboard.SetDataObject Method
System.Windows.Forms.IDataObject
System.Windows.Forms.Clipboard.GetDataObject
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.GetFileDropList Method
Retrieves a collection of strings representing file names from the Clipboard.
' Usage
Dim value As System.Collections.Specialized.StringCollection = My.Computer.Clipboard.GetFil
eDropList()
' Declaration
Public Function GetFileDropList() As System.Collections.Specialized.StringCollection
Return Value
StringCollection
Remarks
This method is available only for non-server applications.
A file drop list is a collection of strings containing path information for files.
Example
This example determines if there is a file drop list on the Clipboard and adds the list to the ListBox lstFiles if they exist.
VB
If My.Computer.Clipboard.ContainsFileDropList Then
Dim filelist As System.Collections.Specialized.StringCollection
filelist = My.Computer.Clipboard.GetFileDropList()
For Each filePath As String In filelist
lstFiles.Items.Add(filePath)
Next
End If
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsFileDropList Method
My.Computer.Clipboard.SetFileDropList Method
System.Collections.Specialized.StringCollection
System.Windows.Forms.Clipboard.GetFileDropList
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.GetImage Method
Retrieves an image from the Clipboard.
' Usage
Dim value As System.Drawing.Image = My.Computer.Clipboard.GetImage()
' Declaration
Public Function GetImage() As System.Drawing.Image
Return Value
Image
Remarks
The GetImage method will return Nothing if there is no data on the Clipboard that is an image.
The method requires AllClipboard.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.GetImage method.
To See
Retrieve an image from the Clipboard How to: Retrieve an Image from the Clipboard in Visual Basic
Example
This example checks to see if there is an image on the Clipboard before retrieving it and assigning it to PictureBox1.
VB
If My.Computer.Clipboard.ContainsImage() Then
Dim grabpicture As System.Drawing.Image
grabpicture = My.Computer.Clipboard.GetImage()
PictureBox1.Image = grabpicture
End If
For this example to function correctly, there must be a PictureBox named PictureBox1 on your form.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Clipboard.GetText Method
Retrieves text from the Clipboard.
' Usage
Dim value As String = My.Computer.Clipboard.GetText()
Dim value As String = My.Computer.Clipboard.GetText(format)
' Declaration
Public Function GetText() As String
' -or-
Public Function GetText( _
ByVal format As System.Windows.Forms.TextDataFormat _
) As String
Parameters
format
TextDataFormat. If specified, identifies what text format should be retrieved. Default is CommaSeparatedValue. Required.
Return Value
String.
Exceptions
This method throws no exceptions.
Remarks
Possible formats are CommaSeparatedValue, Html, Rtf and UnicodeText.
The method requires AllClipboard.
This method returns an empty string if there is no data on the Clipboard that matches the specified format.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.GetText method.
To See
Read text from the Clipboard How to: Read from the Clipboard in Visual Basic
Example
This example reads text from the Clipboard into the string textOnClipboard.
VB
Dim textOnClipboard As String = My.Computer.Clipboard.GetText()
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Read from the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsText Method
My.Computer.Clipboard.SetText Method
System.Windows.Forms.TextDataFormat
System.Windows.Forms.Clipboard.GetText
Visual Basic Language Reference
My.Computer.Clipboard.SetAudio Method
Writes audio data to the Clipboard.
' Usage
My.Computer.Clipboard.SetAudio(audioBytes)
My.Computer.Clipboard.SetAudio(audioStream)
' Declaration
Public Sub SetAudio( _
ByVal audioBytes As Byte() _
)
' -or-
Public Sub SetAudio( _
ByVal audioStream As System.IO.Stream _
)
Parameters
audioBytes
Byte array. Audio data to be written to the Clipboard. Required.
audioStream
Stream Audio data to be written to the clipboard. Required.
Exceptions
No exceptions are thrown by this method.
Remarks
This method can be used to write the audio data as either a byte array or an audio stream.
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.SetAudio method.
To See
Write audio data to the Clipboard How to: Save an Audio Stream to the Clipboard in Visual Basic
Example
This example creates the byte array musicReader, reads the file cool.wav into it, and then writes it to the Clipboard.
VB
Dim musicReader As Byte()
musicReader = My.Computer.FileSystem.ReadAllBytes("cool.wav")
My.Computer.Clipboard.SetAudio(musicReader)
Replace cool.wav with the name and path of the file you wish to read.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsAudio Method
My.Computer.Clipboard.GetAudioStream Method
System.IO.Stream
System.Windows.Forms.Clipboard.SetAudio
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.SetData Method
Writes data in a custom format to the Clipboard.
' Usage
My.Computer.Clipboard.SetData(format ,data)
' Declaration
Public Sub SetData( _
ByVal format As String, _
ByVal data As Object _
)
Parameters
format
String. Format of data. Required.
data
Object. Data object to be written to the Clipboard. Required.
Exceptions
This method throws no exceptions.
Remarks
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.
Example
This example writes the DataObject dataChunk to the Clipboard in the custom format specialFormat.
VB
My.Computer.Clipboard.SetData("specialFormat", dataChunk)
This example depends on the existence of the custom data format specialFormat.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsData Method
My.Computer.Clipboard.GetData Method
My.Computer.Clipboard.GetDataObject Method
My.Computer.Clipboard.SetDataObject Method
SetData
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.SetDataObject Method
Writes a DataObject to the Clipboard.
' Usage
My.Computer.Clipboard.SetDataObject(data)
' Declaration
Public Sub SetDataObject( _
ByVal data As System.Windows.Forms.DataObject _
)
Parameters
data
DataObject. Data object to be written to the Clipboard. Required.
Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.
Example
This example writes the data object dataChunk to the Clipboard.
VB
My.Computer.Clipboard.SetDataObject(dataChunk)
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsData Method
My.Computer.Clipboard.GetData Method
My.Computer.Clipboard.GetDataObject Method
My.Computer.Clipboard.SetData Method
SetDataObject
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.SetFileDropList Method
Writes a collection of strings representing file paths to the Clipboard.
' Usage
My.Computer.Clipboard.SetFileDropList(filePaths)
' Declaration
Public Sub SetFileDropList( _
ByVal filePaths As System.Collections.Specialized.StringCollection _
)
Parameters
filePaths
StringCollection. List of file names. Required.
Remarks
A file drop list is a collection of strings representing file names.
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.
Example
This example gets the collection of file names from MyDocuments, converts it to a file drop list, and writes it to the Clipboard.
VB
Dim list As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
list = My.Computer.FileSystem.GetFiles _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
Dim listReader As New System.Collections.Specialized.StringCollection
For Each item As String In list
listReader.Add(item)
Next
My.Computer.Clipboard.SetFileDropList(listReader)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsFileDropList Method
My.Computer.Clipboard.GetFileDropList Method
System.Collections.Specialized.StringCollection
SetFileDropList
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.SetImage Method
Writes an image to the Clipboard.
' Usage
My.Computer.Clipboard.SetImage(image)
' Declaration
Public Sub SetImage( _
ByVal image As System.Drawing.Image _
)
Parameters
image
Image. Image to be written. Required.
Remarks
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.
Example
This example writes the image coolPicture to the Clipboard.
VB
My.Computer.Clipboard.SetImage(coolPicture)
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Retrieve an Image from the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsImage Method
My.Computer.Clipboard.GetImage Method
System.Drawing.Image
System.Windows.Forms.Clipboard.SetImage(System.Drawing.Image)
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clipboard.SetText Method
Writes text to the Clipboard.
' Usage
My.Computer.Clipboard.SetText(text)
My.Computer.Clipboard.SetText(text ,format)
' Declaration
Public Sub SetText( _
ByVal text As String _
)
' -or-
Public Sub SetText( _
ByVal text As String, _
ByVal format As System.Windows.Forms.TextDataFormat _
)
Parameters
text
String. Text to be written. Required.
format
TextDataFormat. Format to be used when writing text. Default is UnicodeText. Required.
Exceptions
The following conditions may cause an exception:
text is an empty string (ArgumentException).
text is Nothing (ArgumentNullException).
Remarks
Possible formats are CommaSeparatedValue, Html, Rtf and UnicodeText.
The method requires AllClipboard.
Previous Clipboard formats are not preserved.
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.SetText method.
To See
Write text to the Clipboard How to: Write to the Clipboard in Visual Basic
Example
This example writes the string This is a test string. to the Clipboard.
VB
My.Computer.Clipboard.SetText("This is a test string.")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsText Method
My.Computer.Clipboard.GetText Method
System.Windows.Forms.TextDataFormat
System.Windows.Forms.Clipboard.SetText
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference
My.Computer.Clock Object
Provides properties for accessing the current local time and Universal Coordinated Time (equivalent to Greenwich Mean Time)
from the system clock.
Remarks
The My.Computer.Clock object provides properties to find the current local time for the computer and the UTC time. It also
exposes the millisecond count from the computer's system timer.
Example
This example uses the My.Computer.Clock.LocalTime property to display the local time of the computer on which the code
runs.
VB
MsgBox("Current local time: " & My.Computer.Clock.LocalTime)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Clock
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.Clock Object Members
My.Computer Object
Microsoft.VisualBasic.Devices.Clock
Visual Basic Language Reference
LocalTime Gets a Date object that contains the current local date and time on this computer.
TickCount Gets the millisecond count from the computer's system timer.
See Also
Reference
My.Computer.Clock Object
Visual Basic Language Reference
My.Computer.Clock.GmtTime Property
Gets a Date object that contains the current local date and time on the computer, expressed as a UTC (GMT) time.
' Usage
Dim value As Date = My.Computer.Clock.GmtTime
' Declaration
Public ReadOnly Property GmtTime As Date
Return Value
A Date object that contains the current date and time expressed as UTC (GMT) time.
Remarks
The My.Computer.Clock.GmtTime property has the same behavior as the System.DateTime.UtcNow property.
Example
This example uses the My.Computer.Clock.GmtTime property to display the GMT time of the computer on which the code
runs.
VB
MsgBox("Current GMT time: " & My.Computer.Clock.GmtTime)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Clock
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Clock.LocalTime Property
Gets a Date object that contains the current local date and time on this computer.
' Usage
Dim value As Date = My.Computer.Clock.LocalTime
' Declaration
Public ReadOnly Property LocalTime As Date
Return Value
A Date object that contains the current local date and time.
Remarks
The My.Computer.Clock.LocalTime property has the same behavior as the System.DateTime.Now property.
Example
This example uses the My.Computer.Clock.LocalTime property to display the local time of the computer on which the code
runs.
VB
MsgBox("Current local time: " & My.Computer.Clock.LocalTime)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Clock
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Clock.TickCount Property
Gets the millisecond count from the computer's system timer.
' Usage
Dim value As Integer = My.Computer.Clock.TickCount
' Declaration
Public ReadOnly Property TickCount As Integer
Return Value
An Integer containing the millisecond count from the computer's system timer.
Remarks
The TickCount property provides access to the computer's system timer, which runs when the computer is active. The timer
resolution is not less than 500 milliseconds.
You can use this property to make your application's behavior dependent on the length of time it has been running, or you can
use it to label events, both of which are independent of the computer's clock.
Caution
When the value of the TickCount property reaches the maximum integer value (MaxValue), it then jumps to the minimum in
teger value (MinValue), a negative number, and continues to increment.
If the computer runs continuously, TickCount increments from zero to the maximum integer value in approximately 24.9 days.
The TickCount property increments only when the operating system is running; it pauses when the computer goes into
certain power-saving modes, such as standby or hibernation. The TickCount property is unrelated to the computer's clock
setting.
Use the My.Computer.Clock.LocalTime Property or My.Computer.Clock.GmtTime Property to obtain the current local date and
time on this computer.
The My.Computer.Clock.TickCount property has the same behavior as the System.Environment.TickCount property.
Example
The following example uses the My.Computer.Clock.TickCount property to run a task in a loop for a given number of
seconds, even if the computer's system time changes while it runs.
VB
Public Sub LoopTask(ByVal secondsToRun As Integer)
Dim startTicks As Integer = My.Computer.Clock.TickCount
Do While IsTimeUp(startTicks, secondsToRun)
' Code to run for at least secondsToRun seconds goes here.
Loop
End Sub
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Clock
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.FileSystem Object
Provides properties and methods for working with drives, files, and directories.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem object.
To See
Read from a text file How to: Read From Text Files in Visual Basic
Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic
Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic
Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats in Visual Basic
Read from a binary file How to: Read From Binary Files in Visual Basic
Read from text files in the MyDocuments direct How to: Read From Existing Text Files in My Documents (Visual Basic)
ory
Read from a text file with a StreamReader How to: Read Text from Files with a StreamReader (Visual Basic)
Write to a text file How to: Write Text to Files in Visual Basic
Append to a text file How to: Append to Text Files in Visual Basic
Write to a binary file How to: Write to Binary Files in Visual Basic
Write to text files in the MyDocuments director How to: Write Text to Files in the My Documents Directory in Visual Basic
y
Write to a text file with a StreamWriter How to: Write Text to Files with a StreamWriter in Visual Basic
Copy files with a specific pattern How to: Copy Files with a Specific Pattern to a Directory in Visual Basic
Copy a file to the same directory How to: Create a Copy of a File in the Same Directory in Visual Basic
Copy a file to a different directory How to: Create a Copy of a File in a Different Directory in Visual Basic
Delete all the files in a directory How to: Delete All Files in a Directory in Visual Basic
Find files with a specific pattern How to: Find Files with a Specific Pattern in Visual Basic
Move a collection of files How to: Move a Collection of Files in Visual Basic
Copy a directory to another directory How to: Copy a Directory to Another Directory in Visual Basic
Find subdirectories with a specific pattern How to: Find Subdirectories with a Specific Pattern in Visual Basic
Get the collection of files in a directory How to: Get the Collection of Files in a Directory in Visual Basic
Determine how many files are in a directory How to: Determine How Many Files Are in a Directory in Visual Basic
Move the contents of a directory How to: Move the Contents of a Directory in Visual Basic
Read from the MyDocuments directory How to: Retrieve the Contents of the My Documents Directory in Visual Basic
Parse a file path How to: Parse File Paths in Visual Basic
Example
This example checks to determine whether the folder C:\backup\logs exists and checks its properties.
VB
Dim logInfo As System.IO.DirectoryInfo
If My.Computer.FileSystem.DirectoryExists("C:\backup\logs") Then
logInfo = My.Computer.FileSystem.GetDirectoryInfo _
("C:\backup\logs")
End If
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.FileSystem Object Members
My.Computer.FileSystem.SpecialDirectories Object
My.Computer Object
Microsoft.VisualBasic.FileIO.FileSystem
Visual Basic Language Reference
SpecialDirectories Returns the My.Computer.FileSystem.SpecialDirectories Object, which can be used to access special director
ies, such as Temp or MyDocuments.
Methods
Method Description
CombinePath Returns a properly formatted combined path as a String.
My.Computer.FileSystem.FindInFiles Method Returns a read-only collection of strings representing the names of files containi
ng the specified text.
GetDirectories Returns a String collection representing the path names of subdirectories within
a directory.
GetFiles Returns a read-only String collection representing the names of files within a dir
ectory.
GetParentPath Returns a String representing the absolute path of the parent of the provided pat
h.
My.Computer.FileSystem.CombinePath Method
Combines two paths and returns a properly formatted path.
' Usage
Dim value As String = My.Computer.FileSystem.CombinePath(baseDirectory ,relativePath)
' Declaration
Public Function CombinePath( _
ByVal baseDirectory As String, _
ByVal relativePath As String _
) As String
Parameters
baseDirectory
String. First path to be combined. Required.
relativePath
String. Second path to be combined. Required.
Return Value
String.
Exceptions
The following condition may create an exception:
Path is malformed (ArgumentException).
Remarks
This method trims excess slash-mark characters to create a properly formatted path.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.CombinePath method.
To See
Combine a directory path and file name How to: Parse File Paths in Visual Basic
Example
This example combines a directory path and file name to create a properly formatted path.
VB
Dim fullPath As String
fullPath = My.Computer.FileSystem.CombinePath _
("C:\Documents and Settings\All Users\Documents\My Pictures", "picture.jpg")
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetParentPath Method
CombinePath
Visual Basic Language Reference
My.Computer.FileSystem.CopyDirectory Method
Copies a directory to another directory.
' Usage
My.Computer.FileSystem.CopyDirectory(sourceDirectoryName ,destinationDirectoryName)
My.Computer.FileSystem.CopyDirectory(sourceDirectoryName ,destinationDirectoryName ,overwri
te)
My.Computer.FileSystem.CopyDirectory(sourceDirectoryName ,destinationDirectoryName ,showUI)
My.Computer.FileSystem.CopyDirectory(sourceDirectoryName ,destinationDirectoryName ,showUI
,onUserCancel)
' Declaration
Public Sub CopyDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String _
)
' -or-
Public Sub CopyDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub CopyDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String, _
ByVal showUI As UIOption _
)
' -or-
Public Sub CopyDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String, _
ByVal showUI As UIOption, _
ByVal onUserCancel As UICancelOption _
)
Parameters
sourceDirectoryName
String. The directory to be copied. Required.
destinationDirectoryName
String. The location to which the directory should be copied. Required.
overwrite
Boolean. Whether or not existing files should be overwritten. Default is False. Required.
showUI
UIOption. Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs. Required.
onUserCancel
UICancelOption. Specifies what should be done if the user clicks Cancel during the operation. Default is ThrowException.
Required.
Exceptions
The following conditions may cause an exception:
The new name specified for the directory contains a colon (:) or slash (\ or /) (ArgumentException).
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
destinationDirectoryName is Nothing or an empty string (ArgumentNullException)
The source directory does not exist (DirectoryNotFoundException).
The source directory is a root directory (IOException).
The combined path points to an existing file (IOException).
The source path and target path are the same (IOException).
ShowUI is set to UIOption.AllDialogs and the user cancels the operation, or one or more files in the directory cannot be
copied (OperationCanceledException).
The operation is cyclic (InvalidOperationException).
The path contains a colon (:) (NotSupportedException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
A destination file exists but cannot be accessed (UnauthorizedAccessException).
Remarks
This method copies the contents of the directory as well as the directory itself. If the target directory does not exist, it is created.
If a directory with the same name exists in the target location, the contents of the two directories are merged. You can specify a
new name for the directory during the operation.
When copying files within a directory, exceptions may be thrown that are caused by a specific file, such as a file existing during
a merge while overwrite is set to False. When such exceptions are thrown, they are consolidated into a single exception whose
Data property holds entries in the form of an IDictionary in which the file or directory path is the key and the specific exception
message is contained in the corresponding value. Use For…Each to enumerate through the entries.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.CopyDirectory method.
To See
Copy a directory How to: Copy a Directory to Another Directory in Visual Basic
Example
The following example copies the directory TestDirectory1 into TestDirectory2, overwriting existing files.
VB
My.Computer.FileSystem.CopyDirectory("C:\TestDirectory1", "C:\TestDirectory2", True)
Replace C:\TestDirectory1 and C:\TestDirectory2 with the path and name of the directory you wish to copy and the
location to which you wish to copy it.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration:
SafeSubWindows.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Get the Collection of Files in a Directory in Visual Basic
How to: Move a Directory in Visual Basic
How to: Move the Contents of a Directory in Visual Basic
How to: Parse File Paths in Visual Basic
How to: Determine the Absolute Path of a File in Visual Basic
How to: Determine if a Directory Exists in Visual Basic
Reference
My.Computer.FileSystem Object
UICancelOption Enumeration
Visual Basic Language Reference
My.Computer.FileSystem.CopyFile Method
Copies a file to a new location.
' Usage
My.Computer.FileSystem.CopyFile(sourceFileName ,destinationFileName)
My.Computer.FileSystem.CopyFile(sourceFileName ,destinationFileName ,overwrite)
My.Computer.FileSystem.CopyFile(sourceFileName ,destinationFileName ,showUI)
My.Computer.FileSystem.CopyFile(sourceFileName ,destinationFileName ,showUI ,onUserCancel)
' Declaration
Public Sub CopyFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String _
)
' -or-
Public Sub CopyFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub CopyFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String, _
ByVal showUI As UIOption _
)
' -or-
Public Sub CopyFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String, _
ByVal showUI As UIOption, _
ByVal onUserCancel As UICancelOption _
)
Parameters
sourceFileName
String. The file to be copied. Required.
destinationFileName
String. The location to which the file should be copied. Required.
overwrite
Boolean. Whether existing files should be overwritten. Default is False. Required.
showUI
UIOption. Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs. Required.
onUserCancel
UICancelOption. Specifies what should be done if the user clicks Cancel during the operation. Default is ThrowException.
Required.
Exceptions
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The system could not retrieve the absolute path (ArgumentException).
destinationFileName contains path information (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
destinationFileName is Nothing or an empty string (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
The combined path points to an existing directory (IOException).
The destination file exists and overwrite is set to False (IOException).
The user does not have sufficient permissions to access the file (IOException).
A file in the target directory with the same name is in use (IOException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
UICancelOption is set to ThrowException, and the user has canceled the operation (OperationCanceledException).
UICancelOption is set to ThrowException, and an unspecified I/O error occurs (OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user does not have required permission (UnauthorizedAccessException).
The user lacks necessary permissions to view the path (SecurityException).
Remarks
CopyFile does not preserve ACEs (Access Control Entries). The newly created file inherits default ACEs from the directory in
which it is created.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.CopyFile method.
To See
Copy a file to the same directory. How to: Create a Copy of a File in the Same Directory in Visual Basic
Copy a file to a different directory. How to: Create a Copy of a File in a Different Directory in Visual Basic
Example
This example copies the file Test.txt to the directory TestFiles2 without overwriting existing files.
VB
My.Computer.FileSystem.CopyFile _
("C:\UserFiles\TestFiles\test.txt", _
"C:\UserFiles\TestFiles2")
Replace the file paths with the paths you want to use in your code.
This example copies the file Test.txt to the directory TestFiles2 and renames it NewFile.txt.
VB
My.Computer.FileSystem.CopyFile _
("C:\UserFiles\TestFiles\test.txt", _
"C:\UserFiles\TestFiles2", "NewFile.txt", FileIO.UICancelOption.DoNothing)
Replace the file paths with the paths you want to use in your code.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
RegistryPermission Controls the ability to access registry variables. Associated enumeration: Unrestricted.
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration:
SafeSubWindows.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Copy Files with a Specific Pattern to a Directory in Visual Basic
How to: Create a Copy of a File in the Same Directory in Visual Basic
How to: Copy a Directory to Another Directory in Visual Basic
How to: Rename a File in Visual Basic
Reference
My.Computer.FileSystem Object
UICancelOption Enumeration
Visual Basic Language Reference
My.Computer.FileSystem.CreateDirectory Method
Creates a directory.
' Usage
My.Computer.FileSystem.CreateDirectory(directory)
' Declaration
Public Sub CreateDirectory( _
ByVal directory As String _
)
Parameters
directory
String. Name and location of the directory. Required.
Exceptions
The following conditions may cause an exception:
The directory name is malformed. For example, it contains illegal characters or is only white space
(ArgumentException Class).
The parent directory of the directory to be created is read-only (IOException Class).
The directory name is Nothing (ArgumentNullException Class).
The directory name is too long (PathTooLongException Class).
The directory name is only a colon (:). (NotSupportedException Class).
The user does not have permission to create the directory (UnauthorizedAccessException).
A partial-trust situation exists in which the user does not have sufficient permissions (SecurityException).
Remarks
If the directory already exists, no exception is thrown.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.CreateDirectory method.
To See
Create a directory How to: Create a Directory in Visual Basic
Example
This example creates the directory, NewDirectory, in C:\Documents and Settings\All Users\Documents.
VB
My.Computer.FileSystem.CreateDirectory _
("C:\Documents and Settings\All Users\Documents\NewDirectory")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine if a Directory Exists in Visual Basic
Reference
My.Computer.FileSystem Object
CreateDirectory
Visual Basic Language Reference
My.Computer.FileSystem.CurrentDirectory Property
Gets or sets the current directory.
' Usage
Dim value As String = My.Computer.FileSystem.CurrentDirectory
' Declaration
Public Property CurrentDirectory As String
Return Value
String.
Exceptions
The following conditions may cause an exception:
The path is not valid (DirectoryNotFoundException).
The user lacks necessary permissions (UnauthorizedAccessException).
Remarks
CurrentDirectory is a system-wide environment variable.
Example
This example returns the current directory and displays it in a message box.
VB
MsgBox(My.Computer.FileSystem.CurrentDirectory)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.DeleteDirectory Method
Deletes a directory.
' Usage
My.Computer.FileSystem.DeleteDirectory(directory ,onDirectoryNotEmpty)
My.Computer.FileSystem.DeleteDirectory(directory ,showUI ,recycle)
My.Computer.FileSystem.DeleteDirectory(directory ,showUI ,recycle ,onUserCancel)
' Declaration
Public Sub DeleteDirectory( _
ByVal directory As String, _
ByVal onDirectoryNotEmpty As DeleteDirectoryOption _
)
' -or-
Public Sub DeleteDirectory( _
ByVal directory As String, _
ByVal showUI As UIOption, _
ByVal recycle As RecycleOption _
)
' -or-
Public Sub DeleteDirectory( _
ByVal directory As String, _
ByVal showUI As UIOption, _
ByVal recycle As RecycleOption, _
ByVal onUserCancel As UICancelOption _
)
Parameters
directory
String. Directory to be deleted. Required.
onDirectoryNotEmpty
DeleteDirectoryOption Enumeration. Specifies what should be done when a directory that is to be deleted contains files or
directories. Default is DeleteDirectoryOption.DeleteAllContents.
showUI
UIOption Enumeration. Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs.
Required.
recycle
RecycleOption Enumeration. Specifies whether or not the deleted file should be sent to the Recycle Bin. Default is
RecycleOption.DeletePermanently.
onUserCancel
UICancelOption Enumeration. Specifies whether to throw an exception if the user clicks Cancel. Required.
Exceptions
The following conditions may cause an exception:
The path is a zero-length string, is malformed, contains only white space, or contains invalid characters (including
wildcard characters) (ArgumentException).
The path is a device path (starts with \\.\) (ArgumentException).
The path is Nothing (ArgumentNullException).
The directory does not exist or is a file (DirectoryNotFoundException).
The directory is not empty, and onDirectoryNotEmpty is set to ThrowIfDirectoryNonEmpty (IOException).
The user does not have permission to delete the directory or subdirectory (IOException).
A file in the directory or subdirectory is in use (IOException).
A file or directory name contains a colon (:) (NotSupportedException).
The user cancels the operation or the directory cannot be deleted (OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user does not have required permissions (SecurityException).
Remarks
The showUI, recycle, and onUserCancel parameters are not supported in applications that are not user interactive, such as
Windows Services.
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.DeleteDirectory method.
To See
Delete a directory How to: Delete a Directory in Visual Basic
Example
The example deletes the directory OldDirectory only if it is empty.
VB
My.Computer.FileSystem.DeleteDirectory _
("C:\OldDirectory", FileIO.DeleteDirectoryOption.ThrowIfDirectoryNonEmpty)
This example deletes the directory OldDirectory and all of its contents.
VB
My.Computer.FileSystem.DeleteDirectory _
("C:\OldDirectory", FileIO.DeleteDirectoryOption.DeleteAllContents)
This example deletes the directory OldDirectory and all of its contents, asking the user to confirm the deletion, but does not
send the contents to the Recycle Bin.
VB
My.Computer.FileSystem.DeleteDirectory _
("C:\OldDirectory", FileIO.UIOption.AllDialogs, FileIO.RecycleOption.DeletePermanently, Fil
eIO.UICancelOption.ThrowException)
This example deletes the directory OldDirectory and all of its contents, sending them to the Recycle Bin, but does not show
the progress of the operation.
VB
My.Computer.FileSystem.DeleteDirectory("C:\OldDirectory", _
FileIO.UIOption.AllDialogs, FileIO.RecycleOption.SendToRecycleBin, FileIO.UICancelOption.T
hrowException)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration:
SafeSubWindows.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Delete a File in Visual Basic
How to: Delete a Directory in Visual Basic
Reference
My.Computer.FileSystem Object
UICancelOption Enumeration
RecycleOption Enumeration
DeleteDirectoryOption Enumeration
UICancelOption Enumeration
UIOption Enumeration
Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory
UICancelOption
Visual Basic Language Reference
My.Computer.FileSystem.DeleteFile Method
Deletes a file.
' Usage
My.Computer.FileSystem.DeleteFile(file)
My.Computer.FileSystem.DeleteFile(file ,showUI ,recycle)
My.Computer.FileSystem.DeleteFile(file ,showUI ,recycle ,onUserCancel)
' Declaration
Public Sub DeleteFile( _
ByVal file As String _
)
' -or-
Public Sub DeleteFile( _
ByVal file As String, _
ByVal showUI As UIOption, _
ByVal recycle As RecycleOption _
)
' -or-
Public Sub DeleteFile( _
ByVal file As String, _
ByVal showUI As UIOption, _
ByVal recycle As RecycleOption, _
ByVal onUserCancel As UICancelOption _
)
Parameters
file
String. Name and path of the file to be deleted. Required.
showUI
UIOption. Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs. Required.
recycle
RecycleOption. Whether or not the deleted file should be sent to the Recycle Bin. Default is
RecycleOption.DeletePermanently. Required.
onUserCancel
UICancelOption. Specifies whether or not an exception is thrown when the user cancels the operation. Default is
UICancelOption.ThrowException. Required.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; it has a trailing slash where a file must be specified; or it is a device path (starts with \\.\)
(ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The file is in use (IOException).
The user lacks necessary permissions to view the path (SecurityException).
The file does not exist (FileNotFoundException).
The user does not have permission to delete the file or the file is read-only (UnauthorizedAccessException).
A partial-trust situation in which the user does not have sufficient permissions (SecurityException).
The user cancelled the operation and onUserCancel is set to Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException
(OperationCanceledException).
Remarks
The showUI, recycle, and onUserCancel parameters are not supported in applications that are not user interactive, such as
Windows Services.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.DeleteFile method.
To See
To delete a file How to: Delete a File in Visual Basic
To delete all files in a directory How to: Delete All Files in a Directory in Visual Basic
Example
This example deletes the file Test.txt.
VB
My.Computer.FileSystem.DeleteFile("C:\test.txt")
This example deletes the file Test.txt and allows the user to confirm that the file should be deleted.
VB
My.Computer.FileSystem.DeleteFile _
("C:\test.txt", FileIO.UIOption.AllDialogs, FileIO.RecycleOption.SendToRecycleBin, FileIO.U
ICancelOption.ThrowException)
This example deletes the file Test.txt and sends it to the Recycle Bin.
VB
My.Computer.FileSystem.DeleteFile _
("C:\test.txt", FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.SendToRecycleBin, Fi
leIO.UICancelOption.ThrowException)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration:
SafeSubWindows.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Delete a Directory in Visual Basic
Reference
My.Computer.FileSystem Object
UIOption Enumeration
RecycleOption Enumeration
UICancelOption Enumeration
My.Computer.FileSystem Object
Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile
Visual Basic Language Reference
My.Computer.FileSystem.DirectoryExists Method
Returns a Boolean indicating whether the specified directory exists.
' Usage
Dim value As Boolean = My.Computer.FileSystem.DirectoryExists(directory)
' Declaration
Public Function DirectoryExists( _
ByVal directory As String _
) As Boolean
Parameters
directory
String. Path of the directory. Required.
Return Value
True if the directory exists; otherwise False.
Exceptions
This method throws no exceptions.
Remarks
The call to DirectoryExists requires FileIOPermission.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.DirectoryExists method.
To See
Determine if a directory exists How to: Determine if a Directory Exists in Visual Basic
Example
This example determines whether the directory C:\backup\logs exists and checks its properties.
VB
If My.Computer.FileSystem.DirectoryExists("C:\backup\logs") Then
Dim logInfo As System.IO.DirectoryInfo
logInfo = My.Computer.FileSystem.GetDirectoryInfo _
("C:\backup\logs")
End If
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine if a File Exists in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
DirectoryExists
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.Drives Property
Returns a read-only collection of all available drive names.
' Usage
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of System.IO.DriveInfo) = My
.Computer.FileSystem.Drives
' Declaration
Public ReadOnly Property Drives As System.Collections.ObjectModel.ReadOnlyCollection(Of Sys
tem.IO.DriveInfo)
Return Value
System.Collections.ObjectModel.ReadOnlyCollection (of System.IO.DriveInfo)
Exceptions
This property throws no exceptions.
Remarks
This property returns all logical drives.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.Drives property.
To See
Determine a drive's volume label How to: Determine a Drive's Volume Label in Visual Basic
Determine a drive's format How to: Determine a Drive's Format in Visual Basic
Determine a drive's type How to: Determine a Drive's Type in Visual Basic
Determine a drive's total space How to: Determine a Drive's Total Space in Visual Basic
Determine a drive's free space How to: Determine a Drive's Physical Free Space in Visual Basic
Determine a drive's root directory How to: Determine a Drive's Root Directory in Visual Basic
Example
This example displays the available drive names in a message box.
VB
Dim getInfo As System.IO.DriveInfo()
getInfo = System.IO.DriveInfo.GetDrives
For Each info As System.IO.DriveInfo In getInfo
MsgBox(info.name)
Next
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
System.Collections.ObjectModel.ReadOnlyCollection
System.IO.DriveInfo
Microsoft.VisualBasic.FileIO.FileSystem.Drives
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.FileExists Method
Returns a Boolean indicating whether the specified file exists.
' Usage
Dim value As Boolean = My.Computer.FileSystem.FileExists(file)
' Declaration
Public Function FileExists( _
ByVal file As String _
) As Boolean
Parameters
file
String. Name and path of the file. Required.
Return Value
Returns True if the file exists; otherwise this method returns False.
Exceptions
The following condition may create an exception:
The name of the file ends with a backslash (\) (ArgumentException).
Remarks
If the application does not have sufficient permissions to read the specified file, the FileExists method returns False, regardless
of the existence of the path; the method does not throw an exception.
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.FileExists method.
To See
Determine if a file exists How to: Determine if a File Exists in Visual Basic
Example
This example checks to see whether or not the file Check.txt exists and supplies the information in a message box.
VB
If My.Computer.FileSystem.FileExists("c://Check.txt") Then
MsgBox("File found.")
Else
MsgBox("File not found.")
End If
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine if a Directory Exists in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
FileExists
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.FindInFiles Method
Returns a read-only collection of strings representing the names of files containing the specified text.
' Usage
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Fil
eSystem.FindInFiles(directory ,containsText ,ignoreCase ,searchType)
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Fil
eSystem.FindInFiles(directory ,containsText ,ignoreCase ,searchType ,fileWildcards)
' Declaration
Public Function FindInFiles( _
ByVal directory As String, _
ByVal containsText As String, _
ByVal ignoreCase As Boolean, _
ByVal searchType As SearchOption _
) As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
' -or-
Public Function FindInFiles( _
ByVal directory As String, _
ByVal containsText As String, _
ByVal ignoreCase As Boolean, _
ByVal searchType As SearchOption, _
ByVal fileWildcards As String() _
) As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
Parameters
directory
String. The directory to be searched. Required.
containsText
String. The search text. Required.
ignoreCase
Boolean. Whether the search should be case-sensitive or not. Default is True. Required.
searchType
SearchOption Enumeration. Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly. Required.
fileWildcards
Array of type String. Pattern to be matched. Required.
Return Value
Read-only collection of type String.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
Remarks
An empty collection is returned if no files matching the specified pattern are found.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.FindInFiles method.
To See
Search a directory for files containing a specific string Walkthrough: Manipulating Files and Directories in Visual Basic
Example
This example searches the directory C:\TestDir for any files containing the string "sample string" and displays the results in
ListBox1.
VB
Dim list As System.Collections.ObjectModel.ReadOnlyCollection _
(Of String)
list = My.Computer.FileSystem.FindInFiles("C:\TestDir", _
"sample string", True, FileIO.SearchOption.SearchTopLevelOnly)
For Each name As String In list
ListBox1.Items.Add(name)
Next
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
SearchOption Enumeration
System.Collections.ObjectModel.ReadOnlyCollection
Microsoft.VisualBasic.FileIO.FileSystem.FindInFiles
Visual Basic Language Reference
My.Computer.FileSystem.GetDirectories Method
Returns a collection of strings representing the path names of subdirectories within a directory.
' Usage
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Fil
eSystem.GetDirectories(directory)
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Fil
eSystem.GetDirectories(directory ,searchType ,wildcards)
' Declaration
Public Function GetDirectories( _
ByVal directory As String _
) As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
' -or-
Public Function GetDirectories( _
ByVal directory As String, _
ByVal searchType As SearchOption, _
ByVal wildcards As String() _
) As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
Parameters
directory
String. Name and path of directory. Required.
searchType
SearchOption Enumeration. Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly. Required.
wildcards
String. Pattern to match names. Required.
Return Value
Read-only collection of String.
Exceptions
The following conditions may produce an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
One or more of the specified wildcard characters is Nothing, an empty string, or contains only spaces
(ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
Remarks
You can use the wildcards parameter to specify a specific pattern. If you would like to include the contents of subdirectories in
the search, set the searchType parameter to SearchAllSubDirectories.
An empty collection is returned if no directories matching the specified pattern are found.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.GetDirectories method.
To See
List subdirectories with a specific pattern How to: Find Subdirectories with a Specific Pattern in Visual Basic
Example
The following example returns all the directories in the directory structure that contain the word Logs in their names and adds
them to ListBox1.
VB
For Each foundDirectory As String In _
My.Computer.FileSystem.GetDirectories _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
True, "*Logs*")
ListBox1.Items.Add(foundDirectory)
Next
This example requires that you have a ListBox named ListBox1 on your form.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
SearchOption Enumeration
System.Collections.ObjectModel.ReadOnlyCollection
Microsoft.VisualBasic.FileIO.FileSystem.GetDirectories
Visual Basic Language Reference
My.Computer.FileSystem.GetDirectoryInfo Method
Returns a DirectoryInfo object for the specified path.
' Usage
Dim value As System.IO.DirectoryInfo = My.Computer.FileSystem.GetDirectoryInfo(directory)
' Declaration
Public Function GetDirectoryInfo( _
ByVal directory As String _
) As System.IO.DirectoryInfo
Parameters
directory
String. Path of directory. Required.
Return Value
DirectoryInfo
Exceptions
The following conditions may cause an exception:
The directory path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it
contains invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The directory path is not valid because it is Nothing (ArgumentNullException).
The directory path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the directory path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the directory path (SecurityException).
Remarks
If the directory does not exist, an exception is not thrown until the first time a property on the DirectoryInfo object is accessed.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.GetDirectoryInfo method.
To See
Determine when a directory was created How to: Determine a Directory's Creation Time in Visual Basic
Determine whether a directory is read-only How to: Determine if a Directory is Read-Only in Visual Basic
Example
This example gets a DirectoryInfo object for the directory C:\Documents and Settings and displays the directory's creation
time, last access time, and last write time.
VB
Dim getInfo As System.IO.DirectoryInfo
getInfo = My.Computer.FileSystem.GetDirectoryInfo _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
MsgBox("The directory was created at " & getInfo.CreationTime)
MsgBox("The directory was last accessed at " & getInfo.LastAccessTime)
MsgBox("The directory was last written to at " & getInfo.LastWriteTime)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
System.IO.DirectoryInfo
GetDirectoryInfo
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.GetDriveInfo Method
Returns a DriveInfo object for the specified drive.
' Usage
Dim value As System.IO.DriveInfo = My.Computer.FileSystem.GetDriveInfo(drive)
' Declaration
Public Function GetDriveInfo( _
ByVal drive As String _
) As System.IO.DriveInfo
Parameters
drive
String. Drive to be examined. Required.
Return Value
DriveInfo
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
Remarks
The DriveInfo class models a drive and provides methods and properties to query for drive information. Use DriveInfo to
determine what drives are available, and what type of drives they are. You can also query the property to determine the
capacity and available free space on the drive.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.GetDriveInfo method.
To See
Determine a drive's volume label How to: Determine a Drive's Volume Label in Visual Basic
Determine a drive's type How to: Determine a Drive's Type in Visual Basic
Determine a drive's total space How to: Determine a Drive's Total Space in Visual Basic
Determine a drive's physical free space How to: Determine a Drive's Physical Free Space in Visual Basic
Determine a drive's root folder How to: Determine a Drive's Root Directory in Visual Basic
Example
This example obtains a DriveInfo object for the C drive and uses it to display information about the drive.
VB
Dim getInfo As System.IO.DriveInfo
getInfo = My.Computer.FileSystem.GetDriveInfo("C:\")
MsgBox("The drive's type is " & getInfo.DriveType)
MsgBox("The drive has " & getInfo.TotalFreeSpace & " bytes free.")
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
System.IO.DriveInfo
GetDriveInfo
DriveType
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.GetFileInfo Method
Returns a FileInfo object for the specified file.
' Usage
Dim value As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(file)
' Declaration
Public Function GetFileInfo( _
ByVal file As String _
) As System.IO.FileInfo
Parameters
file
String. Name and path of the file. Required.
Return Value
FileInfo
Exceptions
The following conditions may cause an exception:
The path name is malformed. For example, it contains invalid characters or is only white space (ArgumentException).
The file name has a trailing slash mark (ArgumentException).
The file does not exist or is Nothing (ArgumentNullException).
The path contains a colon in the middle of the string (NotSupportedException).
The path is too long (PathTooLongException).
The user lacks necessary permissions (SecurityException).
The user lacks ACL (access control list) access to the file (UnauthorizedAccessException).
Remarks
An exception is not thrown if the file does not exist; rather, it will be thrown the first time the object's properties are accessed.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.GetFileInfo method.
To See
To get information about a file How to: Get Information About a File in Visual Basic
Determine a file's name and path How to: Parse File Paths in Visual Basic
Example
This example retrieves a System.IO.FileInfo object for the file MyLogFile.log and uses it to report the file's full name, last
access time, and length.
VB
Dim information As System.IO.FileInfo
information = My.Computer.FileSystem.GetFileInfo("C:\MyLogFile.log")
MsgBox("The file's full name is " & information.FullName & ".")
MsgBox("Last access time is " & information.LastAccessTime & ".")
MsgBox("The length is " & information.Length & ".")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
System.IO.FileInfo
Microsoft.VisualBasic.FileIO.FileSystem.GetFileInfo(System.String)
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.GetFiles Method
Returns a read-only collection of strings representing the names of files within a directory.
' Usage
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Fil
eSystem.GetFiles(directory)
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Fil
eSystem.GetFiles(directory ,searchType ,wildcards)
' Declaration
Public Function GetFiles( _
ByVal directory As String _
) As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
' -or-
Public Function GetFiles( _
ByVal directory As String, _
ByVal searchType As SearchOption, _
ByVal wildcards As String() _
) As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
Parameters
directory
String. Directory to be searched. Required.
searchType
SearchOption Enumeration. Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly. Required.
wildcards
String. Pattern to be matched. Required.
Return Value
Read-only collection of strings.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
Remarks
An empty collection is returned if no files matching the specified pattern are found.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.GetFiles method.
To See
Get the collection of files in a directory How to: Get the Collection of Files in a Directory in Visual Basic
Find files with a specific pattern in a directory How to: Find Files with a Specific Pattern in Visual Basic
Example
The following example returns all files in the directory and adds them to ListBox1.
VB
For Each foundFile As String In My.Computer.FileSystem.GetFiles _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
ListBox1.Items.Add(foundFile)
Next
This example requires that you have a ListBox named ListBox1 on your form.
This example returns all files in the directory with the extension .dll and adds them to ListBox1.
VB
For Each foundFile As String In My.Computer.FileSystem.GetFiles _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments, True, "*.dll")
ListBox1.Items.Add(foundFile)
Next
This example requires that you have a ListBox named ListBox1 on your form.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Find Files with a Specific Pattern in Visual Basic
How to: Get the Collection of Files in a Directory in Visual Basic
Reference
My.Computer.FileSystem Object
SearchOption Enumeration
System.Collections.ObjectModel.ReadOnlyCollection
Microsoft.VisualBasic.FileIO.FileSystem.GetFiles
Visual Basic Language Reference
My.Computer.FileSystem.GetName Method
Parses the file name out of the path provided.
' Usage
Dim value As String = My.Computer.FileSystem.GetFileName(path)
' Declaration
Public Function GetFileName( _
ByVal path As String _
) As String
Parameters
path
Required. Path to be parsed. String.
Return Value
String.
Exceptions
This method throws no exceptions.
Remarks
This is a string operation; the FileSystem is not examined.
The GetName method ignores a slash mark occurring at the end of the path.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.GetFileName method.
To See
Parse a file path How to: Parse File Paths in Visual Basic
Example
The following example parses a file path and returns the name of the file.
VB
MsgBox("The filename is: " & _
My.Computer.FileSystem.GetName("C:\testdirectory\testfile"))
Replace the path C:\Testdirectory\Testfile with the path you wish to parse.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.FileSystem.GetParentPath Method
Returns the parent path of the provided path.
' Usage
Dim value As String = My.Computer.FileSystem.GetParentPath(path)
' Declaration
Public Function GetParentPath( _
ByVal path As String _
) As String
Parameters
path
String. Path to be examined. Required.
Return Value
String.
Exceptions
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
Path does not have a parent path because it is a root path (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
Remarks
This is a string operation; the file system is not examined.
Example
This example gets the parent path for C:\Backups\Tmp\Test.
VB
Dim strPath As String
strPath = My.Computer.FileSystem.GetParentPath("C:\backups\tmp\test")
MsgBox(strPath)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Parse File Paths in Visual Basic
Reference
My.Computer.FileSystem Object
GetParentPath
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.GetTempFileName Method
Creates a uniquely named zero-byte temporary file on disk and returns the full path of that file.
' Usage
Dim value As String = My.Computer.FileSystem.GetTempFileName()
' Declaration
Public Function GetTempFileName() As String
Return Value
String containing the full path of the temporary file.
Remarks
This method can be used to create a temporary file.
Example
This example creates a temp file and returns its path.
VB
MsgBox("The file is located at " & _
My.Computer.FileSystem.GetTempFileName)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
Microsoft.VisualBasic.FileIO.FileSystem.GetTempFileName
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.MoveDirectory Method
Moves a directory from one location to another.
' Usage
My.Computer.FileSystem.MoveDirectory(sourceDirectoryName ,destinationDirectoryName)
My.Computer.FileSystem.MoveDirectory(sourceDirectoryName ,destinationDirectoryName ,overwri
te)
My.Computer.FileSystem.MoveDirectory(sourceDirectoryName ,destinationDirectoryName ,showUI)
My.Computer.FileSystem.MoveDirectory(sourceDirectoryName ,destinationDirectoryName ,showUI
,onUserCancel)
' Declaration
Public Sub MoveDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String _
)
' -or-
Public Sub MoveDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub MoveDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String, _
ByVal showUI As UIOption _
)
' -or-
Public Sub MoveDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String, _
ByVal showUI As UIOption, _
ByVal onUserCancel As UICancelOption _
)
Parameters
sourceDirectoryName
String. Path of the directory to be moved. Required.
destinationDirectoryName
String. Path of the directory to which the source directory is being moved. Required.
overwrite
Boolean. Specifies whether existing directories should be overwritten. Default is False. Required.
showUI
UIOption. Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs. Required.
onUserCancel
UICancelOption Enumeration. Specifies whether or not an exception is thrown when the user cancels the operation. Default is
UICancelOption.ThrowException. Required.
Exceptions
The following conditions may cause an exception:
The path is a zero-length string, contains only white space, contains invalid characters, or is a device path (starts with \\.\)
(ArgumentException).
The path is Nothing (ArgumentNullException).
The source is invalid (DirectoryNotFoundException).
The source is a root directory (IOException).
The combined path points to an existing file (IOException).
The source path and the target path are the same (IOException).
The file already exists and overwrite is set to False (IOException).
onUserCancel is set to ThrowException and a subdirectory of the file cannot be copied (IOException).
The operation is cyclic (InvalidOperationException).
A file or directory name in the path contains a colon (:) (NotSupportedException).
UICancelOption is set to ThrowException, and the user cancels the operation, or the operation cannot be
completed(OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
UICancelOption is set to ThrowException, and the user lacks necessary permissions (SecurityException).
The user does not have permission to modify the file (UnauthorizedAccessException).
Remarks
If an attempt is made to move a directory inside a directory that does not exist, the target structure will be created.
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.MoveDirectory method.
To See
Move a directory How to: Move a Directory in Visual Basic
Example
This example moves Directory1 inside Directory2.
VB
My.Computer.FileSystem.MoveDirectory("C:\Directory1", "C:\Directory2")
This example moves Directory1 inside Directory2, overwriting the directory if it already exists.
VB
My.Computer.FileSystem.MoveDirectory("C:\Directory1", "C:\Directory2", _
True)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration:
SafeSubWindows.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
UIOption Enumeration
UICancelOption Enumeration
My.Computer.FileSystem.MoveFile Method
My.Computer.FileSystem.CopyDirectory Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.MoveFile Method
Moves a file to a new location.
' Usage
My.Computer.FileSystem.MoveFile(sourceFileName ,destinationFileName)
My.Computer.FileSystem.MoveFile(sourceFileName ,destinationFileName ,overwrite)
My.Computer.FileSystem.MoveFile(sourceFileName ,destinationFileName ,showUI)
My.Computer.FileSystem.MoveFile(sourceFileName ,destinationFileName ,showUI ,onUserCancel)
' Declaration
Public Sub MoveFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String _
)
' -or-
Public Sub MoveFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub MoveFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String, _
ByVal showUI As UIOption _
)
' -or-
Public Sub MoveFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String, _
ByVal showUI As UIOption, _
ByVal onUserCancel As UICancelOption _
)
Parameters
sourceFileName
String. Path of the file to be moved. Required.
destinationFileName
String. Path of the directory into which the file should be moved. Required.
overwrite
Boolean. Specifies whether to overwrite existing files. Default is False. Required.
showUI
UIOption Enumeration. Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs.
Required.
onUserCancel
UICancelOption Enumeration. Specifies whether or not an exception is thrown when the user cancels the operation. Default is
UICancelOption.ThrowException. Required.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The file name ends with a backslash (\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
destinationFileName is Nothing or an empty string (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
The combined path points to an existing directory, the destination file exists and overwrite is set to False, a file in the
target directory with the same name is in use, or the user does not have sufficient permissions to access the file
(IOException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
onUserCancel is set to ThrowException, and either the user has cancelled the operation or an unspecified I/O error
occurs (OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have required permission (UnauthorizedAccessException).
Remarks
If the target structure does not exist, it is created.
The MoveFile method preserves ACEs (Access Control Entries) only when moving the file within the same volume. This
includes inherited ACEs, which become direct ACEs when moved (direct ACEs take precedence over inherited ACEs). If a file is
moved between volumes, ACEs will not be copied.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.MoveFile method.
To See
Move a file How to: Move a File in Visual Basic
Move a collection of files How to: Move a Collection of Files in Visual Basic
Move the contents of a directory How to: Move the Contents of a Directory in Visual Basic
Example
This example moves the file Test.txt from TestDir1 to TestDir2.
VB
My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt", "C:\TestDir2\test.txt")
This example moves the file Test.txt from TestDir1 to TestDir2 and renames it Test2.txt.
VB
My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt", "C:\TestDir2\test2.txt")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
RegistryPermission Controls the ability to access registry variables. Associated enumeration: Unrestricted.
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration:
SafeSubWindows.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
UIOption Enumeration
UICancelOption Enumeration
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.OpenTextFieldParser Method
The OpenTextFieldParser method allows you to create a TextFieldParser Object, which provides a way to easily and efficiently
parse structured text files, such as logs. The TextFieldParser object can be used to read both delimited and fixed-width files.
' Usage
Dim value As TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(file)
Dim value As TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(file ,delimiters)
Dim value As TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(file ,fieldWidths
)
' Declaration
Public Function OpenTextFieldParser( _
ByVal file As String _
) As TextFieldParser
' -or-
Public Function OpenTextFieldParser( _
ByVal file As String, _
ByVal delimiters As String() _
) As TextFieldParser
' -or-
Public Function OpenTextFieldParser( _
ByVal file As String, _
ByVal fieldWidths As Integer() _
) As TextFieldParser
Parameters
file
String. The file to be opened with the TextFieldParser. Required.
delimiters
String(). Delimiters for the fields. Required.
fieldWidths
Integer(). Widths of the fields. Required.
Return Value
TextFieldParser
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The file name ends with a trailing slash (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
Specified file does not exist (FileNotFoundException).
Specified file is in use (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line
causing the exception, while the TextFieldParser.ErrorLine Property is assigned the text contained in the line.
The user does not have sufficient permissions to access the file (UnauthorizedAccessException).
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.OpenTextFieldParser method.
To See
Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic
Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic
Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats in Visual Basic
Example
This example opens the TextFieldParser reader and uses it to read from C:\TestFolder1\Test1.txt.
VB
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
reader = My.Computer.FileSystem.OpenTextFieldParser _
("C:\TestFolder1\test1.txt")
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.delimiters = New String() {","}
Dim currentRow As String()
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlEvidence.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Read From Text Files in Visual Basic
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
My.Computer.FileSystem Object
TextFieldParser Object
OpenTextFieldParser
Concepts
Parsing Text Files with the TextFieldParser Object
Other Resources
Reading from Files in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.OpenTextFileReader Method
Opens a StreamReader.
' Usage
Dim value As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(file)
Dim value As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(file ,encod
ing)
' Declaration
Public Function OpenTextFileReader( _
ByVal file As String _
) As System.IO.StreamReader
' -or-
Public Function OpenTextFileReader( _
ByVal file As String, _
ByVal encoding As System.Text.Encoding _
) As System.IO.StreamReader
Parameters
file
String. File to be read. Required.
encoding
Encoding. Default is UTF8. Required.
Return Value
StreamReader
Exceptions
The following conditions may create an exception:
The file name ends with a backslash (\) (ArgumentException).
The specified file cannot be found (FileNotFoundException).
The user lacks necessary permissions to read from the file (SecurityException).
Remarks
Only text files can be read with a StreamReader.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.OpenTextFileReader method.
To See
Open a file with a StreamReader How to: Read Text from Files with a StreamReader (Visual Basic)
Example
This example opens the file Testfile.txt, reads a line from it, and displays the line in a MessageBox.
VB
Dim fileReader As System.IO.StreamReader
fileReader = _
My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Read Text from Files with a StreamReader (Visual Basic)
Reference
My.Computer.FileSystem Object
System.Text.Encoding
System.IO.StreamReader
Microsoft.VisualBasic.FileIO.FileSystem.OpenTextFileReader
Other Resources
Reading from Files in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.OpenTextFileWriter Method
Opens a StreamWriter.
' Usage
Dim value As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(file ,appen
d)
Dim value As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(file ,appen
d ,encoding)
' Declaration
Public Function OpenTextFileWriter( _
ByVal file As String, _
ByVal append As Boolean _
) As System.IO.StreamWriter
' -or-
Public Function OpenTextFileWriter( _
ByVal file As String, _
ByVal append As Boolean, _
ByVal encoding As System.Text.Encoding _
) As System.IO.StreamWriter
Parameters
file
String. File to be written to. Required.
append
Boolean. Specifies whether to append to or overwrite information in the file. Default is False. Required.
encoding
Encoding. Encoding to be used in writing to the file. Default is UTF8. Required.
Return Value
StreamWriter
Exceptions
The following condition may cause an exception to be thrown:
The file name ends with a trailing slash (ArgumentException).
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.OpenTextFileWriter method.
To See
Write text to a file with a StreamWriter How to: Write Text to Files with a StreamWriter in Visual Basic
Example
This example opens a StreamWriter with the My.Computer.FileSystem.OpenTextFileWriter method and uses it to write a
string to a text file with the WriteLine method of the StreamWriter class.
VB
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Write Text to Files with a StreamWriter in Visual Basic
Reference
My.Computer.FileSystem Object
System.Text.Encoding
System.IO.StreamWriter
Microsoft.VisualBasic.FileIO.FileSystem.OpenTextFileWriter
Visual Basic Language Reference
My.Computer.FileSystem.ReadAllBytes Method
Returns the contents of a file as a byte array.
' Usage
Dim value As Byte() = My.Computer.FileSystem.ReadAllBytes(file)
' Declaration
Public Function ReadAllBytes( _
ByVal file As String _
) As Byte()
Parameters
file
String. File to be read. Required.
Return Value
Byte array containing the contents of the file.
Exceptions
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The file name ends with a trailing slash (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The file does not exist (FileNotFoundException).
The file is in use by another process or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
There is not enough memory to write the string to buffer (OutOfMemoryException).
The user lacks necessary permissions to view the path (SecurityException).
Remarks
The ReadAllBytes method of the My.Computer.FileSystem object allows you to read from a binary file. The contents of the
file are returned as a byte array.
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a
Visual Basic source file. Verify all inputs before using the data in your application.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.ReadAllBytes method.
To See
Read from a binary file How to: Read From Binary Files in Visual Basic
Example
This example reads from the file C:/Documents and Settings/selfportrait.jpg.
VB
My.Computer.FileSystem.ReadAllBytes _
("C:/Documents and Settings/selfportrait.jpg")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
ReadAllBytes
Other Resources
Reading from Files in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.ReadAllText Method
Returns the contents of a text file as a String.
' Usage
Dim value As String = My.Computer.FileSystem.ReadAllText(file)
Dim value As String = My.Computer.FileSystem.ReadAllText(file ,encoding)
' Declaration
Public Function ReadAllText( _
ByVal file As String _
) As String
' -or-
Public Function ReadAllText( _
ByVal file As String, _
ByVal encoding As System.Text.Encoding _
) As String
Parameters
file
String. Name and path of the file to read. Required.
encoding
System.Text.Encoding. Character encoding to use in reading the file. Required. Default is UTF-8.
Return Value
String containing the contents of the file.
Exceptions
The contents of the file may not be what is expected, and methods to read from the file may fail.
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The file name ends with a trailing slash (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The file does not exist (FileNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
There is not enough memory to write the string to buffer (OutOfMemoryException).
The user lacks necessary permissions to view the path (SecurityException).
Remarks
The ReadAllText method of the My.Computer.FileSystem object allows you to read from a text file. The contents of the file
are returned as a string.
The file encoding can be specified if the contents of the file are in an encoding such as ASCII or UTF-8. If you are reading from a
file with extended characters, you need to specify the file encoding.
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a
Visual Basic source file. Verify all inputs before using the data in your application.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.ReadAllText method.
To See
Read from a text file How to: Read From Text Files in Visual Basic
Example
This example reads the contents of Test.txt into a string and then displays it in a message box.
VB
Dim reader As String
reader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
MsgBox(reader)
This example reads the contents of the ASCII file Test.txt into a string and then displays it in a message box.
VB
Dim reader As String
reader = My.Computer.FileSystem.ReadAllText("C:\test.txt", _
System.Text.Encoding.ASCII)
MsgBox(reader)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Read Text from Files with a StreamReader (Visual Basic)
Troubleshooting: Reading from and Writing to Text Files
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
System.Text.Encoding
Microsoft.VisualBasic.FileIO.FileSystem.ReadAllText
StreamReader
Concepts
File Encodings
Other Resources
Reading from Files in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.RenameDirectory Method
Renames a directory.
' Usage
My.Computer.FileSystem.RenameDirectory(directory ,newName)
' Declaration
Public Sub RenameDirectory( _
ByVal directory As String, _
ByVal newName As String _
)
Parameters
directory
String. Path and name of directory to be renamed. Required.
newName
String. New name for directory. Required.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The newName parameter contains path information (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The newName parameter is Nothing or an empty string (ArgumentNullException).
The source directory is not valid or does not exist (DirectoryNotFoundException).
There is an existing file or directory with the name specified in newName (IOException).
The directory is a root directory (IOException).
The path exceeds 248 characters (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have required permission (UnauthorizedAccessException).
Remarks
This method cannot be used to move a directory; use the MoveDirectory method to move and rename the directory.
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.RenameDirectory method.
To See
Rename a directory How to: Rename a Directory in Visual Basic
Example
This example renames the Test directory to SecondTest.
VB
My.Computer.FileSystem.RenameDirectory("C:MyDocuments\Test", "SecondTest")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Parse File Paths in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.MoveDirectory Method
RenameDirectory
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.RenameFile Method
Renames a file.
' Usage
My.Computer.FileSystem.RenameFile(file ,newName)
' Declaration
Public Sub RenameFile( _
ByVal file As String, _
ByVal newName As String _
)
Parameters
file
String. File to be renamed. Required.
newName
String. New name of file. Required.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The newName parameter contains path information or ends with a backslash (\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The newName parameter is Nothing or an empty string (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
There is an existing file or directory with the name specified in newName (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have the required permission (UnauthorizedAccessException).
Remarks
This method cannot be used to move a file; use the My.Computer.FileSystem.MoveFile Method to move and rename the file.
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.RenameFile method.
To See
Rename a file How to: Rename a File in Visual Basic
Example
This example renames the file Test.txt to SecondTest.txt.
VB
My.Computer.FileSystem.RenameFile("C:\Test.txt", "SecondTest.txt")
Change "C:\Test.txt" to the path and file name of the file that you want to rename.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(System.String,System.String)
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.SpecialDirectories Property
Gets an object that provides properties for accessing commonly referenced directories.
' Usage
Dim value As Microsoft.VisualBasic.MyServices.SpecialDirectoriesProxy = My.Computer.FileSys
tem.SpecialDirectories
' Declaration
Public ReadOnly Property SpecialDirectories As MyServices.SpecialDirectoriesProxy
Return Value
This property returns the My.Computer.FileSystem.SpecialDirectories Object for the computer.
Remarks
This property provides easy access to the My.Computer.FileSystem.SpecialDirectories Object.
Example
This example returns the file path for the user's Desktop directory and displays it.
VB
Dim filePath As String
filePath = My.Computer.FileSystem.SpecialDirectories.Desktop
MsgBox(filePath)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.FileSystem.WriteAllBytes Method
Writes data to a binary file.
' Usage
My.Computer.FileSystem.WriteAllBytes(file ,data ,append)
' Declaration
Public Sub WriteAllBytes( _
ByVal file As String, _
ByVal data As Byte(), _
ByVal append As Boolean _
)
Parameters
file
String. Path and name of the file to be written to. Required.
data
Byte. Data to be written to the file. Required.
append
Boolean. Whether to append or overwrite data. Default is False. Required.
Exceptions
The following conditions may create an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing or ends with a backslash (\) (ArgumentNullException).
The file parameter points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).
The file is in use by another process or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
Remarks
If the append parameter is True, it appends the data to the file; otherwise data in the file is overwritten.
If the specified path, excluding the file name, is not valid, a DirectoryNotFoundException exception will be thrown. If the
path is valid but the file does not exist, the file is created.
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.WriteAllBytes method.
To See
Write to a binary file How to: Write to Binary Files in Visual Basic
Example
This example appends the data array CustomerData to the file CollectedData.
VB
My.Computer.FileSystem.WriteAllBytes _
("C:\MyDocuments\CustomerData", CustomerData, True)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Write to Binary Files in Visual Basic
Reference
My.Computer.FileSystem Object
WriteAllBytes
Other Resources
Writing to Files in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.WriteAllText Method
Writes text to a file.
' Usage
My.Computer.FileSystem.WriteAllText(file ,text ,append)
My.Computer.FileSystem.WriteAllText(file ,text ,append ,encoding)
' Declaration
Public Sub WriteAllText( _
ByVal file As String, _
ByVal text As String, _
ByVal append As Boolean _
)
' -or-
Public Sub WriteAllText( _
ByVal file As String, _
ByVal text As String, _
ByVal append As Boolean, _
ByVal encoding As System.Text.Encoding _
)
Parameters
file
String. File to be written to. Required.
text
String. Text to be written to file. Required.
append
Boolean. Whether to append text or overwrite existing text. Default is False. Required.
encoding
Encoding. What encoding to use when writing to file. Required. Default is UTF-8.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters, ends with a trailing slash, or is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
file points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
If you are running in a partial-trust context, the code might throw an exception due to insufficient privileges. For more
information, see Code Access Security Basics.
Remarks
When no encoding is specified, UTF-8 is used. The byte order mark (BOM) for the encoding is written to the file unless you
specify System.Text.Encoding.Default, which uses the system's current ANSI code page.
If the specified file does not exist, it is created.
If append is set to False, existing text in the file is overwritten.
If the specified encoding does not match the existing encoding of the file, the specified coding is ignored.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.WriteAllText method.
To See
Write text to a file How to: Write Text to Files in Visual Basic
Append text to a file How to: Append to Text Files in Visual Basic
Example
This example writes the line "This is new text to be added." to the file Test.txt, overwriting any existing text in the file.
VB
My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", _
"This is new text to be added.", False)
This example writes the names of the files in the Documents and Settings folder to FileList.txt, inserting a carriage return
between each for better readability.
VB
For Each foundFile As String In _
My.Computer.FileSystem.GetFiles("C:\Documents and Settings")
foundFile = foundFile & vbCrLf
My.Computer.FileSystem.WriteAllText _
("C:\Documents and Settings\FileList.txt", foundFile, True)
Next
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
System.Text.Encoding
Microsoft.VisualBasic.FileIO.FileSystem.WriteAllText
Other Resources
Writing to Files in Visual Basic
Visual Basic Language Reference
My.Computer.FileSystem.SpecialDirectories Object
Provides properties for accessing commonly referenced directories.
Remarks
If the path for the referenced directory is empty, usually due to the operating system not supporting the directory, a
DirectoryNotFoundException exception is thrown.
No backslash (\) appears at the end of the path.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.SpecialDirectories object.
To See
Read from the MyDocuments directory How to: Retrieve the Contents of the My Documents Directory in Visual Basic
Example
This example returns the filePath for the user's Desktop directory and displays it.
VB
Dim filePath As String
filePath = My.Computer.FileSystem.SpecialDirectories.Desktop
MsgBox(filePath)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object Members
My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData Property
My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData Property
My.Computer.FileSystem.SpecialDirectories.Desktop Property
My.Computer.FileSystem.SpecialDirectories.MyDocuments Property
My.Computer.FileSystem.SpecialDirectories.MyMusic Property
My.Computer.FileSystem.SpecialDirectories.MyPictures Property
My.Computer.FileSystem.SpecialDirectories.Programs Property
My.Computer.FileSystem.SpecialDirectories.Temp Property
My.Computer.FileSystem Object
Microsoft.VisualBasic.FileIO.SpecialDirectories
Visual Basic Language Reference
CurrentUserApplicationData Read-only String representing the pathname pointing to the current user's Application Data direc
tory.
Desktop Read-only String representing the pathname pointing to the user's Desktop directory.
MyDocuments Read-only String representing the pathname pointing to the user's MyDocuments directory.
MyMusic Read-only String representing the pathname pointing to the user's MyMusic directory.
MyPictures Read-only String representing the pathname pointing to the user's MyPictures directory.
Programs Read-only String representing the pathname pointing to the user's Programs directory.
Temp Read-only String representing the pathname pointing to the user's Temp directory.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Visual Basic Language Reference
My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
Property
Gets a path for storing application data that is shared among all users on the computer.
' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
' Declaration
Public ReadOnly Property AllUsersApplicationData As String
Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories.
If the path does not exist, it is created with the following format: BasePath\CompanyName\ProductName\Version
A typical BasePath in Windows XP is C:\Documents and Settings\All Users\Application Data. The CompanyName, ProductName, and
Version can be obtained from the My.Application.Info.CompanyName, My.Application.Info.ProductName, and My.Application.Info.Version
properties.
Note
If the Company and Product names are not specified in the Assembly Information dialog box, the CompanyName\ProductName in
the path are replaced with the assembly name. For more information on setting assembly information names, see
How to: Specify Assembly Information.
Example
This example displays the path for shared application data in a MessageBox.
VB
MsgBox _
(My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.AllUsersApplicationData
Visual Basic Language Reference
My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData
Property
Gets a path for storing the current user's application data.
' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData
' Declaration
Public ReadOnly Property CurrentUserApplicationData As String
Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories.
If the path does not exist, it is created with the following format: BasePath\CompanyName\ProductName\Version
A typical BasePath in Windows XP is C:\Documents and Settings\username\Application Data. The CompanyName, ProductName, and Version
can be obtained from the My.Application.Info.CompanyName, My.Application.Info.ProductName, and My.Application.Info.Version properties.
Note
If the Company and Product names are not specified in the Assembly Information dialog box, the CompanyName\ProductName in the pat
h are replaced with the assembly name. For more information on setting assembly information names, see
How to: Specify Assembly Information.
Data stored in this path is part of a user profile that is enabled for roaming. A roaming user works on more than one computer in a network. The
user profile for a roaming user is kept on a server on the network and is loaded onto a system when the user logs on. For a user profile to be
eligible for roaming, the operating system must support roaming profiles and the feature must be enabled.
Example
This example displays the path for storing the current user's application data in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.CurrentUserApplicationData
Visual Basic Language Reference
My.Computer.FileSystem.SpecialDirectories.Desktop Property
Gets a path name pointing to the Desktop directory.
' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.Desktop
' Declaration
Public ReadOnly Property Desktop As String
Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories.
Example
This example displays the path for the Desktop directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.Desktop)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission is required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.Desktop
Visual Basic Language Reference
My.Computer.FileSystem.SpecialDirectories.MyDocuments
Property
Gets a path name pointing to the My Documents directory.
' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
' Declaration
Public ReadOnly Property MyDocuments As String
Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories.
Example
This example displays the path for the My Documents directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission is required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.MyDocuments
Visual Basic Language Reference
My.Computer.FileSystem.SpecialDirectories.MyMusic Property
Gets a path name pointing to the My Music directory.
' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.MyMusic
' Declaration
Public ReadOnly Property MyMusic As String
Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories.
Example
This example displays the path for the My Music directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.MyMusic)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission is required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.MyMusic
Visual Basic Language Reference
My.Computer.FileSystem.SpecialDirectories.MyPictures
Property
Gets a path name pointing to the My Pictures directory.
' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.MyPictures
' Declaration
Public ReadOnly Property MyPictures As String
Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object class contains paths to commonly referenced directories.
Example
This example displays the path for the My Pictures directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.MyPictures)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission is required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.MyPictures
Visual Basic Language Reference
My.Computer.FileSystem.SpecialDirectories.ProgramFiles
Property
Gets a path pointing to the Program Files directory.
' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.ProgramFiles
' Declaration
Public ReadOnly Property Programs As String
Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories. The Program Files
directory contains the computer's program files.
Example
This example displays the path for the Program Files directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.ProgramFiles)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.ProgramFiles
Visual Basic Language Reference
My.Computer.FileSystem.SpecialDirectories.Programs Property
Gets a path name pointing to the Programs directory.
' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.Programs
' Declaration
Public ReadOnly Property Programs As String
Return Value
String.
Exceptions
The following conditions may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories. The Programs
directory contains the user's program groups.
Example
This example displays the path for the Programs directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.Programs)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission is required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.Programs
Visual Basic Language Reference
My.Computer.FileSystem.SpecialDirectories.Temp Property
Gets a path name pointing to the system's current temporary directory.
' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.Temp
' Declaration
Public ReadOnly Property Temp As String
Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories.
Example
This example displays the path for the system's current temporary directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.Temp)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permissions are required:
Permission Description
EnvironmentPermission Controls access to system and user environment variables. Associated enumeration: Unrestricted.
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.Temp
Visual Basic Language Reference
My.Computer.Info Object
Provides properties for getting information about the computer's memory, loaded assemblies, name, and operating system.
Remarks
The properties exposed by the My.Computer.Info object return information about the computer from which the application is
deployed, as determined at run time. Typically, this data differs from what was available on the development computer.
Example
This example uses the My.Computer.Info.AvailablePhysicalMemory property to display the amount of available physical
memory for the computer on which the code runs.
VB
MsgBox("Computer's available physical memory: " & _
My.Computer.Info.AvailablePhysicalMemory)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.Info Object Members
Visual Basic Language Reference
AvailableVirtualMemory Gets the total amount of free virtual address space available for the computer.
InstalledUICulture Gets the current UI culture installed with the operating system.
OSPlatform Gets the platform identifier for the operating system of the computer.
TotalPhysicalMemory Gets the total amount of physical memory for the computer.
TotalVirtualMemory Gets the total amount of virtual address space available for the computer.
See Also
Reference
My.Computer.Info Object
Visual Basic Language Reference
My.Computer.Info.AvailablePhysicalMemory Property
Gets the total amount of free physical memory for the computer.
' Usage
Dim value As ULong = My.Computer.Info.AvailablePhysicalMemory
' Declaration
Public ReadOnly Property AvailablePhysicalMemory As ULong
Return Value
A ULong containing the number of bytes of free physical memory for the computer.
Exceptions
The following condition can cause an exception:
The application cannot obtain the memory status (Win32Exception).
Remarks
The My.Computer.Info.AvailablePhysicalMemory property requires Windows XP, Windows 2000 Professional, Windows
Server 2003, or Windows 2000 Server.
Example
This example uses the My.Computer.Info.AvailablePhysicalMemory property to display the amount of available physical
memory for the computer on which the code runs.
VB
MsgBox("Computer's available physical memory: " & _
My.Computer.Info.AvailablePhysicalMemory)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Info.AvailableVirtualMemory Property
Gets the total amount of the computer's free virtual address space.
' Usage
Dim value As ULong = My.Computer.Info.AvailableVirtualMemory
' Declaration
Public ReadOnly Property AvailableVirtualMemory As ULong
Return Value
A ULong containing the number of bytes of the computer's free virtual address space.
Exceptions
The following condition can cause an exception:
The application cannot obtain the memory status (Win32Exception).
Remarks
The My.Computer.Info.AvailableVirtualMemory property requires Windows XP, Windows 2000 Professional, Windows
Server 2003, or Windows 2000 Server.
Example
This example uses the My.Computer.Info.AvailableVirtualMemory property to display the amount of available virtual
memory for the computer on which the code runs.
VB
MsgBox("Computer's available virtual memory: " & _
My.Computer.Info.AvailableVirtualMemory)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Info.InstalledUICulture Property
Gets the current UI culture installed with the operating system.
' Usage
Dim value As System.Globalization.CultureInfo = My.Computer.Info.InstalledUICulture
' Declaration
Public ReadOnly Property InstalledUICulture As System.Globalization.CultureInfo
Return Value
A CultureInfo object represents the UI culture installed on the computer.
Remarks
The My.Computer.Info.InstalledUICulture property has the same behavior as the InstalledUICulture property.
In a localized operating system, such as Japanese Windows 2000 Professional, this property returns the culture of the
operating system.
Example
This example uses the My.Computer.Info.InstalledUICulture property to display the name of the operating system's UI
culture.
VB
MsgBox("Computer's UI culture name: " & _
My.Computer.Info.InstalledUICulture.DisplayName)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Info.OSFullName Property
Gets the full operating system name.
' Usage
Dim value As String = My.Computer.Info.OSFullName
' Declaration
Public ReadOnly Property OSFullName As String
Return Value
A String containing the operating-system name.
Exceptions
The following condition can cause an exception:
The calling code does not have full trust (SecurityException).
Remarks
This property returns detailed information about the operating system name if Windows Management Instrumentation (WMI)
is installed on the computer. Otherwise, this property returns the same string as the My.Computer.Info.OSPlatform
property, which provides less detailed information than WMI can provide.
Example
This example uses the My.Computer.Info.OSFullName property to display the name of the computer's operating system.
VB
MsgBox("Computer's operating system name: " & _
My.Computer.Info.OSFullName)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.Info Object
My.Computer.Info.OSPlatform Property
Microsoft.VisualBasic.Devices.ComputerInfo.OSFullName
Visual Basic Language Reference
My.Computer.Info.OSPlatform Property
Gets the platform identifier for the operating system of the computer.
' Usage
Dim value As String = My.Computer.Info.OSPlatform
' Declaration
Public ReadOnly Property OSPlatform As String
Return Value
A String containing the platform identifier for the operating system of the computer, chosen from the member names of the
PlatformID enumeration.
Exceptions
The following condition can cause an exception:
The application cannot obtain the operating-system platform information (ExecutionEngineException).
Remarks
The My.Computer.Info.OSPlatform property provides functionality similar to the Platform property of the object returned by
the OSVersion property.
Example
This example uses the My.Computer.Info.OSPlatform property to display the platform of the computer's operating system.
VB
MsgBox("Computer's operating system platform: " & _
My.Computer.Info.OSPlatform)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Info.OSVersion Property
Gets the version of the computer's operating system.
' Usage
Dim value As String = My.Computer.Info.OSVersion
' Declaration
Public ReadOnly Property OSVersion As String
Return Value
A String containing the current version number of the operating system.
Exceptions
The following condition can cause an exception:
The application cannot obtain the operating-system version information (ExecutionEngineException).
Remarks
The My.Computer.Info.OSVersion property formats the version as "major.minor.build.revision".
The My.Computer.Info.OSVersion property provides functionality similar to the Version property of the object returned by
the OSVersion property.
Example
This example uses the My.Computer.Info.OSVersion property to display the version of the computer's operating system.
VB
MsgBox("Computer's operating system version: " & _
My.Computer.Info.OSVersion)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Info.TotalPhysicalMemory Property
Gets the total amount of physical memory for the computer.
' Usage
Dim value As ULong = My.Computer.Info.TotalPhysicalMemory
' Declaration
Public ReadOnly Property TotalPhysicalMemory As ULong
Return Value
A ULong containing the number of bytes of physical memory for the computer.
Exceptions
The following condition can cause an exception:
The application cannot obtain the memory status (Win32Exception).
Remarks
The My.Computer.Info.TotalPhysicalMemory property requires Windows XP, Windows 2000 Professional, Windows Server
2003 or Windows 2000 Server.
Example
This example uses the My.Computer.Info.TotalPhysicalMemory property to display the total amount of physical memory
for the computer on which the code runs.
VB
MsgBox("Computer's available physical memory: " & _
My.Computer.Info.TotalPhysicalMemory)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Info.TotalVirtualMemory Property
Gets the total amount of virtual address space available for the computer.
' Usage
Dim value As ULong = My.Computer.Info.TotalVirtualMemory
' Declaration
Public ReadOnly Property TotalVirtualMemory As ULong
Return Value
A ULong containing the number of bytes of virtual address space available for the computer.
Exceptions
The following condition can cause an exception:
The application cannot obtain the memory status (Win32Exception).
Remarks
The My.Computer.Info.TotalVirtualMemory property requires Windows XP, Windows 2000 Professional, Windows Server
2003 or Windows 2000 Server.
Example
This example uses the My.Computer.Info.TotalVirtualMemory property to display the total amount of virtual memory for
the computer on which the code runs.
VB
MsgBox("Computer's available virtual memory: " & _
My.Computer.Info.TotalVirtualMemory)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Keyboard Object
Provides properties for accessing the current state of the keyboard, such as what keys are currently pressed, and provides a
method to send keystrokes to the active window.
Remarks
The My.Computer.Keyboard object provides an interface to the computer's keyboard. The properties of the
My.Computer.Keyboard provide information about the state of several special keys. The
My.Computer.Keyboard.SendKeys method lets you send keys to the active window as if they have been typed at the
keyboard.
Task
The following table lists examples of tasks involving the My.Computer.Keyboard object.
To See
Check if CAPS LOCK is on How to: Determine If CapsLock is On in Visual Basic
Send keystrokes to an application How to: Start an Application and Send it Keystrokes (Visual Basic)
Example
This example uses the My.Computer.Keyboard.CtrlKeyDown property to determine if the computer's CTRL key is pressed.
VB
If My.Computer.Keyboard.CtrlKeyDown Then
MsgBox("CTRL key down")
Else
MsgBox("CTRL key up")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
See Also
Reference
My.Computer.Keyboard Object Members
My.Computer Object
Microsoft.VisualBasic.Devices.Keyboard
Concepts
Accessing the Keyboard
Visual Basic Language Reference
My.Computer.Keyboard.AltKeyDown Property
Gets a Boolean indicating if the ALT key is down.
' Usage
Dim value As Boolean = My.Computer.Keyboard.AltKeyDown
' Declaration
Public ReadOnly Property AltKeyDown As Boolean
Return Value
A Boolean value: True if the ALT key is down; otherwise False.
Remarks
The My.Computer.Keyboard.AltKeyDown property provides functionality similar to the ModifierKeys property.
Example
This example uses the My.Computer.Keyboard.AltKeyDown property to determine if the computer's ALT key is down.
VB
If My.Computer.Keyboard.AltKeyDown Then
MsgBox("ALT key down")
Else
MsgBox("ALT key up")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Keyboard Object
ModifierKeys
Microsoft.VisualBasic.Devices.Keyboard.AltKeyDown
Visual Basic Language Reference
My.Computer.Keyboard.CapsLock Property
Gets a Boolean indicating if CAPS LOCK is turned on.
' Usage
Dim value As Boolean = My.Computer.Keyboard.CapsLock
' Declaration
Public ReadOnly Property CapsLock As Boolean
Return Value
A Boolean value: True if CAPS LOCK is turned on; otherwise False.
Remarks
Only the state of CAPS LOCK is returned.
Example
This example uses the My.Computer.Keyboard.CapsLock property to determine if the computer's CAPS LOCK is turned on.
VB
If My.Computer.Keyboard.CapsLock Then
MsgBox("CAPS LOCK on")
Else
MsgBox("CAPS LOCK off")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Keyboard Object
Microsoft.VisualBasic.Devices.Keyboard.CapsLock
Visual Basic Language Reference
My.Computer.Keyboard.CtrlKeyDown Property
Gets a Boolean indicating if a CTRL key is down.
' Usage
Dim value As Boolean = My.Computer.Keyboard.CtrlKeyDown
' Declaration
Public ReadOnly Property CtrlKeyDown As Boolean
Return Value
A Boolean value. True if a CTRL key is down; otherwise False.
Remarks
The My.Computer.Keyboard.CtrlKeyDown property provides functionality similar to the ModifierKeys property.
Example
This example uses the My.Computer.Keyboard.CtrlKeyDown property to determine if the computer's CTRL key is down.
VB
If My.Computer.Keyboard.CtrlKeyDown Then
MsgBox("CTRL key down")
Else
MsgBox("CTRL key up")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Keyboard Object
ModifierKeys
Microsoft.VisualBasic.Devices.Keyboard.CtrlKeyDown
Visual Basic Language Reference
My.Computer.Keyboard.NumLock Property
Gets a Boolean indicating if the NUM LOCK key is on.
' Usage
Dim value As Boolean = My.Computer.Keyboard.NumLock
' Declaration
Public ReadOnly Property NumLock As Boolean
Return Value
A Boolean value. True if NUM LOCK is on; otherwise False.
Remarks
Only the state of the NUM LOCK key is returned.
Example
This example uses the My.Computer.Keyboard.NumLock property to determine if the computer's NUM LOCK key is on.
VB
If My.Computer.Keyboard.NumLock Then
MsgBox("NUM LOCK on")
Else
MsgBox("NUM LOCK off")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Keyboard Object
Microsoft.VisualBasic.Devices.Keyboard.NumLock
Visual Basic Language Reference
My.Computer.Keyboard.ScrollLock Property
Gets a Boolean indicating whether the SCROLL LOCK key is on.
' Usage
Dim value As Boolean = My.Computer.Keyboard.ScrollLock
' Declaration
Public ReadOnly Property ScrollLock As Boolean
Return Value
A Boolean value. True if SCROLL LOCK is on; otherwise False.
Remarks
Only the state of the SCROLL LOCK key is returned.
Example
This example uses the My.Computer.Keyboard.ScrollLock property to determine if the computer's SCROLL LOCK key is on.
VB
If My.Computer.Keyboard.ScrollLock Then
MsgBox("SCROLL LOCK on")
Else
MsgBox("SCROLL LOCK off")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Keyboard Object
Microsoft.VisualBasic.Devices.Keyboard.ScrollLock
Visual Basic Language Reference
My.Computer.Keyboard.SendKeys Method
Sends one or more keystrokes to the active window, as if typed on the keyboard.
' Usage
My.Computer.Keyboard.SendKeys(keys)
My.Computer.Keyboard.SendKeys(keys ,wait)
' Declaration
Public Sub SendKeys( _
ByVal keys As String _
)
' -or-
Public Sub SendKeys( _
ByVal keys As String, _
ByVal wait As Boolean _
)
Parameters
keys
A String that defines the keys to send.
wait
Optional. A Boolean that specifies whether or not to wait for keystrokes to get processed before the application continues.
True by default.
Exceptions
The following condition can cause an exception:
A partial-trust situation exists in which the user lacks necessary permissions (SecurityException).
Remarks
The My.Computer.Keyboard.SendKeys method provides functionality similar to the Send and SendWait methods.
The wait argument is useful if the other application must finish before your application can continue.
Note
Because there is no managed method to activate another application, you can either use this class within the current applicati
on, manually select the window to send the keys to, or use Windows API methods, such as FindWindow and SetForegroun
dWindow, to force focus on other applications. For more information, see Walkthrough: Calling Windows APIs.
The keys argument can specify any single key or any key combined with ALT, CTRL, or SHIFT (or any combination of those
keys). Each key is represented by one or more characters, such as a for the character "a", or {ENTER} for the ENTER key.
To combine a key with SHIFT, precede the key code with + (plus sign). To combine a key with CTRL, precede the key code with ^
(caret). To combine a key with ALT, precede the key code with % (percent sign). To specify repeating keys, use the form {key
number}. You must put a space between key and number. For example, {LEFT 42} means "press the LEFT ARROW key 42
times"; {h 10} means "press 'h' 10 times."
The following table lists the codes that can be used to specify characters that are not displayed when you press the
corresponding key (such as ENTER or TAB).
Key Code
BACKSPACE {BACKSPACE} or {BS}
BREAK {BREAK}
END {END}
ENTER ~
HELP {HELP}
HOME {HOME}
INS {INSERT}
PAGE UP {PGUP}
RETURN {RETURN}
TAB {TAB}
UP ARROW {UP}
Web Site No
Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration: AllWindows.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
Walkthrough: Calling Windows APIs
Reference
My.Computer.Keyboard Object
Send
SendWait
Microsoft.VisualBasic.Devices.Keyboard.SendKeys(System.String,System.Boolean)
Visual Basic Language Reference
My.Computer.Keyboard.ShiftKeyDown Property
Gets a Boolean indicating if a SHIFT key is down.
' Usage
Dim value As Boolean = My.Computer.Keyboard.ShiftKeyDown
' Declaration
Public ReadOnly Property ShiftKeyDown As Boolean
Return Value
A Boolean value. True if a SHIFT key is down; otherwise False.
Remarks
The My.Computer.Keyboard.ShiftKeyDown property provides functionality similar to the ModifierKeys property.
Example
This example uses the My.Computer.Keyboard.ShiftKeyDown property to determine if one of the computer's SHIFT keys is
down.
VB
If My.Computer.Keyboard.ShiftKeyDown Then
MsgBox("SHIFT key down")
Else
MsgBox("SHIFT key up")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Keyboard Object
ModifierKeys
Microsoft.VisualBasic.Devices.Keyboard.ShiftKeyDown
Visual Basic Language Reference
My.Computer.Mouse Object
Provides properties for getting information about the format and configuration of the mouse installed on the local computer.
Remarks
The My.Computer.Mouse object provides a way to find information about the computer's mouse: whether the mouse
buttons are swapped, and details about the mouse wheel.
Example
This example uses the My.Computer.Mouse.WheelExists and My.Computer.Mouse.WheelScrollLines properties to
determine if the mouse has a scroll wheel and how much to scroll when it rotates.
VB
If My.Computer.Mouse.WheelExists Then
Dim lines As Integer = My.Computer.Mouse.WheelScrollLines
If lines > 0 Then
MsgBox("Application scrolls " & _
lines & " line(s) for each wheel turn.")
Else
MsgBox("Application scrolls " & _
(-lines) & " page(s) for each wheel turn.")
End If
Else
MsgBox("Mouse has no scroll wheel.")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Mouse
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
See Also
Reference
My.Computer.Mouse Object Members
My.Computer Object
Microsoft.VisualBasic.Devices.Mouse
Visual Basic Language Reference
WheelExists Gets a Boolean that indicates if the mouse has a scroll wheel.
This property is only available for non-server applications.
WheelScrollLines Gets a number that indicates how much to scroll when the mouse wheel is rotated one notch.
This property is available only for non-server applications.
See Also
Reference
My.Computer.Mouse Object
Visual Basic Language Reference
My.Computer.Mouse.ButtonsSwapped Property
Gets a Boolean that indicates if the functionality of the left and right mouse buttons has been swapped.
' Usage
Dim value As Boolean = My.Computer.Mouse.ButtonsSwapped
' Declaration
Public ReadOnly Property ButtonsSwapped As Boolean
Return Value
A Boolean with a value True if the functionality of the left and right mouse buttons has been swapped; otherwise, False.
Exceptions
The following condition can cause an exception:
The computer has no mouse installed (InvalidOperationException).
Remarks
The My.Computer.Mouse.ButtonsSwapped property:
Provides functionality similar to the MouseButtonsSwapped property.
Provides information about the computer that runs the code.
Example
This example uses the My.Computer.Mouse.ButtonsSwapped property to determine if functionality of the left and right
mouse buttons has been swapped.
VB
If My.Computer.Mouse.ButtonsSwapped Then
MsgBox("Functionality of the mouse buttons is swapped.")
Else
MsgBox("Default functionality of the mouse buttons.")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Mouse
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Mouse.WheelExists Property
Gets a Boolean that indicates if the mouse has a scroll wheel.
' Usage
Dim value As Boolean = My.Computer.Mouse.WheelExists
' Declaration
Public ReadOnly Property WheelExists As Boolean
Return Value
A Boolean with value True if the mouse has a scroll wheel; otherwise False.
Exceptions
The following condition can cause an exception:
The computer has no mouse installed (InvalidOperationException).
Remarks
The My.Computer.Mouse.WheelExists property provides functionality similar to the MouseWheelPresent property.
You should check the value of the My.Computer.Mouse.WheelExists property before attempting to access the
My.Computer.Mouse.WheelScrollLines Property, which throws an exception if the mouse does not have a scroll wheel.
The My.Computer.Mouse.WheelExists property provides information about the computer that runs the code.
Example
This example uses the My.Computer.Mouse.WheelExists property to determine if the mouse has a scroll wheel and how
much to scroll when the mouse wheel is rotated.
VB
If My.Computer.Mouse.WheelExists Then
Dim lines As Integer = My.Computer.Mouse.WheelScrollLines
If lines > 0 Then
MsgBox("Application scrolls " & _
lines & " line(s) for each wheel turn.")
Else
MsgBox("Application scrolls " & _
(-lines) & " page(s) for each wheel turn.")
End If
Else
MsgBox("Mouse has no scroll wheel.")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Mouse
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Mouse Object
My.Computer.Mouse.WheelScrollLines Property
Microsoft.VisualBasic.Devices.Mouse.WheelExists
Visual Basic Language Reference
My.Computer.Mouse.WheelScrollLines Property
Gets a number that indicates how much to scroll when the mouse wheel is rotated one notch.
' Usage
Dim value As Integer = My.Computer.Mouse.WheelScrollLines
' Declaration
Public ReadOnly Property WheelScrollLines As Integer
Return Value
An Integer that indicates how much to scroll when the mouse wheel is rotated one notch. A positive value indicates scrolling
by that number of lines, while a negative value indicates scrolling by one screen at a time.
Exceptions
The following conditions can cause an exception:
The computer has no mouse installed (InvalidOperationException).
The mouse has no scroll wheel (InvalidOperationException).
Remarks
You can use this property to determine how many lines to scroll up or down in a multi-line control that has a scroll bar.
The My.Computer.Mouse.WheelScrollLines property provides functionality similar to the MouseWheelScrollLines property.
Because this property throws an exception if the mouse does not have a scroll wheel, you should make sure a mouse has a
scroll wheel by checking the My.Computer.Mouse.WheelExists property.
This property provides information about the computer that runs the code.
Example
This example determines if the mouse has a scroll wheel and uses the My.Computer.Mouse.WheelExists property to
determine how much to scroll when the mouse wheel is rotated.
VB
If My.Computer.Mouse.WheelExists Then
Dim lines As Integer = My.Computer.Mouse.WheelScrollLines
If lines > 0 Then
MsgBox("Application scrolls " & _
lines & " line(s) for each wheel turn.")
Else
MsgBox("Application scrolls " & _
(-lines) & " page(s) for each wheel turn.")
End If
Else
MsgBox("Mouse has no scroll wheel.")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Mouse
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes
Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Mouse Object
My.Computer.Mouse.WheelExists Property
Microsoft.VisualBasic.Devices.Mouse.WheelScrollLines
Visual Basic Language Reference
My.Computer.Network Object
Provides a property, event, and methods for interacting with the network to which the computer is connected.
Tasks
The following table lists examples of tasks involving the My.Computer.Network object.
To See
Upload a file How to: Upload a File in Visual Basic
Check connection status How to: Check Connection Status in Visual Basic
Determine if a remote computer is available How to: Determine if a Remote Computer is Available in Visual Basic
Example
This example uploads the file Order.txt to http://www.cohowinery.com/uploads.
VB
My.Computer.Network.UploadFile ( _
"C:\My Documents\Order.txt", _
"http://www.cohowinery.com/uploads.aspx")
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Network
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.Network Object Members
My.Computer Object
My.Computer.Network.NetworkAvailabilityChanged Event
Microsoft.VisualBasic.Devices.Network
Visual Basic Language Reference
My.Computer.Network.DownloadFile Method
Downloads the specified remote file and saves it in the specified location.
' Usage
My.Computer.Network.DownloadFile(address ,destinationFileName)
My.Computer.Network.DownloadFile(address ,destinationFileName)
My.Computer.Network.DownloadFile(address ,destinationFileName ,userName ,password)
My.Computer.Network.DownloadFile(address ,destinationFileName ,userName ,password)
My.Computer.Network.DownloadFile(address ,destinationFileName ,userName ,password ,showUI ,
connectionTimeout ,overwrite)
My.Computer.Network.DownloadFile(address ,destinationFileName ,userName ,password ,showUI ,
connectionTimeout ,overwrite ,onUserCancel)
My.Computer.Network.DownloadFile(address ,destinationFileName ,userName ,password ,showUI ,
connectionTimeout ,overwrite)
My.Computer.Network.DownloadFile(address ,destinationFileName ,userName ,password ,showUI ,
connectionTimeout ,overwrite ,onUserCancel)
My.Computer.Network.DownloadFile(address ,destinationFileName ,networkCredentials ,showUI ,
connectionTimeout ,overwrite)
My.Computer.Network.DownloadFile(address ,destinationFileName ,networkCredentials ,showUI ,
connectionTimeout ,overwrite ,onUserCancel)
' Declaration
Public Sub DownloadFile( _
ByVal address As String, _
ByVal destinationFileName As String _
)
' -or-
Public Sub DownloadFile( _
ByVal address As System.Uri, _
ByVal destinationFileName As String _
)
' -or-
Public Sub DownloadFile( _
ByVal address As String, _
ByVal destinationFileName As String, _
ByVal userName As String, _
ByVal password As String _
)
' -or-
Public Sub DownloadFile( _
ByVal address As System.Uri, _
ByVal destinationFileName As String, _
ByVal userName As String, _
ByVal password As String _
)
' -or-
Public Sub DownloadFile( _
ByVal address As String, _
ByVal destinationFileName As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub DownloadFile( _
ByVal address As String, _
ByVal destinationFileName As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal overwrite As Boolean, _
ByVal onUserCancel As UICancelOption _
)
' -or-
Public Sub DownloadFile( _
ByVal address As System.Uri, _
ByVal destinationFileName As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub DownloadFile( _
ByVal address As System.Uri, _
ByVal destinationFileName As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal overwrite As Boolean, _
ByVal onUserCancel As UICancelOption _
)
' -or-
Public Sub DownloadFile( _
ByVal address As System.Uri, _
ByVal destinationFileName As String, _
ByVal networkCredentials As System.Net.ICredentials, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub DownloadFile( _
ByVal address As System.Uri, _
ByVal destinationFileName As String, _
ByVal networkCredentials As System.Net.ICredentials, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal overwrite As Boolean, _
ByVal onUserCancel As UICancelOption _
)
Parameters
address
String or Uri. Path of the file to download, including file name and host address. Required.
destinationFileName
String. File name and path of the downloaded file. Required.
userName
String. User name to authenticate. Default is an empty string, "".
password
String.Password to authenticate. Default is an empty string, "".
showUI
Boolean. Specifies whether to display the progress of the operation. Default is False.
connectionTimeout
Int32. Timeout interval, in milliseconds. Default is 100 seconds.
overwrite
Boolean. Specifies whether to overwrite existing files. Default is False.
onUserCancel
UICancelOption. Specifies behavior when the user clicks Cancel or No on the dialog box shown as a result of ShowUI set to
True. Default is ThrowException.
networkCredentials
ICredentials. Credentials to be supplied.
Exceptions
The following conditions may cause an exception to be thrown:
The drive name is not valid (ArgumentException).
destinationFileName ends with a trailing slash (ArgumentException).
overwrite is set to False and the destination file already exists (IOException).
The server does not respond within the specified connectionTimeout (TimeoutException).
The authentication fails (SecurityException).
User lacks necessary permissions (SecurityException).
The request is denied by the website (WebException).
Remarks
If showUI is set to True, a dialog box appears that shows the progress of the operation; the dialog box contains a Cancel
button that can be used to cancel the operation. The dialog box is not modal, and therefore does not block user input to other
windows in the program.
If the server does not respond within the specified connectionTimeout, the operation is cancelled, and an exception is thrown.
DownloadFile outputs trace information when you enable network tracing in your application. For more information, see
Enabling Network Tracing.
Note
The DownloadFile method does not send optional HTTP headers. Some servers may return 500 (Internal Server Error) if the
optional user agent header is missing. To send optional headers, you must construct a request using the WebClient class. For
more information, see Network Operations in the .NET Framework with Visual Basic.
Security Note
The FTP protocol sends information, including passwords, in plain text and should not be used for transmitting sensitive infor
mation.
Tasks
The following table lists an example of a task involving the My.Computer.Network.DownloadFile method.
To See
Download a file How to: Download a File in Visual Basic
Example
This example downloads the file WineList.txt from http://www.cohowinery.com/downloads and saves it to C:\Documents
and Settings\All Users\Documents.
VB
My.Computer.Network.DownloadFile _
("http://www.cohowinery.com/downloads/WineList.txt", _
"C:\Documents and Settings\All Users\Documents\WineList.txt")
This example downloads the file WineList.txt from http://www.cohowinery.com/downloads and saves it to C:\Documents
and Settings\All Users\Documents, specifying a timeout interval of 500 milliseconds.
VB
My.Computer.Network.DownloadFile _
("http://www.cohowinery.com/downloads/", _
"C:\Documents and Settings\All Users\Documents\WineList.txt", _
"", "", False, 500, True)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Network
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration: AllWindows.
WebPermission Controls rights to access HTTP Internet resources. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Download a File in Visual Basic
How to: Determine if a Remote Computer is Available in Visual Basic
How to: Parse File Paths in Visual Basic
Reference
My.Computer.Network Object
System.Uri
System.Net.ICredentials
Microsoft.VisualBasic.Devices.Network.DownloadFile
Visual Basic Language Reference
My.Computer.Network.IsAvailable Property
Indicates whether a computer is connected to a network.
' Usage
Dim value As Boolean = My.Computer.Network.IsAvailable
' Declaration
Public ReadOnly Property IsAvailable As Boolean
Return Value
Boolean.
Remarks
IsAvailable always returns False when called from a Click Once application or if the user does not have
NetworkInformationPermission.
Tasks
The following table lists examples of tasks involving the My.Computer.Network.IsAvailable property.
To See
Check whether a computer is connected to a network How to: Check Connection Status in Visual Basic
Example
This example checks the property's status and reports it.
VB
If My.Computer.Network.IsAvailable = True Then
MsgBox("Computer is connected.")
Else
MsgBox("Computer is not connected.")
End If
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Network
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
WebPermission Controls rights to access HTTP Internet resources. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine if a Remote Computer is Available in Visual Basic
Reference
My.Computer.Network Object
Microsoft.VisualBasic.Devices.Network.IsAvailable
Visual Basic Language Reference
My.Computer.Network.Ping Method
Pings the specified server.
' Usage
Dim value As Boolean = My.Computer.Network.Ping(hostNameOrAddress)
Dim value As Boolean = My.Computer.Network.Ping(address)
Dim value As Boolean = My.Computer.Network.Ping(hostNameOrAddress ,timeout)
Dim value As Boolean = My.Computer.Network.Ping(address ,timeout)
' Declaration
Public Function Ping( _
ByVal hostNameOrAddress As String _
) As Boolean
' -or-
Public Function Ping( _
ByVal address As System.Uri _
) As Boolean
' -or-
Public Function Ping( _
ByVal hostNameOrAddress As String, _
ByVal timeout As Integer _
) As Boolean
' -or-
Public Function Ping( _
ByVal address As System.Uri, _
ByVal timeout As Integer _
) As Boolean
Parameters
hostNameOrAddress
String. The URL, computer name, or IP number of the server to ping. Required.
address
Uri. The URI of the server to ping. Required.
timeout
Int32. Time threshold in milliseconds for contacting the destination. Default is 500. Required.
Return Value
Boolean indicating whether or not the operation was successful.
Exceptions
The following conditions may cause an exception to be thrown:
No network connection is available (InvalidOperationException).
URL was not valid (PingException).
Remarks
The Ping method is not a fail-safe method for determining the availability of a remote computer: the ping port on the target
computer may be turned off or the ping request may be blocked by a firewall or router.
The address passed to the Ping method must be DNS resolvable and cannot be preceded by "http://".
Tasks
The following table lists examples of tasks involving the My.Computer.Network.Ping method.
To See
Determine whether a remote computer or host is availabl How to: Determine if a Remote Computer is Available in Visual Basic
e
Example
This example reports whether or not the server can be pinged by determining whether the Ping method returns True.
VB
If My.Computer.Network.Ping("198.01.01.01") Then
MsgBox("Server pinged successfully.")
Else
MsgBox("Ping request timed out.")
End If
Replace "198.01.01.01" with the IP address, URL, or computer name of the server to ping.
This example reports whether or not the server can be pinged by determining whether the Ping method returned True and
specifies a timeout interval of 1000 milliseconds.
VB
If My.Computer.Network.Ping("www.cohowinery.com",1000) Then
MsgBox("Server pinged successfully.")
Else
MsgBox("Ping request timed out.")
End If
Replace "www.cohowinery.com" with the IP address, URL, or computer name of the server to ping.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Network
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
WebPermission Controls rights to access HTTP Internet resources. Associated enumeration: Unrestricted.
SocketPermission Controls rights to make or accept connections on a transport address. Associated enumeratio
n: Unrestricted.
NetworkInformationPermission Controls access to network information and traffic statistics for the local computer. Associated
enumeration: Ping.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.Network Object
System.Uri
Microsoft.VisualBasic.Devices.Network.Ping
Visual Basic Language Reference
My.Computer.Network.NetworkAvailabilityChanged Event
Occurs when the network availability changes.
' Usage
Public Sub MyComputerNetwork_NetworkAvailabilityChanged( _
ByVal sender As Object, _
ByVal e As Devices.NetworkAvailableEventArgs _
)
End Sub
Sub Handle_NetworkAvailabilityChanged()
AddHandler My.Computer.Network.NetworkAvailabilityChanged, _
AddressOf MyComputerNetwork_NetworkAvailabilityChanged
End Sub
' Declaration
Public Event NetworkAvailabilityChanged( _
ByVal sender As Object, _
ByVal e As Devices.NetworkAvailableEventArgs _
)
Parameters
sender
Required. The Object that raised the event.
e
Required. A NetworkAvailableEventArgs object that contains information about the availability of the network.
Remarks
An application raises the NetworkAvailabilityChanged event every time the availability of the network changes. You can use
the IsNetworkAvailable property of the e parameter to get the new state of the network connection. To get the current state of
the network connection, use the My.Computer.Network.IsAvailable Property.
In a Windows Forms application, this event is raised on the application's main thread with the other user-interface events. This
allows the event handler to directly access the application's user interface. However, if the application is busy handling another
user-interface event when this event is raised, this event cannot be processed until the other event handler finishes or calls the
My.Application.DoEvents Method.
You cannot use the Handles statement to handle the NetworkAvailabilityChanged event; you must use the AddHandler
statement.
In Windows Forms applications, the My.Application object exposes a NetworkAvailabilityChanged event that provides the
same functionality as this event, but you can handle it with the Handles statement. For more information, see
My.Application.NetworkAvailabilityChanged Event.
Note
Many network hubs provide a network connection, even if the hub is disconnected from a larger network. Consequently, for
wired connections, this event indicates a change in the connection between the computer and a hub.
Note
The NetworkAvailabilityChanged event is not raised by applications that run on Windows 95 and Windows 98 or by appli
cations that are run on Windows 2000 by a non-administrator. If your application might run on those platforms, use the
My.Computer.Network.IsAvailable Property to check for network availability.
Example
This example uses the My.Computer.Network.NetworkAvailabilityChanged event to update the user interface of a form
or control.
VB
Private Sub DisplayAvailability(ByVal available As Boolean)
Label1.Text = available.ToString
End Sub
DisplayAvailability(e.IsNetworkAvailable)
End Sub
This code should to be in a form or control that has a Label named Label1. You must call the
Handle_NetworkAvailabilityChanged method to initialize the label and hook up the event handler.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Network
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Network.UploadFile Method
Sends the specified file to the specified host address.
' Usage
My.Computer.Network.UploadFile(sourceFileName ,address)
My.Computer.Network.UploadFile(sourceFileName ,address)
My.Computer.Network.UploadFile(sourceFileName ,address ,userName ,password)
My.Computer.Network.UploadFile(sourceFileName ,address ,userName ,password)
My.Computer.Network.UploadFile(sourceFileName ,address ,userName ,password ,showUI ,connect
ionTimeout)
My.Computer.Network.UploadFile(sourceFileName ,address ,userName ,password ,showUI ,connect
ionTimeout ,onUserCancel)
My.Computer.Network.UploadFile(sourceFileName ,address ,userName ,password ,showUI ,connect
ionTimeout)
My.Computer.Network.UploadFile(sourceFileName ,address ,userName ,password ,showUI ,connect
ionTimeout ,onUserCancel)
My.Computer.Network.UploadFile(sourceFileName ,address ,networkCredentials ,showUI ,connect
ionTimeout)
My.Computer.Network.UploadFile(sourceFileName ,address ,networkCredentials ,showUI ,connect
ionTimeout ,onUserCancel)
' Declaration
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As String _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As System.Uri _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As String, _
ByVal userName As String, _
ByVal password As String _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As System.Uri, _
ByVal userName As String, _
ByVal password As String _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal onUserCancel As UICancelOption _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As System.Uri, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As System.Uri, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal onUserCancel As UICancelOption _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As System.Uri, _
ByVal networkCredentials As System.Net.ICredentials, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As System.Uri, _
ByVal networkCredentials As System.Net.ICredentials, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal onUserCancel As UICancelOption _
)
Parameters
sourceFileName
String. Path and name of file to upload. Required.
address
String or Uri. URL, IP address, or URI of destination server. Required.
userName
String. User name to authenticate. Default is an empty string: "".
password
String. Password to authenticate. Default is an empty string: "".
showUI
Boolean. Whether to display progress of the operation. Default is False.
connectionTimeout
Int32. Timeout interval in milliseconds. Default is 100 seconds.
onUserCancel
UICancelOption. Action to be taken when the user clicks Cancel. Default is ThrowException.
networkCredentials
ICredentials. Credentials for authentication.
Exceptions
The following conditions may cause an exception:
The local file path is not valid (ArgumentException).
connectionTimeout is less than or equal to zero (ArgumentException).
address does not include a file name (InvalidOperationException).
Authentication failed (SecurityException).
User lacks necessary permissions (SecurityException).
Connection timed out (TimeoutException).
The website denies the request (WebException).
Remarks
If showUI is set to True, a dialog box shows the progress of the operation and includes a Cancel button that the user can click
to cancel the operation. Because the dialog box is not modal, it does not block user input to other windows in the program.
If the server does not respond within the interval specified in connectionTimeout, the operation is cancelled and an exception is
thrown.
My.Computer.Network.UploadFile outputs trace information when you enable network tracing in your application. For
more information, see Enabling Network Tracing.
Security Note
The FTP protocol sends information, including passwords, in plain text and should not be used for transmitting sensitive infor
mation.
Tasks
The following table lists an example of a task involving the My.Computer.Network.UploadFile method.
To See
Upload a file How to: Upload a File in Visual Basic
Example
This example uploads the file Order.txt to http://www.cohowinery.com/uploads.
VB
My.Computer.Network.UploadFile ( "C:\My Documents\Order.txt", _
"http://www.cohowinery.com/upload.aspx")
This example uploads the file Order.txt to http://www.cohowinery.com/uploads without supplying a user name or password,
shows the progress of the upload, and has a time-out interval of 500 milliseconds.
VB
My.Computer.Network.UploadFile ("C:\My Documents\Order.txt", _
"http://www.cohowinery.com/upload.aspx","","",True,500)
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Network
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration: AllWindows.
WebPermission Controls rights to access HTTP Internet resources. Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Download a File in Visual Basic
How to: Parse File Paths in Visual Basic
Reference
My.Computer.Network Object
System.Uri
System.Net.ICredentials
Microsoft.VisualBasic.FileIO.UICancelOption
Microsoft.VisualBasic.Devices.Network.UploadFile
Visual Basic Language Reference
My.Computer.Ports Object
Provides a property and a method for accessing the computer's serial ports.
Remarks
The My.Computer.Ports object provides a straightforward entry point for accessing the .NET Framework serial port class,
SerialPort.
Tasks
The following table lists examples of tasks involving the My.Computer.Ports object.
To See
Dial a modem attached to a serial port How to: Dial Modems Attached to Serial Ports in Visual Basic
Send a string to a serial port How to: Send Strings to Serial Ports in Visual Basic
Receive strings from a serial port How to: Receive Strings From Serial Ports in Visual Basic
Show available serial ports How to: Show Available Serial Ports in Visual Basic
Example
This example describes how to send strings to the computer's COM1 serial port.
The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates the
serial port should appear within this block, or within a Try...Catch...Finally block with a call to use the Close method.
The WriteLine method sends the data to the serial port.
VB
Sub SendSerialData(ByVal data As String)
' Send strings to a serial port.
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1")
com1.WriteLine(data)
End Using
End Sub
For more information, see How to: Send Strings to Serial Ports in Visual Basic.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Ports
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Web Site No
See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Send Strings to Serial Ports in Visual Basic
How to: Receive Strings From Serial Ports in Visual Basic
How to: Show Available Serial Ports in Visual Basic
Reference
My.Computer.Ports Object Members
My.Computer Object
Microsoft.VisualBasic.Devices.Ports
Visual Basic Language Reference
My.Computer.Ports.OpenSerialPort Method
Creates and opens a SerialPort object.
' Usage
Dim value As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(portName)
Dim value As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(portName ,baudRa
te)
Dim value As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(portName ,baudRa
te ,parity)
Dim value As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(portName ,baudRa
te ,parity ,dataBits)
Dim value As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(portName ,baudRa
te ,parity ,dataBits ,stopBits)
' Declaration
Public Function OpenSerialPort( _
ByVal portName As String _
) As System.IO.Ports.SerialPort
' -or-
Public Function OpenSerialPort( _
ByVal portName As String, _
ByVal baudRate As Integer _
) As System.IO.Ports.SerialPort
' -or-
Public Function OpenSerialPort( _
ByVal portName As String, _
ByVal baudRate As Integer, _
ByVal parity As System.IO.Ports.Parity _
) As System.IO.Ports.SerialPort
' -or-
Public Function OpenSerialPort( _
ByVal portName As String, _
ByVal baudRate As Integer, _
ByVal parity As System.IO.Ports.Parity, _
ByVal dataBits As Integer _
) As System.IO.Ports.SerialPort
' -or-
Public Function OpenSerialPort( _
ByVal portName As String, _
ByVal baudRate As Integer, _
ByVal parity As System.IO.Ports.Parity, _
ByVal dataBits As Integer, _
ByVal stopBits As System.IO.Ports.StopBits _
) As System.IO.Ports.SerialPort
Parameters
portName
String. Required. Name of the port to open.
baudRate
Integer. Baud rate of the port.
parity
Parity. Parity of the port.
dataBits
Integer. Data-bit setting of the port.
stopBits
StopBits. Stop-bit setting of the port.
Return Value
An open SerialPort object, configured with the supplied arguments.
Exceptions
The following conditions can cause an exception:
The portName argument is Nothing or an empty string (ArgumentNullException).
The baudRate or dataBits argument is zero or negative (ArgumentException).
The parity argument type is not one of the Parity enumeration values (InvalidEnumArgumentException).
The stopBits argument type is not one of the StopBits enumeration values (InvalidEnumArgumentException).
Remarks
The My.Computer.Ports.OpenSerialPort method creates and opens a SerialPort object. The arguments to the
OpenSerialPort method determine the settings of the SerialPort object.
Your code should close the SerialPort object when it is finished using the object. You can use the Close method to close the
object explicitly or the Using statement to close it implicitly. See the example in this topic for more information.
Tasks
The following table lists examples of tasks involving the My.Computer.Ports.OpenSerialPort method.
To See
Dial a modem attached to a serial port How to: Dial Modems Attached to Serial Ports in Visual Basic
Send a string to serial port How to: Send Strings to Serial Ports in Visual Basic
Receive strings from a serial port How to: Receive Strings From Serial Ports in Visual Basic
Example
This example describes how to send strings to the computer's COM1 serial port.
The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates the
serial port should appear within this block, or within a Try...Catch...Finally block with a call to use the Close method.
The WriteLine method sends the data to the serial port.
VB
Sub SendSerialData(ByVal data As String)
' Send strings to a serial port.
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1")
com1.WriteLine(data)
End Using
End Sub
For more information, see How to: Send Strings to Serial Ports in Visual Basic.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Ports
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Send Strings to Serial Ports in Visual Basic
How to: Receive Strings From Serial Ports in Visual Basic
Reference
My.Computer.Ports Object
My.Computer.Ports.SerialPortNames Property
Using Statement (Visual Basic)
System.IO.Ports.Parity
System.IO.Ports.StopBits
System.IO.Ports.SerialPort
Microsoft.VisualBasic.Devices.Ports.OpenSerialPort(System.String)
Visual Basic Language Reference
My.Computer.Ports.SerialPortNames Property
Gets a collection of the names of the serial ports on the computer.
' Usage
Dim value As System.Collections.Generic.ReadOnlyCollection`1(Of String) = My.Computer.Ports
.SerialPortNames
' Declaration
Public ReadOnly Property SerialPortNames As System.Collections.Generic.ReadOnlyCollection`1
(Of String)
Return Value
A collection of the names of the serial ports on the computer.
Remarks
The My.Computer.Ports.SerialPortNames property gets a collection of the names of the serial ports on the computer.
Note
The port names returned by My.Computer.Ports.SerialPortNames may be incorrect when run on Windows 98. To prevent
application errors, use exception handling, such as the Try...Catch...Finally statement or the Using statement, when using th
e port names to open ports.
Tasks
The following table lists an example of a task involving the My.Computer.Ports.SerialPortNames property.
To See
Show available serial ports How to: Show Available Serial Ports in Visual Basic
Example
This example loops over all the strings that the My.Computer.Ports.SerialPortNames property returns. These strings are the
names of the available serial ports on the computer.
Typically, a user selects which serial port the application should use from the list of available ports. In this example, the serial
port names are stored in a ListBox control. For more information, see ListBox Control (Windows Forms).
VB
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
ListBox1.Items.Add(sp)
Next
End Sub
Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Show Available Serial Ports in Visual Basic
Reference
My.Computer.Ports Object
My.Computer.Ports.OpenSerialPort Method
Try...Catch...Finally Statement (Visual Basic)
Using Statement (Visual Basic)
ReadOnlyCollection
Microsoft.VisualBasic.Devices.Ports.SerialPortNames
Visual Basic Language Reference
My.Computer.Registry Object
Provides properties and methods for manipulating the registry.
Remarks
To use these properties, you must have Read and Write permission from the RegistryPermissionAccess Enumeration. Any code
running with full trust (under the default security policy, this is any code installed on the user's local hard drive) has the
necessary permissions to access the registry. For more information, see RegistryPermission Class.
Tasks
The following table lists examples of tasks involving the My.Computer.Registry object.
To See
Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic
Determine if a value in a registry key exists How to: Determine if a Value Exists in a Registry Key in Visual Basic
Write data to a registry key How to: Set Values in Registry Keys in Visual Basic
Delete a registry key How to: Delete a Registry Key in Visual Basic
Read data from the registry How to: Read a Value from a Registry Key in Visual Basic
Example
This example reads the value Name from HKEY_CURRENT_USER\Software\MyApp and displays it in a message box.
VB
Dim readValue As Object
readValue = My.Computer.Registry.GetValue _
("HKEY_CURRENT_USER\Software\MyApp", "Name", Nothing)
MsgBox("The value is " & CStr(readValue))
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
Walkthrough: Creating a Registry Key and Changing Its Values
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object Members
My.Computer.Registry.ClassesRoot Property
My.Computer.Registry.CurrentConfig Property
My.Computer.Registry.CurrentUser Property
My.Computer.Registry.DynData Property
My.Computer.Registry.LocalMachine Property
My.Computer.Registry.PerformanceData Property
My.Computer.Registry.Users Property
My.Computer.Registry.GetValue Method
My.Computer.Registry.SetValue Method
My.Computer Object
Microsoft.Win32.Registry
Concepts
Common Registry Tasks
Visual Basic Language Reference
My.Computer.Registry.ClassesRoot Property
Returns a RegistryKey type which provides access to HKEY_CLASSES_ROOT.
' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.ClassesRoot
' Declaration
Public ReadOnly Property ClassesRoot As Microsoft.Win32.RegistryKey
Return Value
RegistryKey
Remarks
The My.Computer.Registry object offers methods and properties for working with registry keys. See
My.Computer.Registry Object for more information.
HKEY_CLASSES_ROOT is primarily used to store information about file associations in Windows.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant only those privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Description
AllAccess Create, read, and write access to registry variables.
Delete a registry key How to: Delete a Registry Key in Visual Basic
Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic
Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic
Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example gets the names of the subkeys for the ClassesRoot registry key and adds them to ListBox1.
VB
Dim keyList As System.Collections.IEnumerable
keyList = My.Computer.Registry.ClassesRoot.GetSubKeyNames()
For Each keyName As String In keyList
ListBox1.Items.Add(keyName)
Next
This example requires that you have a ListBox named ListBox1 in your project.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryKey
Microsoft.Win32.Registry.ClassesRoot
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference
My.Computer.Registry.CurrentConfig Property
Returns a RegistryKey type which provides access to HKEY_CURRENT_CONFIG.
' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentConfig
' Declaration
Public ReadOnly Property CurrentConfig As Microsoft.Win32.RegistryKey
Return Value
RegistryKey
Remarks
The My.Computer.Registry object offers methods and properties for working with registry keys. See
My.Computer.Registry Object for more information.
HKEY_CURRENT_CONFIG is primarily used to store settings for devices on the computer.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant only those privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Description
AllAccess Create, read, and write access to registry variables.
Delete a registry key How to: Delete a Registry Key in Visual Basic
Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic
Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic
Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example creates the subkey MyDeviceSettings.
VB
My.Computer.Registry.CurrentConfig.CreateSubKey("MyDeviceSettings")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryKey
Microsoft.Win32.Registry.CurrentConfig
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference
My.Computer.Registry.CurrentUser Property
Returns a RegistryKey type which provides access to HKEY_CURRENT_USER.
' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentUser
' Declaration
Public ReadOnly Property CurrentUser As Microsoft.Win32.RegistryKey
Return Value
RegistryKey
Remarks
The My.Computer.Registry object offers methods and properties for working with registry keys. See
My.Computer.Registry Object for more information.
HKEY_CURRENT_USER is primarily used to store per-user settings, such as colors and fonts, in Windows. The key differ
according to the user.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant the fewest privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Description
AllAccess Create, read, and write access to registry variables.
Delete a registry key How to: Delete a Registry Key in Visual Basic
Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic
Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic
Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example deletes the subkey Software\MyCompany\Preferences\UserData.
VB
My.Computer.Registry.CurrentUser.DeleteSubKey _
("Software\MyCompany\Preferences\UserData")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryKey
Microsoft.Win32.Registry.CurrentUser
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference
My.Computer.Registry.DynData Property
Returns a RegistryKey type, which provides access to HKEY_DYNDATA.
' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.DynData
' Declaration
Public ReadOnly Property DynData As Microsoft.Win32.RegistryKey
Return Value
RegistryKey
Remarks
The My.Computer.Registry object offers methods and properties for working with registry keys. See
My.Computer.Registry Object for more information.
HKEY_DYNDATA is used to store dynamic registry data, such as that used by Virtual Device Drivers and is supported only on
Windows 95/98 systems. On non-Windows 95/98 systems, calling any methods of the key returned by Registry.DynData,
such as CreateSubKey, DeleteSubKey, GetSubKeyCount, GetValueCount, etc., will throw a IOException.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant the fewest privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Description
AllAccess Create, read, and write access to registry variables.
Delete a registry key How to: Delete a Registry Key in Visual Basic
Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic
Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic
Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example deletes the subkey tree Software\MyCompany\Preferences.
VB
My.Computer.Registry.DynData.DeleteSubKeyTree("Software\MyCompany\Preferences")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Registry.GetValue Method
Gets a value from a registry key.
' Usage
Dim value As Object = My.Computer.Registry.GetValue(keyName ,valueName ,defaultValue)
' Declaration
Public Function GetValue( _
ByVal keyName As String, _
ByVal valueName As String, _
ByVal defaultValue As Object _
) As Object
Parameters
keyName
String. Key from which the value is to be retrieved. Required.
valueName
String. Value to be retrieved. Required.
defaultValue
Object. Default value to be supplied if the value does not exist. Required.
Remarks
valueName is not case-sensitive.
A registry key can contain one value that is not associated with any name. When this unnamed value is displayed in the
registry editor, the string "(Default)" appears instead of a name. To retrieve this unnamed value, specify either null or the empty
string ("") for valueName.
Exceptions
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The user does not have permissions to read from registry keys (SecurityException).
The key name exceeds the 255-character limit (ArgumentException).
Tasks
The following table lists examples of tasks involving the GetValue method.
To See
Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic
Example
This example reads the value Name from HKEY_CURRENT_USER\Software\MyApp and displays it in a MessageBox.
VB
Dim readValue As Object
readValue = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\MyApp", "Name", Nothi
ng)
MsgBox("The value is " & CStr(readValue))
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
GetValue
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference
My.Computer.Registry.LocalMachine Property
Returns a RegistryKey type, which provides access to HKEY_LOCAL_MACHINE.
' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.LocalMachine
' Declaration
Public ReadOnly Property LocalMachine As Microsoft.Win32.RegistryKey
Return Value
RegistryKey
Remarks
The My.Computer.Registry object offers methods and properties for working with registry keys. See
My.Computer.Registry Object for more information.
HKEY_LOCAL_MACHINE is usually used to store settings that do not vary from user to user in Windows. All users of the
computer share this key. Its five subkeys (Hardware, SAM, Security, Software, and System) hold configuration data for the
local machine.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant the fewest privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Description
AllAccess Create, read, and write access to registry variables.
Delete a registry key How to: Delete a Registry Key in Visual Basic
Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic
Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic
Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example opens the subkey Software\MyCompany\Preferences and sets the value FontColor to "red".
VB
My.Computer.Registry.LocalMachine.OpenSubKey _
("Software\MyCompany\Preferences", True)
My.Computer.Registry.LocalMachine.SetValue("FontColor", "red")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryKey
Microsoft.Win32.Registry.LocalMachine
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference
My.Computer.Registry.PerformanceData Property
Returns a RegistryKey type, which provides access to HKEY_PERFORMANCE_DATA.
' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.PerformanceData
' Declaration
Public ReadOnly Property PerformanceData As Microsoft.Win32.RegistryKey
Return Value
RegistryKey
Remarks
HKEY_PERFORMANCE_DATA is used to access performance information for software components. Each software component
creates keys for its objects and counters when it is installed and writes counter data while it is executing. This data is not stored
in the registry, although the registry is used to access it. Instead, calling registry functions via HKEY_PERFORMANCE_DATA
causes the system to collect the data from the appropriate system object managers.
This key does not exist on Windows 98 systems; an attempt to use it other than calling the Name method will throw an
IOException.
This key cannot normally be written to; attempting to create a subkey on it will throw an IOException.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant the fewest privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Description
AllAccess Create, read, and write access to registry variables.
Delete a registry key How to: Delete a Registry Key in Visual Basic
Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic
Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic
Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example gets the value ThisSoftware from the MyCompany subkey.
VB
My.Computer.Registry.PerformanceData.GetValue("MyCompany\ThisSoftware")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
My.Computer.Registry.SetValue Method
Writes a value to a registry key.
' Usage
My.Computer.Registry.SetValue(keyName ,valueName ,value)
My.Computer.Registry.SetValue(keyName ,valueName ,value ,valueKind)
' Declaration
Public Sub SetValue( _
ByVal keyName As String, _
ByVal valueName As String, _
ByVal value As Object _
)
' -or-
Public Sub SetValue( _
ByVal keyName As String, _
ByVal valueName As String, _
ByVal value As Object, _
ByVal valueKind As Microsoft.Win32.RegistryValueKind _
)
Parameters
keyName
String. Name of the key to be written to. Required.
valueName
String. Name of the value to be written. Required.
value
Object. Value to be written. Required.
valueKind
RegistryValueKind. Required.
Remarks
If the specified key or value does not exist, it is created.
Exceptions
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The key name exceeds the 255-character limit (ArgumentException).
The specified hive is not valid (ArgumentException).
The key is closed (IOException).
The path is not valid (IOException).
The registry key is read-only (UnauthorizedAccessException).
Tasks
Here is an example of a task involving the My.Computer.Registry.SetValue method.
To See
Set a value in a registry key How to: Create a Registry Key and Set Its Values in Visual Basic
Example
This example sets the value Name to "Author's Name" in the key HKEY_CURRENT_USER\Software\MyApp.
VB
Dim readValue As Object
readValue = My.Computer.Registry.GetValue _
("HKEY_CURRENT_USER\Software\MyApp", "Name", Nothing)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryValueKind
Microsoft.Win32.Registry.SetValue
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Registry Access for Visual Basic 6.0 Users
Visual Basic Language Reference
My.Computer.Registry.Users Property
Returns a RegistryKey type, which provides access to HKEY_USERS.
' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.Users
' Declaration
Public ReadOnly Property Users As Microsoft.Win32.RegistryKey
Return Value
RegistryKey
Remarks
The My.Computer.Registry object offers methods and properties for working with registry keys. See
My.Computer.Registry Object for more information.
HKEY_USERS is primarily used to store default settings for first-time users.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant the fewest privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Access to Registry Variables
AllAccess Create, read, and write
Create Create
NoAccess No access.
Read Read
Write Write
Tasks
The following table lists examples of tasks involving the My.Computer.Registry object.
To See
Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic
Delete a registry key How to: Delete a Registry Key in Visual Basic
Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic
Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic
Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example counts and displays the number of values in the registry key.
VB
Dim keyCount as Integer
keyCount = My.Computer.Registry.Users.ValueCount
MsgBox(keyCount)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryKey
Microsoft.Win32.Registry.Users
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference
My.Forms Object
Provides properties for accessing an instance of each Windows form declared in the current project.
Remarks
The My.Forms object provides an instance of each form in the current project. The name of the property is the same as the
name of the form that the property accesses. For information about adding forms to a project, see
How to: Add Windows Forms to a Project.
You can access the forms provided by the My.Forms object by using the name of the form, without qualification. Because the
property name is the same as the form's type name, this allows you to access a form as if it had a default instance. For
example, My.Forms.Form1.Show is equivalent to Form1.Show.
The My.Forms object exposes only the forms associated with the current project. It does not provide access to forms declared
in referenced DLLs. To access a form that a DLL provides, you must use the qualified name of the form, written as
DllName.FormName. For more information, see How to: Access a Form.
You can use the My.Application.OpenForms Property to get a collection of all the application's open forms.
The object and its properties are available only for Windows applications.
Properties
Each property of the My.Forms object provides access to an instance of a form in the current project. The name of the property
is the same as the name of the form that the property accesses, and the property type is the same as the form's type.
Note
If there is a name collision, the property name to access a form is RootNamespace_Namespace_FormName. For example, co
nsider two forms named Form1.If one of these forms is in the root namespace WindowsApplication1 and in the namespace N
amespace1, you would access that form through My.Forms.WindowsApplication1_Namespace1_Form1.
The My.Forms object provides access to the instance of the application's main form that was created on startup. For all other
forms, the My.Forms object creates a new instance of the form when it is accessed and stores it. Subsequent attempts to
access that property return that instance of the form.
You can dispose of a form by assigning Nothing to the property for that form. The property setter calls the Close method of
the form, and then assigns Nothing to the stored value. If you assign any value other than Nothing to the property, the setter
throws an ArgumentException exception.
You can test whether a property of the My.Forms object stores an instance of the form by using the Is or IsNot operator. You
can use those operators to check if the value of the property is Nothing.
Note
Typically, the Is or IsNot operator has to read the value of the property to perform the comparison. However, if the property
currently stores Nothing, the property creates a new instance of the form and then returns that instance. However, the Visua
l Basic compiler treats the properties of the My.Forms object differently and allows the Is or IsNot operator to check the stat
us of the property without altering its value.
Tasks
The following table lists examples of tasks involving the My.Forms object.
To See
Access one form from another form. How to: Access a Form
Control one form from another form. How to: Communicate Between Forms in an Application
Example
This example changes the title of the default SidebarMenu form.
VB
Sub ShowSidebarMenu(ByVal newTitle As String)
If My.Forms.SidebarMenu IsNot Nothing Then
My.Forms.SidebarMenu.Text = newTitle
End If
End Sub
For this example to work, your project must have a form named SidebarMenu. For more information, see
How to: Add Windows Forms to a Project.
This code will work only in a Windows Application project.
Requirements
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No
Console Application No
Windows Service No
Web Site No
See Also
Tasks
How to: Add Windows Forms to a Project
How to: Access a Form
Reference
My.Application.OpenForms Property
My.Application.OpenForms Property
Is Operator (Visual Basic)
IsNot Operator
Form
Close
Concepts
Accessing Application Forms
Visual Basic Language Reference
My.Log Object
Provides a property and methods for writing event and exception information to the application's log listeners.
Remarks
The My.Log object provides a straightforward entry point with which to access the .NET Framework's logging services. The
WriteEntry and WriteException methods write messages to the application's log listeners. The listeners can be configured by
the application's configuration file. For more information, see
Walkthrough: Changing Where My.Application.Log Writes Information and Working with Application Logs in Visual Basic.
The My.Log object is only available for ASP.NET applications. For client applications, use My.Application.Log. For more
information, see My.Application.Log Object.
Requirements
Namespace: Microsoft.VisualBasic.Logging
Class: Log
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Write Log Messages
How to: Log Exceptions in Visual Basic
Walkthrough: Determining Where My.Application.Log Writes Information
Reference
My.Log Object Members
My.Application Object
My.Application.Log Object
Microsoft.VisualBasic.Logging.Log
Visual Basic Language Reference
My.Request Object
Gets the HttpRequest object for the requested page.
Remarks
The My.Request object contains information about the current HTTP request.
The My.Request object is available only for ASP.NET applications.
Example
The following example gets the header collection from the My.Request object and uses the My.Response object to write it to
the ASP.NET page.
VB
<script runat="server">
Public Sub ShowHeaders()
' Load the header collection from the Request object.
Dim coll As System.Collections.Specialized.NameValueCollection
coll = My.Request.Headers
See Also
Reference
My.Response Object
HttpRequest
Visual Basic Language Reference
My.Response Object
Gets the HttpResponse object associated with the Page. This object allows you to send HTTP response data to a client and
contains information about that response.
Remarks
The My.Response object contains the current HttpResponse object associated with the page.
The My.Response object is only available for ASP.NET applications.
Example
The following example gets the header collection from the My.Request object and uses the My.Response object to write it to
the ASP.NET page.
VB
<script runat="server">
Public Sub ShowHeaders()
' Load the header collection from the Request object.
Dim coll As System.Collections.Specialized.NameValueCollection
coll = My.Request.Headers
See Also
Reference
My.Request Object
HttpResponse
Visual Basic Language Reference
My.Resources Object
Provides properties and classes for accessing the application's resources.
Remarks
The My.Resources object provides access to the application's resources and allows you to dynamically retrieve resources for
your application. For more information, see Managing Application Resources.
The My.Resources object exposes only global resources. It does not provide access to resource files associated with forms.
You must access the form resources from the form. For more information, see Walkthrough: Localizing Windows Forms.
You can access the application's culture-specific resource files from the My.Resources object. By default, the My.Resources
object looks up resources from the resource file that matches the culture in My.Application.UICulture Property. However, you
can override this behavior and specify a particular culture to use for the resources. For more information, see
Resources in Applications.
Properties
The properties of the My.Resources object provide read-only access to your application's resources. To add or remove
resources, use the Project Designer. For more information, see How to: Add or Remove Resources. Resources added through
the Project Designer are accessed using My.Resources.resourceName.
You can also add or remove resource files by selecting your project in Solution Explorer and choosing Add New Item or
Add Existing Item from the Project menu. Resources added this way are available using
My.Resources.resourceFileName.resourceName.
Each resource has a name, category, and value, and these resource settings determine how the property to access the resource
appears in the My.Resources object. For resources added in the Project Designer:
The name determines the name of the property,
The resource data is the value of the property,
The category determines the type of the property:
Categ Property data type
ory
String String
s
Imag Bitmap
es
Icons Icon
Audio UnmanagedMemoryStream
The UnmanagedMemoryStream class derives from the Stream class, so it can be used with methods that take s
treams, such as the My.Computer.Audio.Play Method.
Classes
The My.Resources object exposes each resource file as a class with shared properties. The class name is the same as the name
of the resource file. As described in the previous section, the resources in a resource file are exposed as properties in the class.
Tasks
The following table lists examples of tasks involving the My.Resources object.
To See
Retrieve a string resource How to: Retrieve String Resources in Visual Basic
Retrieve an image resource How to: Retrieve Image Resources in Visual Basic
Retrieve an icon resource How to: Retrieve Icon Resources in Visual Basic
Retrieve an audio resource How to: Retrieve Audio Resources in Visual Basic
Retrieve a localized resource How to: Retrieve Localized Resources in Visual Basic
Example
This example sets the icon of the form to the icon named Form1Icon that is stored in the application's resource file.
VB
Sub SetFormIcon()
Me.Icon = My.Resources.Form1Icon
End Sub
For this example to work, your application must have an icon named Form1Icon in the application's resource file. For more
information, see How to: Add or Remove Resources.
See Also
Tasks
How to: Retrieve String Resources in Visual Basic
How to: Retrieve Image Resources in Visual Basic
How to: Retrieve Icon Resources in Visual Basic
How to: Retrieve Audio Resources in Visual Basic
How to: Retrieve Localized Resources in Visual Basic
How to: Add or Remove Resources
Walkthrough: Localizing Windows Forms
Reference
My.Application.UICulture Property
Concepts
Resources in Applications
Other Resources
Managing Application Resources
Visual Basic Language Reference
My.Settings Object
Provides properties and methods for accessing the application's settings.
Remarks
The My.Settings object provides access to the application's settings and allows you to dynamically store and retrieve property
settings and other information for your application. For more information, see Managing Application Settings.
Properties
The properties of the My.Settings object provide access to your application's settings. To add or remove settings, use the
Settings Designer. For more information, see How to: Add or Remove Application Settings.
Each setting has a Name, Type, Scope, and Value, and these settings determine how the property to access each setting
appears in the My.Settings object:
Name determines the name of the property.
Type determines the type of the property.
Scope indicates if the property is read-only. If the value is Application, the property is read-only; if the value is User, the
property is read-write.
Value is the default value of the property.
Methods
Method Description
Reload Reloads the user settings from the last saved values.
The My.Settings object also provides advanced properties and methods, inherited from the ApplicationSettingsBase class.
Tasks
The following table lists examples of tasks involving the My.Settings object.
To See
Read an application setting How to: Read Application Settings in Visual Basic
Change a user setting How to: Change User Settings in Visual Basic
Persist user settings How to: Persist User Settings in Visual Basic
Create a property grid for user settings How to: Create Property Grids for User Settings in Visual Basic
Example
This example displays the value of the Nickname setting.
VB
Sub ShowNickname()
MsgBox("Nickname is " & My.Settings.Nickname)
End Sub
For this example to work, your application must have a Nickname setting, of type String. For more information, see
How to: Add or Remove Application Settings.
See Also
Tasks
How to: Read Application Settings in Visual Basic
How to: Change User Settings in Visual Basic
How to: Persist User Settings in Visual Basic
How to: Create Property Grids for User Settings in Visual Basic
How to: Add or Remove Application Settings
Reference
ApplicationSettingsBase
Other Resources
Managing Application Settings
Visual Basic Language Reference
My.User Object
Provides access to the information about the current user.
Remarks
The properties and methods exposed by the My.User object provide access to the information about the current user. The
meaning of "current user" differs slightly between Windows and Web applications. In a Windows application, the current user
is the user who runs the application. In a Web application, the current user is the user who accesses the application.
The My.User property also provides access to the IPrincipal for the current user. A principal object represents the user's
security context, including that user's identity and any roles to which the user belongs.
For Windows applications, this property provides the same functionality as the CurrentPrincipal property. For Web
applications, this property provides the same functionality as the User property of the object returned by the Current property.
Note
For Windows applications, only projects built on the Windows Application template initialize the My.User object by defaul
t. In all other Windows project types, you must initialize the My.User object by calling the
My.User.InitializeWithWindowsUser Method explicitly or by assigning a value to CurrentPrincipal.
Note
The My.User object cannot report information about the current Windows user when run under Windows 95 and Windows
98 because those operating systems do not support the concept of a logged-on user. You must implement custom authentic
ation to use the My.User object on those operating systems. For more information, see
Walkthrough: Implementing Custom Authentication and Authorization.
Tasks
The following table lists examples of tasks involving the My.User object.
To See
Get the user's login name How to: Determine a User's Login Name
Get the user's domain name, if the application uses Wi How to: Determine the User's Domain
ndows authentication
IsAuthenticated Gets a value that indicates whether the user has been authenticated.
IsInRole Determines whether the current user belongs to the specified role.
See Also
Reference
My.User Object
Visual Basic Language Reference
My.User.CurrentPrincipal Property
Gets or sets the current principal (for role-based security).
' Usage
Dim value As System.Security.Principal.IPrincipal = My.User.CurrentPrincipal
' Declaration
Public Property CurrentPrincipal As System.Security.Principal.IPrincipal
Return Value
A IPrincipal value representing the security context.
Exceptions
The following conditions can cause an exception:
The caller does not have the permission required to set the principal (SecurityException).
Remarks
You can set the My.User.CurrentPrincipal property to an object that implements the IPrincipal interface to enable custom
authentication.
In most project types, this property gets and sets the thread's current principal. In an ASP.NET application, this property gets
and sets the security information for the current HTTP request's user identity.
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Tasks
To See
Get the user's login name How to: Determine a User's Login Name
Get the user's domain name, if the application uses Wi How to: Determine the User's Domain
ndows authentication
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: User, WebUser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine a User's Login Name
How to: Determine the User's Domain
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
System.Security.Principal.IPrincipal
Microsoft.VisualBasic.ApplicationServices.User.CurrentPrincipal
Visual Basic Language Reference
My.User.InitializeWithWindowsUser Method
Sets the thread's current principal to the Windows user that started the application.
' Usage
My.User.InitializeWithWindowsUser()
' Declaration
Public Sub InitializeWithWindowsUser()
Remarks
You can use the My.User.InitializeWithWindowsUser method to set the thread's current principal to the Windows user that
started the application. The Visual Basic Application Model in a Windows application calls this method at startup by default. In
other project types, you must set the thread's current principal by calling this method explicitly or by assigning a value to
System.Threading.Thread.CurrentPrincipal.
In Windows projects, the My.User object is based on the thread's current principal; therefore, this method can change the
information My.User returns. In an ASP.NET application, the My.User object is based on the current HTTP request's user
identity, and is unaffected by this method.
Note
The exact behavior of the My.User object depends on the type of application and on the operating system on which the appli
cation runs. For more information, see My.User Object.
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: User, WebUser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
Microsoft.VisualBasic.ApplicationServices.User.InitializeWithWindowsUser
Visual Basic Language Reference
My.User.IsAuthenticated Property
Gets a value that indicates whether the user has been authenticated.
' Usage
Dim value As Boolean = My.User.IsAuthenticated
' Declaration
Public ReadOnly Property IsAuthenticated As Boolean
Return Value
True if the user was authenticated; otherwise, False.
Remarks
The My.User.IsAuthenticated property allows your code to determine if the current user has been authenticated.
Note
The exact behavior of My.User object depends on the type of the application and on the operating system on which the appli
cation runs. For more information, see My.User Object.
Tasks
To See
Implement custom authentication Walkthrough: Implementing Custom Authentication and Authorization
Example
This example verifies that the user has been authenticated before accessing a resource.
VB
If My.User.IsAuthenticated Then
' Insert code to access a resource here.
End If
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: User, WebUser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
Microsoft.VisualBasic.ApplicationServices.User.IsAuthenticated
Visual Basic Language Reference
My.User.IsInRole Method
Determines whether the current user belongs to the specified role.
' Usage
Dim value As Boolean = My.User.IsInRole(role)
Dim value As Boolean = My.User.IsInRole(role)
' Declaration
Public Function IsInRole( _
ByVal role As String _
) As Boolean
' -or-
Public Function IsInRole( _
ByVal role As BuiltInRole _
) As Boolean
Parameters
role
String or BuiltInRole Enumeration. The role for which to check membership.
Return Value
True if the current user is a member of the specified role; otherwise, False.
Remarks
The My.User.IsInRole method allows your code to determine if the current user is a member of the specified role.
The overload of the My.User.IsInRole method that takes a string provides easy access to the IsInRole method of the current
principal.
The overload of the My.User.IsInRole method that takes a BuiltInRole enumeration behaves differently, depending on the
current principal. If it is a Windows user principal (WindowsPrincipal), this function converts role to the equivalent
WindowsBuiltInRole enumeration and returns the result of calling IsInRole. If the current principal is any other principal, this
function passes the name of the enumeration value in role to the principal's IsInRole method.
Note
The exact behavior of the My.User object depends on the type of the application and on the operating system on which the a
pplication runs. For more information, see My.User Object.
Tasks
To See
Determine the user's role How to: Determine if a User is in a Group
Example
This example checks if the user is an administrator before accessing a resource.
VB
If My.User.IsInRole( _
ApplicationServices.BuiltInRole.Administrator) Then
' Insert code to access a resource here.
End If
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: User, WebUser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine if a User is in a Group
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
BuiltInRole Enumeration
Microsoft.VisualBasic.ApplicationServices.BuiltInRole
Microsoft.VisualBasic.ApplicationServices.User.IsInRole(System.String)
Visual Basic Language Reference
My.User.Name Property
Gets the name of the current user.
' Usage
Dim value As String = My.User.Name
' Declaration
Public ReadOnly Property Name As String
Return Value
String. The name of the current user.
Remarks
You can use the My.User object to get information about the current user.
The principal that authenticates the user also controls the format of the user name. By default, an application uses Windows
authentication, and the user name has the format DOMAIN\USERNAME. A custom implementation of the principal does not
necessarily use the same format.
Note
The My.User.Name property returns an empty string when run under Windows 95 and Windows 98 because those operati
ng systems do not recognize user names.
Note
The exact behavior of the My.User object depends on the type of the application and on the operating system on which the a
pplication runs. For more information, see My.User Object.
Tasks
The following table lists examples of tasks involving the My.User.Name property.
To See
Get the user's login name How to: Determine a User's Login Name
Get the user's domain name, if the application uses Wi How to: Determine the User's Domain
ndows authentication
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine a User's Login Name
How to: Determine the User's Domain
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
Microsoft.VisualBasic.ApplicationServices.User.Name
Visual Basic Language Reference
My.WebServices Object
Provides properties for creating and accessing a single instance of each XML Web service referenced by the current project.
Remarks
The My.WebServices object provides an instance of each Web service referenced by the current project. Each instance is
instantiated on demand. You can access these Web services through the properties of the My.WebServices object. The name
of the property is the same as the name of the Web service that the property accesses. Any class that inherits from
SoapHttpClientProtocol is a Web service. For information about adding Web services to a project, see
How to: Access an XML Web Service in Managed Code.
The My.WebServices object exposes only the Web services associated with the current project. It does not provide access to
Web services declared in referenced DLLs. To access a Web service that a DLL provides, you must use the qualified name of the
Web service, in the form DllName.WebServiceName. For more information, see
Accessing XML Web Services in Managed Code.
The object and its properties are not available for Web applications.
Properties
Each property of the My.WebServices object provides access to an instance of a Web service referenced by the current
project. The name of the property is the same as the name of the Web service that the property accesses, and the property type
is the same as the Web service's type.
Note
If there is a name collision, the property name to access a Web service is RootNamespace_Namespace_ServiceName. For exa
mple, consider two Web services named Service1.If one of these services is in the root namespace WindowsApplication1 an
d in the namespace Namespace1, you would access that service through My.WebServices.WindowsApplication1_Namespace1_
Service1.
When you first access one of the My.WebServices object's properties, it creates a new instance of the Web service and stores
it. Subsequent accesses of that property return that instance of the Web service.
You can dispose of a Web service by assigning Nothing to the property for that Web service. The property setter assigns
Nothing to the stored value. If you assign any value other than Nothing to the property, the setter throws an
ArgumentException exception.
You can test whether a property of the My.WebServices object stores an instance of the Web service by using the Is or IsNot
operator. You can use those operators to check if the value of the property is Nothing.
Note
Typically, the Is or IsNot operator has to read the value of the property to perform the comparison. However, if the property
currently stores Nothing, the property creates a new instance of the Web service and then returns that instance. However, th
e Visual Basic compiler treats the properties of the My.WebServices object specially, and allows the Is or IsNot operator to
check the status of the property without altering its value.
Tasks
The following table lists an example of a task involving the My.Forms object.
To See
Call a Web Service asynchronously and handle an event when it completes How to: Call a Web Service Asynchronously
Example
This example calls the FahrenheitToCelsius method of the TemperatureConverter XML Web service, and returns the result.
VB
Function ConvertFromFahrenheitToCelsius( _
ByVal dFahrenheit As Double) _
As Double
Return My.WebServices.TemperatureConverter.FahrenheitToCelsius(dFahrenheit)
End Function
For this example to work, your project must reference a Web service named Converter, and that Web service must expose the
ConvertTemperature method. For more information, see How to: Access an XML Web Service in Managed Code.
Web Site No
See Also
Tasks
How to: Access an XML Web Service in Managed Code
Reference
SoapHttpClientProtocol
ArgumentException
Concepts
Accessing Application Web Services
Other Resources
Accessing XML Web Services in Managed Code
Visual Basic Language Reference
TextFieldParser Object
Provides methods and properties for parsing structured text files.
Exceptions
The following condition may cause an exception:
A text field does not match the specified format. For example, in a fixed-width file, one of the fields does not match the
specified width. (MalformedLineException).
Remarks
The TextFieldParser object provides methods and properties for parsing structured text files. Parsing a text file with the
TextFieldParser is similar to iterating over a text file, while the ReadFields method to extract fields of text is similar to
splitting the strings.
The TextFieldParser can parse two types of files: delimited or fixed-width. Some properties, such as Delimiters and
HasFieldsEnclosedInQuotes are meaningful only when working with delimited files, while the FieldWidths property is
meaningful only when working with fixed-width files.
Tasks
The following table lists examples of tasks involving the Microsoft.VisualBasic.FileIO.TextFieldParser object.
To See
Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic
Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic
Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats in Visual Basic
Example
This example parses through a tab-delimited text file, Bigfile.
VB
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser _
("c:\logs\bigfile")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {vbTab}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
" is invalid. Skipping")
End Try
End While
End Using
This example depends on the existence of a function, processFields, which processes the fields as they are read.
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser Object Members
TextFieldParser.CommentTokens Property
TextFieldParser.Delimiters Property
TextFieldParser.EndOfData Property
TextFieldParser.ErrorLine Property
TextFieldParser.ErrorLineNumber Property
TextFieldParser.FieldWidths Property
TextFieldParser.HasFieldsEnclosedInQuotes Property
TextFieldParser.LineNumber Property
TextFieldParser.TextFieldType Property
TextFieldParser.TrimWhiteSpace Property
TextFieldParser.Close Method
TextFieldParser.PeekChars Method
TextFieldParser.ReadFields Method
TextFieldParser.ReadLine Method
TextFieldParser.ReadToEnd Method
TextFieldParser.SetDelimiters Method
TextFieldParser.SetFieldWidths Method
My.Computer.FileSystem.OpenTextFieldParser Method
Microsoft.VisualBasic.FileIO.TextFieldParser
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference
Delimiters String. The delimiters for the text file. Valid only for delimited files.
EndOfData Boolean. Returns True if there are no non-blank, non-comment lines between the current cursor
position and the end of the file.
ErrorLine String. Returns the line that caused the most recent MalformedLineException. Default is "".
ErrorLineNumber Long. Returns the line number that caused the most recent MalformedLineException. Default is
-1.
FieldWidths Integer. Denotes the width of each column in the text file. Valid only for fixed-width files.
HasFieldsEnclosedInQuotes Boolean. Returns True if fields can be enclosed in quotation marks. Valid only for delimited files.
Default is True.
LineNumber Integer. Returns the current line number, or -1 if no more characters are available.
TrimWhiteSpace Boolean. Indicates whether leading and trailing white spaces should be trimmed from field values
.
Methods
Close Closes the underlying stream.
PeekChars Reads the specified number of characters without advancing the cursor.
ReadFields Reads all fields on the current line, returns them as an array of strings, and advances cursor to the next line.
ReadLine Returns the current line as a String and advances the cursor to the next line.
SetDelimiters Sets the delimiters for the reader to the specified values and the field type to Delimited.
SetFieldWidths Sets the delimiters for the reader to the specified values and the field type to FixedWidth.
See Also
Reference
TextFieldParser Object
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference
TextFieldParser Constructor
Initializes a new instance of the TextFieldParser class.
' Usage
Dim value As New TextFieldParser(path)
Dim value As New TextFieldParser(path, defaultEncoding)
Dim value As New TextFieldParser(path, defaultEncoding, detectEncoding)
Dim value As New TextFieldParser(stream)
Dim value As New TextFieldParser(stream, defaultEncoding)
Dim value As New TextFieldParser(stream, defaultEncoding, detectEncoding)
Dim value As New TextFieldParser(stream, defaultEncoding, detectEncoding, leaveOpen)
Dim value As New TextFieldParser(reader)
' Declaration
Public Sub New( _
ByVal path As String _
)
' -or-
Public Sub New( _
ByVal path As String, _
ByVal defaultEncoding As System.Text.Encoding _
)
' -or-
Public Sub New( _
ByVal path As String, _
ByVal defaultEncoding As System.Text.Encoding, _
ByVal detectEncoding As Boolean _
)
' -or-
Public Sub New( _
ByVal stream As Stream _
)
' -or-
Public Sub New( _
ByVal stream As Stream, _
ByVal defaultEncoding As System.Text.Encoding _
)
' -or-
Public Sub New( _
ByVal stream As Stream, _
ByVal defaultEncoding As System.Text.Encoding, _
ByVal detectEncoding As Boolean _
)
' -or-
Public Sub New( _
ByVal stream As Stream, _
ByVal defaultEncoding As System.Text.Encoding, _
ByVal detectEncoding As Boolean, _
ByVal leaveOpen As Boolean _
)
' -or-
Public Sub New( _
ByVal reader As TextReader _
)
Parameters
path
String. The complete path of the file to be parsed.
stream
Stream. The stream to be parsed.
defaultEncoding
Encoding. The character encoding to use if encoding is not determined from file. Default is UTF8.
detectEncoding
Boolean. Indicates whether to look for byte order marks at the beginning of the file. Default is True.
leaveOpen
Boolean. Indicates whether to leave stream open when the TextFieldParser object is closed. Default is False.
reader
TextReader. The TextReader stream to be parsed.
Remarks
Creates a new TextFieldParser object to parse the file or stream represented by the path, stream, or reader parameters.
If the defaultEncoding parameter is specified, this constructor uses it as the default encoding.
If the detectEncoding parameter is True, this constructor attempts to detect the encoding by looking at the first three bytes of
the file or stream. It automatically recognizes UTF-8, little-endian Unicode, and big-endian Unicode text if the file starts with the
appropriate byte-order marks. Otherwise, the encoding specified by defaultEncoding is used.
Caution
When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cul
tural setting, the characters might not be interpretable and could cause an exception to be thrown.
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.#ctor(System.IO.Stream)
Visual Basic Language Reference
TextFieldParser.Close Method
Closes the current TextFieldParser object.
' Usage
TextFieldParserObject.Close()
' Declaration
Public Sub Close()
Remarks
This method closes a TextFieldParser object.
Example
This example closes the TextFieldParser FileReader.
VB
FileReader.Close()
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.Close
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference
TextFieldParser.CommentTokens Property
Defines comment tokens. A comment token is a string that, when placed at the beginning of a line, indicates that the line is a
comment and should be ignored by the parser.
' Usage
Dim value As String() = TextFieldParserObject.CommentTokens
' Declaration
Public Property CommentTokens As String()
Return Value
String ().
Exceptions
The following condition may produce an exception:
A comment token includes white space (ArgumentException).
Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Zero-length comment tokens are ignored.
Example
This example specifies that for the TextFieldParser, FileReader lines beginning with a single quotation mark (') should be
ignored.
VB
FileReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
FileReader.CommentTokens = New String() {"'"}
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.CommentTokens
Visual Basic Language Reference
TextFieldParser.Delimiters Property
Defines the delimiters for a text file.
' Usage
Dim value As String() = TextFieldParserObject.Delimiters
' Declaration
Public Property Delimiters As String()
Return Value
String ().
Exceptions
The following condition may result in an exception:
An attempt to use a newline character, an empty string, or Nothing as a delimiter (ArgumentException).
Remarks
This property is meaningful only if TextFieldType = FieldType.Delimited.
Defining the delimiters for a text file can also be accomplished with the SetDelimiters method. For more information, see
TextFieldParser.SetDelimiters Method.
Tasks
The following table lists an example of a task involving the Delimiters property.
To See
Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic
Example
This example specifies that the delimiter for the TextFieldParser object, FileReader, is a comma (,).
VB
FileReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
FileReader.Delimiters = New String() {","}
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
TextFieldParser Object
TextFieldParser.SetDelimiters Method
Microsoft.VisualBasic.FileIO.TextFieldParser.Delimiters
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference
TextFieldParser.EndOfData Property
Returns True if there are no non-blank, non-comment lines between the current cursor position and the end of the file.
' Usage
Dim value As Boolean = TextFieldParserObject.EndOfData
' Declaration
Public ReadOnly Property EndOfData As Boolean
Return Value
Boolean.
Remarks
This property can be used when reading from files to determine the end of the data being read.
Tasks
The following table lists examples of tasks involving the EndOfData property.
To See
Read from a delimited file How to: Read From Comma-Delimited Text Files in Visual Basic
Read from a fixed-width file How to: Read From Fixed-width Text Files in Visual Basic
Example
This example uses the EndofData property to loop through all the fields in the file with the TextFieldReader, FileReader.
VB
Dim StdFormat As Integer() = {5, 10, 11, -1}
Dim ErrorFormat As Integer() = {5, 5, -1}
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
FileReader.TextFieldType = FileIO.FieldType.FixedWidth
FileReader.FieldWidths = StdFormat
Dim CurrentRow As String()
While Not FileReader.EndOfData
Try
Dim RowType As String = FileReader.PeekChars(3)
If String.Compare(RowType, "Err") = 0 Then
' If this line describes an error, the format of the row will be different.
FileReader.SetFieldWidths(ErrorFormat)
CurrentRow = FileReader.ReadFields
FileReader.SetFieldWidths(StdFormat)
Else
' Otherwise parse the fields normally
CurrentRow = FileReader.ReadFields
For Each newString As String In CurrentRow
My.Computer.FileSystem.WriteAllText("newFile.txt", newString, True)
Next
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permissions are required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlEvidence.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.EndOfData
Visual Basic Language Reference
TextFieldParser.ErrorLine Property
Returns the line that caused the most recent MalformedLineException exception.
' Usage
Dim value As String = TextFieldParserObject.ErrorLine
' Declaration
Public ReadOnly Property ErrorLine As String
Return Value
String.
Remarks
If no MalformedLineException exceptions have been thrown, an empty string is returned.
The TextFieldParser.ErrorLineNumber Property can be used to display the number of the line causing the exception.
Tasks
The following table lists examples of tasks involving the ErrorLine property.
To See
Read from a delimited file How to: Read From Comma-Delimited Text Files in Visual Basic
Read from a fixed-width file How to: Read From Fixed-width Text Files in Visual Basic
Example
This example uses the ErrorLine property to display the line causing the current MalformedLineException exception.
VB
Dim FileReader As Microsoft.VisualBasic.FileIO.TextFieldParser
FileReader = My.Computer.FileSystem.OpenTextFieldParser("C:\test.txt")
Dim currentRow As String()
While Not FileReader.EndOfData
Try
currentRow = FileReader.ReadFields
For Each currentField As String In currentRow
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", currentField, True)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & FileReader.ErrorLine & " is not valid.")
End Try
End While
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Text Files with Multiple Formats in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Test Code with a Try…Catch Block in Visual Basic
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.ErrorLine
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference
TextFieldParser.ErrorLineNumber Property
Returns the number of the line that caused the most recent MalformedLineException exception.
' Usage
Dim value As Long = TextFieldParserObject.ErrorLineNumber
' Declaration
Public ReadOnly Property ErrorLineNumber As Long
Return Value
Long.
Exceptions
This property throws no exceptions.
Remarks
If no MalformedLineException exceptions have been thrown, -1 is returned.
The TextFieldParser.ErrorLine Property can be used to display the number of the line causing the exception. Blank lines and
comments are not ignored when determining the line number.
Tasks
The following table lists examples of tasks involving the ErrorLineNumber property.
To See
Read from a delimited file How to: Read From Comma-Delimited Text Files in Visual Basic
Read from a fixed-width file How to: Read From Fixed-width Text Files in Visual Basic
Example
This example uses the ErrorLineNumber property to display the location of the line causing the current
MalformedLineException exception.
VB
Dim FileReader As Microsoft.VisualBasic.FileIO.TextFieldParser
FileReader = My.Computer.FileSystem.OpenTextFieldParser("C:\test.txt")
Dim currentRow As String()
While Not FileReader.EndOfData
Try
currentRow = FileReader.ReadFields
For Each currentField As String In currentRow
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", currentField, True)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & FileReader.ErrorLineNumber & " is not valid.")
End Try
End While
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Text Files with Multiple Formats in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Test Code with a Try…Catch Block in Visual Basic
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.ErrorLineNumber
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference
TextFieldParser.FieldWidths Property
Denotes the width of each column in the text file being parsed.
' Usage
Dim value As Integer() = TextFieldParserObject.FieldWidths
' Declaration
Public Property FieldWidths As Integer()
Return Value
Integer ().
Exceptions
The following condition may produce an exception:
A width value in any place other than the last entry of the array is less than or equal to zero (ArgumentException).
Remarks
This property is meaningful only if TextFieldParser.TextFieldType Property = FieldType.FixedWidth. If the last entry in the
array is less than or equal to zero, the field is assumed to be of variable width.
The SetFieldWidths method can also be used to set field widths. For more information, see
TextFieldParser.SetFieldWidths Method.
Tasks
The following table lists examples of tasks involving the FieldWidths property.
To See
Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic
Example
This example reads the file ParserText.txt, specifying the widths; the first column is 5 characters wide, the second is 10, the
third is 11, and the fourth is of variable width
VB
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
MyReader.FieldWidths = New Integer() {5, 10, 11, -1}
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser Object
FieldType Enumeration
Microsoft.VisualBasic.FileIO.TextFieldParser.FieldWidths
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference
TextFieldParser.HasFieldsEnclosedInQuotes Property
Denotes whether fields are enclosed in quotation marks when parsing a delimited file.
' Usage
Dim value As Boolean = TextFieldParserObject.HasFieldsEnclosedInQuotes
' Declaration
Public Property HasFieldsEnclosedInQuotes As Boolean
Return Value
Boolean.
Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
If the property is True, the parser assumes that fields are enclosed in quotation marks (" ") and may contain line endings.
If a field is enclosed in quotation marks, for example, abc, “field2a,field2b”, field3 and this property is True, then all text
enclosed in quotation marks will be returned as is; this example would return abc|field2a,field2b|field3. Setting this
property to False would make this example return abc|”field2a|field2b”|field3.
Example
This example sets the HasFieldsEnclosedInQuotes property to True for myReader.
VB
FileReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
FileReader.Delimiters = New String() {","}
FileReader.CommentTokens = New String() {""}
FileReader.HasFieldsEnclosedInQuotes = True
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.HasFieldsEnclosedInQuotes
Visual Basic Language Reference
TextFieldParser.LineNumber Property
Returns the current line number, or returns -1 if no more characters are available in the stream.
' Usage
Dim value As Long = TextFieldParserObject.LineNumber
' Declaration
Public ReadOnly Property LineNumber As Long
Return Value
Integer.
Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Blank lines and comments are not ignored when determining the line number.
Example
This example searches for the name "Jones" in the text file and reports what line(s) it occurs on.
VB
Using FileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
FileReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
FileReader.Delimiters = New String() {","}
Dim currentRow As String()
While Not FileReader.EndOfData
Try
currentRow = FileReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
If currentField = "Jones" Then
MsgBox("The name Jones occurs on line " & _
FileReader.LineNumber)
End If
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.LineNumber
Visual Basic Language Reference
TextFieldParser.PeekChars Method
Reads the specified number of characters without advancing the cursor.
' Usage
Dim value As String = TextFieldParserObject.PeekChars(numberOfChars)
' Declaration
Public Function PeekChars( _
ByVal numberOfChars As Integer _
) As String
Parameters
numberOfChars
Int32. Number of characters to read. Required.
Return Value
String.
Exceptions
The following condition may cause an exception to be thrown:
numberOfChars is less than 0 (ArgumentException).
Remarks
The numberOfChars value must be less than the total number of characters in the line. If it is not, the string returned by
PeekChars will be truncated to the length of the line.
Blank lines are ignored.
End-of-line characters are not returned.
The PeekChars method performs no parsing; an end-of- line character within a delimited field is interpreted as the actual end
of the line.
Tasks
The following table lists examples of tasks involving the PeekChars method.
To See
Determine the format of a field before parsing it How to: Read From Text Files with Multiple Formats in Visual Basic
Example
This example uses PeekChars to find the end of the data and stop parsing the file at that point.
VB
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
MyReader.CommentTokens = New String() {"'"}
Dim currentRow As String()
While (MyReader.PeekChars(1) IsNot "")
Try
currentRow = MyReader.ReadFields()
For Each currentField As String In currentRow
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", currentField, True)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permissions are required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlEvidence.
For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
TextFieldParser Object
PeekChars
Concepts
Parsing Text Files with the TextFieldParser Object
Other Resources
Reading from Files in Visual Basic
Visual Basic Language Reference
TextFieldParser.ReadFields Method
Reads all fields on the current line, returns them as an array of strings, and advances the cursor to the next line containing data.
' Usage
Dim value As String() = TextFieldParserObject.ReadFields()
' Declaration
Public Function ReadFields() As String()
Return Value
String ().
Exceptions
The following condition may cause an exception to be thrown:
A field cannot be parsed using the specified format (MalformedLineException).
Remarks
In order to allow users to parse text files in multiple formats, the ReadFields method examines the values of TextFieldType,
Delimiters, and FieldWidths, if they are specified, each time it is called. Users need to correctly configure the TextFieldType
and FieldWidths or Delimiters properties, as appropriate. If TextFieldType is set to Delimited, and Delimiters is not set, or
if TextFieldType is set to FixedWidth and FieldWidths, an exception is thrown.
If ReadFields encounters blank lines, they are skipped and the next non-blank line is returned.
Tasks
The following table lists examples of tasks involving the ReadFields method.
To See
Read from a delimited file How to: Read From Comma-Delimited Text Files in Visual Basic
Read from a fixed-width file How to: Read From Fixed-width Text Files in Visual Basic
Example
This example uses the ReadFields method to read from the file ParserText.txt and write the fields to Testfile.txt.
VB
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
For Each currentField As String In currentRow
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", currentField, True)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permissions are required:
Permission Description
FileIOPermission Associated enumeration: Unrestricted.
For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
TextFieldParser Object
TextFieldParser.TextFieldType Property
TextFieldParser.FieldWidths Property
TextFieldParser.Delimiters Property
TextFieldParser.ReadLine Method
Microsoft.VisualBasic.FileIO.TextFieldParser.ReadFields
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference
TextFieldParser.ReadLine Method
Returns the current line as a string and advances the cursor to the next line.
' Usage
Dim value As String = TextFieldParserObject.ReadLine()
' Declaration
Public Function ReadLine() As String
Return Value
String
Exceptions
The following condition may cause an exception to be thrown:
Target file does not exist (FileNotFoundException).
Remarks
The ReadLine method performs no parsing; an end-of-line character within a delimited field is interpreted as the actual end of
the line.
Nothing is returned if the end of the file is reached.
Example
This example reads through the file ParserText.txt and writes it to Testfile.txt.
VB
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadLine()
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", currentRow, True)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
TextFieldParser.ReadToEnd Method
Reads the remainder of the text file and returns it as a string.
' Usage
Dim value As String = TextFieldParserObject.ReadToEnd()
' Declaration
Public Function ReadToEnd() As String
Return Value
String.
Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
If there is nothing more to read because the end of the file has been reached, Nothing is returned.
The ReadToEnd method does not ignore blank lines and comments.
Example
This example uses the ReadToEnd method to read the entire file ParserText.txt and write it to the file Testfile.txt.
VB
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
Dim allText As String = FileReader.ReadToEnd
My.Computer.FileSystem.WriteAllText("C://testfile.txt", allText, True)
End Using
TextFieldParser.SetDelimiters Method
Sets the delimiters for the reader to the specified values, and sets the field type to Delimited.
' Usage
TextFieldParserObject.SetDelimiters(delimiters)
' Declaration
Public Sub SetDelimiters( _
ByVal delimiters As String() _
)
Parameters
delimiters
Array of type String.
Exceptions
The following condition may cause an exception to be thrown.
A delimiter is zero-length (ArgumentException).
Remarks
The existing contents of the Delimiters property are cleared when this method is set.
This method provides a way to set delimiters without creating an array.
Tasks
The following table lists an example of a task involving the SetDelimiters method.
To See
Parse a text file Parsing Text Files with the TextFieldParser Object
Example
This example opens a text field parser and defines the delimiter as vbTab.
VB
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\logs\test.log")
FileReader.SetDelimiters(vbTab)
End Using
Replace the path C:\logs\test.log with the path and name of the file you wish to parse.
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
Reference
TextFieldParser Object
TextFieldParser.SetFieldWidths Method
SetDelimiters
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference
TextFieldParser.SetFieldWidths Method
Sets the delimiters for the reader to the specified values and the field type to FixedWidth.
' Usage
TextFieldParserObject.SetFieldWidths(fieldWidths)
' Declaration
Public Sub SetFieldWidths( _
ByVal fieldWidths As Integer() _
)
Parameters
fieldWidths
Array of Integer.
Exceptions
The following condition may cause an exception to be thrown:
A delimiter is not an integer (ArgumentException).
Remarks
The existing contents of the Delimiters property are cleared when this is set.
This method provides a way to set delimiters without creating an array.
Tasks
The following table lists example of tasks involving the SetFieldWidths method.
To See
Parse a text file. Parsing Text Files with the TextFieldParser Object
Example
This example opens a text-field parser and defines the field width as 5.
VB
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\logs\test.log")
FileReader.SetFieldWidths(5)
End Using
Replace the path C:\logs\test.log with the path and name of the file you wish to parse.
The following example opens a text-field parser and defines the field widths as 5, 10, and variable.
VB
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\logs\test.log")
MyReader.SetFieldWidths(5, 10, -1)
End Using
Replace the path C:\logs\test.log with the path and name of the file you wish to parse.
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
TextFieldParser Object
TextFieldParser.SetDelimiters Method
SetFieldWidths
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference
TextFieldParser.TextFieldType Property
Indicates whether the file to be parsed is delimited or fixed-width.
' Usage
Dim value As FieldType = TextFieldParserObject.TextFieldType
' Declaration
Public Property TextFieldType As FieldType
Return Value
TextFieldType.
Remarks
The default value of this property is delimited.
Tasks
The following table lists examples of tasks involving the TextFieldType property.
To See
Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic
Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic
Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats in Visual Basic
Example
This example creates a TextFieldParser, FileReader, and specifies that it is delimited.
VB
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
FileReader.TextFieldType = _
Microsoft.VisualBasic.FileIO.FieldType.Delimited
FileReader.SetDelimiters(",")
End Using
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser Object
FieldType Enumeration
FieldType Enumeration
TextFieldParser
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference
TextFieldParser.TrimWhiteSpace Property
Indicates whether leading and trailing white space should be trimmed from field values.
' Usage
Dim value As Boolean = TextFieldParserObject.TrimWhiteSpace
' Declaration
Public Property TrimWhiteSpace As Boolean
Return Value
Boolean.
Remarks
The default value for this property is True.
Example
This example creates a TextFieldParser, FileReader, and sets the TrimWhiteSpace property to True.
VB
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
FileReader.TextFieldType = _
Microsoft.VisualBasic.FileIO.FieldType.Delimited
FileReader.SetDelimiters(",")
FileReader.TrimWhiteSpace = True
End Using
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
TextFieldParser Object
My.Computer.FileSystem.OpenTextFieldParser Method
Microsoft.VisualBasic.FileIO.TextFieldParser.TrimWhiteSpace
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference
Dim n1 As Integer = 96 / 8 / 4
Dim n2 As Integer = (96 / 8) / 4
Dim n3 As Integer = 96 / (8 / 4)
The first expression evaluates the division 96 / 8 (resulting in 12) and then the division 12 / 4, resulting in 3. Because the
compiler evaluates the operations for n1 from left to right, the evaluation is exactly the same when that order is explicitly
indicated for n2. Both n1 and n2 have a result of 3. By contrast, n3 has a result of 48, because the parentheses force the compiler
to evaluate 8 / 4 first.
Because of this behavior, operators are said to be left associative in Visual Basic.
Overriding Precedence and Associativity
You can use parentheses to force some parts of an expression to be evaluated before others. This can override both the order
of precedence and the left associativity. Visual Basic always performs operations within parentheses before those outside.
Within parentheses, however, it maintains normal precedence and associativity, unless you use parentheses within the
parentheses. The following example illustrates this.
Dim a, b, c, d, e, f, g As Double
a = 8.0
b = 3.0
c = 4.0
d = 2.0
e = 1.0
f = a - b + c / d * e
' The preceding line sets f to 7.0. Because of natural operator
' precedence and associativity, it is exactly equivalent to the
' following line.
f = (a - b) + ((c / d) * e)
' The following line overrides the natural operator precedence
' and left associativity.
g = (a - (b + c)) / (d * e)
' The preceding line sets g to 0.5.
See Also
Reference
= Operator (Visual Basic)
Is Operator (Visual Basic)
IsNot Operator
Like Operator
TypeOf Operator (Visual Basic)
Operators Listed by Functionality
Concepts
Operators and Expressions in Visual Basic
Visual Basic Language Reference
Bit Shift Operators These operators perform arithmetic shifts on bit patterns.
Parts
result
Required. Any String or Object variable.
expression1
Required. Any expression with a data type that widens to String.
expression2
Required. Any expression with a data type that widens to String.
Remarks
If the data type of expression1 or expression2 is not String but widens to String, it is converted to String. If either of the data
types does not widen to String, the compiler generates an error.
The data type of result is String. If one or both expressions evaluate to Nothing or have a value of System.DBNull.Value, they
are treated as a string with a value of "".
Note
The & operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefine
d behavior. For more information, see Operator Procedures.
Example
This example uses the & operator to force string concatenation. The result is a string value representing the concatenation of
the two string operands.
VB
Dim sampleStr As String
sampleStr = "Hello" & " World"
' The preceding statement sets sampleStr to "Hello World".
See Also
Reference
&= Operator (Visual Basic)
Concatenation Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Concatenation Operators in Visual Basic
Visual Basic Language Reference
number1 * number2
Parts
number1
Required. Any numeric expression.
number2
Required. Any numeric expression.
Result
The result is the product of number1 and number2.
Supported Types
All numeric types, including the unsigned and floating-point types and Decimal.
Remarks
The data type of the result depends on the types of the operands. The following table shows how the data type of the result is
determined.
Operand data types Result data type
Both expressions are integral data types (SByte, Byte, Short, A numeric data type appropriate for the data types of number1 an
UShort, Integer, UInteger, Long, ULong) d number2. See the "Integer Arithmetic" tables in
Data Types of Operator Results.
See Also
Reference
*= Operator (Visual Basic)
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference
variableorproperty *= expression
Parts
variableorproperty
Required. Any numeric variable or property.
expression
Required. Any numeric expression.
Remarks
The element on the left side of the *= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The *= operator assigns the value on its right to the variable or
property on its left.
Overloading
The * Operator (Visual Basic) can be overloaded, which means that a class or structure can redefine its behavior when an
operand has the type of that class or structure. Overloading the * operator affects the behavior of the *= operator. If your code
uses *= on a class or structure that overloads *, be sure you understand its redefined behavior. For more information, see
Operator Procedures.
Example
The following example uses the *= operator to multiply one Integer variable by a second and assign the result to the first
variable.
VB
Dim var1 As Integer = 10
Dim var2 As Integer = 3
var1 *= var2
' The value of var1 is now 30.
See Also
Reference
* Operator (Visual Basic)
Assignment Operators
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference
expression1 + expression2
- or -
+ expression1
Parts
expression1
Required. Any numeric or string expression.
expression2
Required unless the + operator is calculating a negative value. Any numeric or string expression.
Result
If expression1 and expression2 are both numeric, the result is their arithmetic sum.
If expression2 is absent, the + operator is the unary identity operator for the unchanged value of an expression. In this sense,
the operation consists of retaining the sign of expression1, so the result is negative if expression1 is negative.
If expression1 and expression2 are both strings, the result is the concatenation of their values.
If expression1 and expression2 are of mixed types, the action taken depends on their types, their contents, and the setting of the
Option Strict Statement. For more information, see the tables in "Remarks."
Supported Types
All numeric types, including the unsigned and floating-point types and Decimal, and String.
Remarks
In general, + performs arithmetic addition when possible, and concatenates only when both expressions are strings.
If neither expression is an Object, Visual Basic takes the following actions.
Data types of expressions Action by compiler
Both expressions are numeric data types (SByte, Byte, Add. The result data type is a numeric type appropriate for the data typ
Short, UShort, Integer, UInteger, Long, ULong, Dec es of expression1 and expression2. See the "Integer Arithmetic" tables i
imal, Single, or Double) n Data Types of Operator Results.
One expression is a numeric data type and the other is If Option Strict is On, then generate a compiler error.
a string
If Option Strict is Off, then implicitly convert the String to Double an
d add.
If the String cannot be converted to Double, then throw an
InvalidCastException exception.
One expression is a numeric data type, and the other is Add, with Nothing valued as zero.
Nothing (Visual Basic)
One expression is a string, and the other is Nothing Concatenate, with Nothing valued as "".
If one expression is an Object expression, Visual Basic takes the following actions.
Data types of expressions Action by compiler
Object expression holds a numeric value and the othe If Option Strict is On, then generate a compiler error.
r is a numeric data type
If Option Strict is Off, then add.
Object expression holds a numeric value and the othe If Option Strict is On, then generate a compiler error.
r is of type String
If Option Strict is Off, then implicitly convert the String to Double an
d add.
If the String cannot be converted to Double, then throw an InvalidCa
stException exception.
Object expression holds a string and the other is a nu If Option Strict is On, then generate a compiler error.
meric data type
If Option Strict is Off, then implicitly convert the string Object to Dou
ble and add.
If the string Object cannot be converted to Double, then throw an Inv
alidCastException exception.
Object expression holds a string and the other is of ty If Option Strict is On, then generate a compiler error.
pe String
If Option Strict is Off, then implicitly convert Object to String and co
ncatenate.
If both expressions are Object expressions, Visual Basic takes the following actions (Option Strict Off only).
Data types of expressions Action by compiler
Both Object expressions hold numeric values Add.
One Object expression holds a numeric value and Implicitly convert the string Object to Double and add.
the other holds a string
If the string Object cannot be converted to a numeric value, then throw an
InvalidCastException exception.
If either Object expression evaluates to Nothing or DBNull, the + operator treats it as a String with a value of "".
Note
When you use the + operator, you might not be able to determine whether addition or string concatenation will occur. Use t
he & operator for concatenation to eliminate ambiguity and to provide self-documenting code.
Overloading
The + operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefined
behavior. For more information, see Operator Procedures.
Example
The following example uses the + operator to add numbers. If the operands are both numeric, Visual Basic computes the
arithmetic result. The arithmetic result represents the sum of the two operands.
VB
Dim sumNumber As Integer
sumNumber = 2 + 2
sumNumber = 4257.04 + 98112
' The preceding statements set sumNumber to 4 and 102369.
You can also use the + operator to concatenate strings. If the operands are both strings, Visual Basic concatenates them. The
concatenation result represents a single string consisting of the contents of the two operands one after the other.
If the operands are of mixed types, the result depends on the setting of the Option Strict Statement. The following example
illustrates the result when Option Strict is On.
VB
Option Strict On
VB
Dim var1 As String = "34"
Dim var2 As Integer = 6
Dim concatenatedNumber As Integer = var1 + var2
... ' The preceding statement generates a COMPILER ERROR.
The following example illustrates the result when Option Strict is Off.
VB
Option Strict Off
VB
Dim var1 As String = "34"
Dim var2 As Integer = 6
Dim concatenatedNumber As Integer = var1 + var2
... ' The preceding statement returns 40 after the string in var1 is
' converted to a numeric value. This might be an unexpected result.
' We do not recommend use of Option Strict Off for these operations.
To eliminate ambiguity, you should use the & operator instead of + for concatenation.
See Also
Reference
& Operator (Visual Basic)
Concatenation Operators (Visual Basic)
Arithmetic Operators (Visual Basic)
Operators Listed by Functionality
Operator Precedence in Visual Basic
Option Strict Statement
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference
variableorproperty += expression
Parts
variableorproperty
Required. Any numeric or String variable or property.
expression
Required. Any numeric or String expression.
Remarks
The element on the left side of the += operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The += operator assigns the value on its right to the variable or
property on its left.
This assignment operator implicitly performs widening but not narrowing conversions if the compilation environment
enforces strict semantics. For more information on these conversions, see Widening and Narrowing Conversions. For more
information on strict and permissive semantics, see Option Strict Statement.
If permissive semantics are allowed, the += operator implicitly performs a variety of string and numeric conversions identical
to those performed by the + operator. For details on these conversions, see + Operator (Visual Basic).
Note
When you use the += operator, you might not be able to determine whether addition or string concatenation will occur. Use
the &= operator for concatenation to eliminate ambiguity and to provide self-documenting code.
Overloading
The + operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. Overloading the + operator affects the behavior of the += operator. If your code uses += on a
class or structure that overloads +, be sure you understand its redefined behavior. For more information, see
Operator Procedures.
Example
The following example uses the += operator to combine the value of one variable with another. The first part uses += with
numeric variables to add one value to another. The second part uses += with String variables to concatenate one value with
another. In both cases, the result is assigned to the first variable.
VB
' This part uses numeric variables.
Dim num1 As Integer = 10
Dim num2 As Integer = 3
num1 += num2
VB
' This part uses string variables.
Dim str1 As String = "10"
Dim str2 As String = "3"
str1 += str2
The value of num1 is now 13, and the value of str1 is now "103".
See Also
Reference
+ Operator (Visual Basic)
Assignment Operators
Arithmetic Operators (Visual Basic)
Concatenation Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference
variableorproperty = value
Parts
variableorproperty
Any writable variable or any property.
value
Any literal, constant, or expression.
Remarks
The element on the left side of the equal sign (=) can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The = operator assigns the value on its right to the variable or property
on its left.
Note
The = operator is also used as a comparison operator. For details, see Comparison Operators (Visual Basic).
Overloading
The = operator can be overloaded only as a relational comparison operator, not as an assignment operator. For more
information, see Operator Procedures.
Example
The following example demonstrates the assignment operator. The value on the right is assigned to the variable on the left.
VB
Dim testInt As Integer
Dim testString As String
Dim testButton As System.Windows.Forms.Button
Dim testObject As Object
testInt = 42
testString = "This is an example of a string literal."
testButton = New System.Windows.Forms.Button()
testObject = testInt
testObject = testString
testObject = testButton
See Also
Reference
&= Operator (Visual Basic)
*= Operator (Visual Basic)
+= Operator (Visual Basic)
-= Operator (Visual Basic)
/= Operator (Visual Basic)
\= Operator
^= Operator (Visual Basic)
Comparison Operators (Visual Basic)
ReadOnly (Visual Basic)
Concepts
Assignment Statements
Visual Basic Language Reference
expression1 – expression2
- or -
– expression1
Parts
expression1
Required. Any numeric expression.
expression2
Required unless the – operator is calculating a negative value. Any numeric expression.
Result
The result is the difference between expression1 and expression2, or the negated value of expression1.
The result data type is a numeric type appropriate for the data types of expression1 and expression2. See the "Integer
Arithmetic" tables in Data Types of Operator Results.
Supported Types
All numeric types, including the unsigned and floating-point types and Decimal.
Remarks
In the first usage shown in the preceding syntax, the – operator is the binary arithmetic subtraction operator for the difference
between two numeric expressions.
In the second usage shown in the preceding syntax, the – operator is the unary negation operator for the negative value of an
expression. In this sense, the negation consists of reversing the sign of expression1, so the result is positive if expression1 is
negative.
If either expression evaluates to Nothing, the – operator treats it as zero.
Note
The – operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the t
ype of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefine
d behavior. For more information, see Operator Procedures.
Example
The following example uses the – operator to calculate and return the difference between two numbers, and then to negate a
number.
VB
Dim binaryResult As Double = 459.35 - 334.9
Dim unaryResult As Double = -334.9
Following the execution of these statements, binaryResult contains 124.45 and unaryResult contains –334.90.
See Also
Reference
-= Operator (Visual Basic)
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference
variableorproperty -= expression
Parts
variableorproperty
Required. Any numeric variable or property.
expression
Required. Any numeric expression.
Remarks
The element on the left side of the -= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The -= operator assigns the value on its right to the variable or
property on its left.
Overloading
The - Operator (Visual Basic) can be overloaded, which means that a class or structure can redefine its behavior when an
operand has the type of that class or structure. Overloading the - operator affects the behavior of the -= operator. If your code
uses -= on a class or structure that overloads -, be sure you understand its redefined behavior. For more information, see
Operator Procedures.
Example
The following example uses the -= operator to subtract one Integer variable from another and assign the result to the latter
variable.
VB
Dim var1 As Integer = 10
Dim var2 As Integer = 3
var1 -= var2
' The value of var1 is now 7.
See Also
Reference
- Operator (Visual Basic)
Assignment Operators
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference
Parts
result
Required. Integral numeric value. The result of shifting the bit pattern. The data type is the same as that of pattern.
pattern
Required. Integral numeric expression. The bit pattern to be shifted. The data type must be an integral type (SByte, Byte,
Short, UShort, Integer, UInteger, Long, or ULong).
amount
Required. Numeric expression. The number of bits to shift the bit pattern. The data type must be Integer or widen to
Integer.
Remarks
Arithmetic shifts are not circular, which means the bits shifted off one end of the result are not reintroduced at the other end. In
an arithmetic left shift, the bits shifted beyond the range of the result data type are discarded, and the bit positions vacated on
the right are set to zero.
To prevent shifting by more bits than the result can hold, Visual Basic masks the value of amount with a size mask
corresponding to the data type of pattern. The binary AND of these values is used for the shift amount. The size masks are as
follows:
Data type of pattern Size mask (decimal) Size mask (hexadecimal)
SByte, Byte 7 &H00000007
If amount is zero, the value of result is identical to the value of pattern. If amount is negative, it is taken as an unsigned value
and masked with the appropriate size mask.
Arithmetic shifts never generate overflow exceptions.
Note
The << operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has th
e type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefi
ned behavior. For more information, see Operator Procedures.
Example
The following example uses the << operator to perform arithmetic left shifts on integral values. The result always has the same
data type as that of the expression being shifted.
VB
Dim pattern As Short = 192
' The bit pattern is 0000 0000 1100 0000.
Dim result1, result2, result3, result4, result5 As Short
result1 = pattern << 0
result2 = pattern << 4
result3 = pattern << 9
result4 = pattern << 17
result5 = pattern << -1
The shift amount for result4 is calculated as 17 AND 15, which equals 1.
See Also
Reference
Bit Shift Operators
Assignment Operators
<<= Operator (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference
Parts
variableorproperty
Required. Variable or property of an integral type (SByte, Byte, Short, UShort, Integer, UInteger, Long, or ULong).
amount
Required. Numeric expression of a data type that widens to Integer.
Remarks
The element on the left side of the <<= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The <<= operator assigns the value on its right to the variable or
property on its left.
Arithmetic shifts are not circular, which means the bits shifted off one end of the result are not reintroduced at the other end. In
an arithmetic left shift, the bits shifted beyond the range of the result data type are discarded, and the bit positions vacated on
the right are set to zero.
Overloading
The << Operator (Visual Basic) can be overloaded, which means that a class or structure can redefine its behavior when an
operand has the type of that class or structure. Overloading the << operator affects the behavior of the <<= operator. If your
code uses <<= on a class or structure that overloads <<, be sure you understand its redefined behavior. For more information,
see Operator Procedures.
Example
The following example uses the <<= operator to shift the bit pattern of an Integer variable left by the specified amount and
assign the result to the variable.
VB
Dim var As Integer = 10
Dim shift As Integer = 3
var <<= shift
' The value of var is now 80.
See Also
Reference
<< Operator (Visual Basic)
Assignment Operators
Bit Shift Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference
Parts
result
Required. Integral numeric value. The result of shifting the bit pattern. The data type is the same as that of pattern.
pattern
Required. Integral numeric expression. The bit pattern to be shifted. The data type must be an integral type (SByte, Byte,
Short, UShort, Integer, UInteger, Long, or ULong).
amount
Required. Numeric expression. The number of bits to shift the bit pattern. The data type must be Integer or widen to
Integer.
Remarks
Arithmetic shifts are not circular, which means the bits shifted off one end of the result are not reintroduced at the other end. In
an arithmetic right shift, the bits shifted beyond the rightmost bit position are discarded, and the leftmost (sign) bit is
propagated into the bit positions vacated at the left. This means that if pattern has a negative value, the vacated positions are
set to one; otherwise they are set to zero.
Note that the data types Byte, UShort, UInteger, and ULong are unsigned, so there is no sign bit to propagate. If pattern is of
any unsigned type, the vacated positions are always set to zero.
To prevent shifting by more bits than the result can hold, Visual Basic masks the value of amount with a size mask
corresponding to the data type of pattern. The binary AND of these values is used for the shift amount. The size masks are as
follows:
Data type of pattern Size mask (decimal) Size mask (hexadecimal)
SByte, Byte 7 &H00000007
If amount is zero, the value of result is identical to the value of pattern. If amount is negative, it is taken as an unsigned value
and masked with the appropriate size mask.
Arithmetic shifts never generate overflow exceptions.
Overloading
The >> operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefined
behavior. For more information, see Operator Procedures.
Example
The following example uses the >> operator to perform arithmetic right shifts on integral values. The result always has the
same data type as that of the expression being shifted.
VB
Dim pattern As Short = 2560
' The bit pattern is 0000 1010 0000 0000.
Dim result1, result2, result3, result4, result5 As Short
result1 = pattern >> 0
result2 = pattern >> 4
result3 = pattern >> 10
result4 = pattern >> 18
result5 = pattern >> -1
The shift amount for result4 is calculated as 18 AND 15, which equals 2.
The following example shows arithmetic shifts on a negative value.
VB
Dim negPattern As Short = -8192
' The bit pattern is 1110 0000 0000 0000.
Dim negResult1, negResult2 As Short
negResult1 = negPattern >> 4
negResult2 = negPattern >> 13
See Also
Reference
Bit Shift Operators
Assignment Operators
>>= Operator (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference
Parts
variableorproperty
Required. Variable or property of an integral type (SByte, Byte, Short, UShort, Integer, UInteger, Long, or ULong).
amount
Required. Numeric expression of a data type that widens to Integer.
Remarks
The element on the left side of the >>= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The >>= operator assigns the value on its right to the variable or
property on its left.
Arithmetic shifts are not circular, which means the bits shifted off one end of the result are not reintroduced at the other end. In
an arithmetic right shift, the bits shifted beyond the rightmost bit position are discarded, and the leftmost bit is propagated into
the bit positions vacated at the left. This means that if variableorproperty has a negative value, the vacated positions are set to
one. If variableorproperty is positive, or if its data type is an unsigned type, the vacated positions are set to zero.
Overloading
The >> Operator (Visual Basic) can be overloaded, which means that a class or structure can redefine its behavior when an
operand has the type of that class or structure. Overloading the >> operator affects the behavior of the >>= operator. If your
code uses >>= on a class or structure that overloads >>, be sure you understand its redefined behavior. For more information,
see Operator Procedures.
Example
The following example uses the >>= operator to shift the bit pattern of an Integer variable right by the specified amount and
assign the result to the variable.
VB
Dim var As Integer = 10
Dim shift As Integer = 2
var >>= shift
' The value of var is now 2 (one bit was lost off the right end).
See Also
Reference
>> Operator (Visual Basic)
Assignment Operators
Bit Shift Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference
expression1 / expression2
Parts
expression1
Required. Any numeric expression.
expression2
Required. Any numeric expression.
Supported Types
All numeric types, including the unsigned and floating-point types and Decimal.
Result
The result is the full quotient of expression1 divided by expression2, including any remainder.
The \ Operator returns the integer quotient, which drops the remainder.
Remarks
The data type of the result depends on the types of the operands. The following table shows how the data type of the result is
determined.
Operand data types Result data typ
e
Both expressions are integral data types (SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong) Double
Both expressions are of the Single Data Type (Visual Basic) Single
Either expression is a floating-point data type (Single Data Type (Visual Basic) or Double
Double Data Type (Visual Basic))
Before division is performed, any integral numeric expressions are widened to Double. If you assign the result to an integral
data type, Visual Basic attempts to convert the result from Double to that type. This can throw an exception if the result does
not fit in that type. In particular, see "Attempted Division by Zero" on this Help page.
If expression1 or expression2 evaluates to Nothing, it is treated as zero.
Attempted Division by Zero
If expression2 evaluates to zero, the / operator behaves differently for different operand data types. The following table shows
the possible behaviors.
Operand data types Behavior if expression2 is zero
Floating-point (Single Returns infinity (PositiveInfinity or NegativeInfinity), or NaN (not a number) if expression1 is also zero
or Double)
Integral (signed or uns Attempted conversion back to integral type throws OverflowException because integral types cannot a
igned) ccept PositiveInfinity, NegativeInfinity, or NaN
Note
The / operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the t
ype of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefine
d behavior. For more information, see Operator Procedures.
Example
This example uses the / operator to perform floating-point division. The result is the quotient of the two operands.
VB
Dim resultValue As Double
resultValue = 10 / 4
resultValue = 10 / 3
The expressions in the preceding example return values of 2.5 and 3.333333. Note that the result is always floating-point
(Double), even though both operands are integer constants.
See Also
Reference
/= Operator (Visual Basic)
\ Operator
Data Types of Operator Results
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference
variableorproperty /= expression
Parts
variableorproperty
Required. Any numeric variable or property.
expression
Required. Any numeric expression.
Remarks
The element on the left side of the /= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The /= operator assigns the value on its right to the variable or
property on its left.
This statement assigns a Double value to the variable or property on the left hand side. If Option Strict is On,
variableorproperty must be a Double. If Option Strict is Off, Visual Basic performs an implicit conversion and assigns the
resulting value to variableorproperty, with a possible error at run time. For more information, see
Widening and Narrowing Conversions and Option Strict Statement.
Overloading
The / Operator (Visual Basic) can be overloaded, which means that a class or structure can redefine its behavior when an
operand has the type of that class or structure. Overloading the / operator affects the behavior of the /= operator. If your code
uses /= on a class or structure that overloads /, be sure you understand its redefined behavior. For more information, see
Operator Procedures.
Example
The following example uses the /= operator to divide one Integer variable by a second and assign the quotient to the first
variable.
VB
Dim var1 As Integer = 12
Dim var2 As Integer = 3
var1 /= var2
' The value of var1 is now 4.
See Also
Reference
/ Operator (Visual Basic)
\= Operator
Assignment Operators
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference
\ Operator
Divides two numbers and returns an integer result.
expression1 \ expression2
Parts
expression1
Required. Any numeric expression.
expression2
Required. Any numeric expression.
Supported Types
All numeric types, including the unsigned and floating-point types and Decimal.
Result
The result is the integer quotient of expression1 divided by expression2, which discards any remainder and retains only the
integer portion. This is known as truncation.
The result data type is a numeric type appropriate for the data types of expression1 and expression2. See the "Integer
Arithmetic" tables in Data Types of Operator Results.
The / Operator (Visual Basic) returns the full quotient, which retains the remainder in the fractional portion.
Remarks
Before performing the division, Visual Basic attempts to convert any floating-point numeric expression to Long. If Option
Strict is On, a compiler error results. If Option Strict is Off, an OverflowException is possible if the value is outside the range
of the Long Data Type (Visual Basic). The conversion to Long is also subject to banker's rounding. For more information, see
"Fractional Parts" in Type Conversion Functions.
If expression1 or expression2 evaluates to Nothing, it is treated as zero.
Attempted Division by Zero
If expression2 evaluates to zero, the \ operator throws a DivideByZeroException exception. This is true for all numeric data
types of the operands.
Note
The \ operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the t
ype of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefine
d behavior. For more information, see Operator Procedures.
Example
The following example uses the \ operator to perform integer division. The result is an integer representing the integer
quotient of the two operands, with the remainder discarded.
VB
Dim resultValue As Integer
resultValue = 11 \ 4
resultValue = 9 \ 3
resultValue = 100 \ 3
resultValue = 67 \ -3
The expressions in the preceding example return values of 2, 3, 33, and -22, respectively.
See Also
Reference
\= Operator
/ Operator (Visual Basic)
Option Strict Statement
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference
\= Operator
Divides the value of a variable or property by the value of an expression and assigns the integer result to the variable or
property.
variableorproperty \= expression
Parts
variableorproperty
Required. Any numeric variable or property.
expression
Required. Any numeric expression.
Remarks
The element on the left side of the \= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The \= operator assigns the value on its right to the variable or
property on its left.
For further information on integer division, see \ Operator.
Overloading
The \ operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. Overloading the \ operator affects the behavior of the \= operator. If your code uses \= on a
class or structure that overloads \, be sure you understand its redefined behavior. For more information, see
Operator Procedures.
Example
The following example uses the \= operator to divide one Integer variable by a second and assign the integer result to the first
variable.
VB
Dim var1 As Integer = 10
Dim var2 As Integer = 3
var1 \= var2
' The value of var1 is now 3.
See Also
Reference
\ Operator
/= Operator (Visual Basic)
Assignment Operators
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference
number ^ exponent
Parts
number
Required. Any numeric expression.
exponent
Required. Any numeric expression.
Result
The result is number raised to the power of exponent, always as a Double value.
Supported Types
Double. Operands of any different type are converted to Double.
Remarks
Visual Basic always performs exponentiation in the Double Data Type (Visual Basic).
The value of exponent can be fractional, negative, or both.
When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from
left to right.
Note
The ^ operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the t
ype of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefine
d behavior. For more information, see Operator Procedures.
Example
The following example uses the ^ operator to raise a number to the power of an exponent. The result is the first operand raised
to the power of the second.
VB
Dim exp1, exp2, exp3, exp4, exp5, exp6 As Double
exp1 = 2 ^ 2
exp2 = 3 ^ 3 ^ 3
exp3 = (-5) ^ 3
exp4 = (-5) ^ 4
exp5 = 8 ^ (1.0 / 3.0)
exp6 = 8 ^ (-1.0 / 3.0)
exp6 = 8 ^ -1.0 / 3.0 would be calculated as (8 to the –1 power, or 0.125) divided by 3.0, which would result in
0.041666666666666666666666666666667.
See Also
Reference
^= Operator (Visual Basic)
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference
variableorproperty ^= expression
Parts
variableorproperty
Required. Any numeric variable or property.
expression
Required. Any numeric expression.
Remarks
The element on the left side of the ^= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The ^= operator assigns the value on its right to the variable or
property on its left.
Visual Basic always performs exponentiation in the Double Data Type (Visual Basic). Operands of any different type are
converted to Double, and the result is always Double.
The value of expression can be fractional, negative, or both.
Overloading
The ^ Operator (Visual Basic) can be overloaded, which means that a class or structure can redefine its behavior when an
operand has the type of that class or structure. Overloading the ^ operator affects the behavior of the ^= operator. If your
code uses ^= on a class or structure that overloads ^, be sure you understand its redefined behavior. For more information,
see Operator Procedures.
Example
The following example uses the ^= operator to raise the value of one Integer variable to the power of a second variable and
assign the result to the first variable.
VB
Dim var1 As Integer = 10
Dim var2 As Integer = 3
var1 ^= var2
' The value of var1 is now 1000.
See Also
Reference
^ Operator (Visual Basic)
Assignment Operators
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference
AddressOf Operator
Creates a procedure delegate instance that references the specific procedure.
AddressOf procedurename
Parts
procedurename
Required. Specifies the procedure to be referenced by the newly created procedure delegate.
Remarks
The AddressOf operator creates a function delegate that points to the function specified by procedurename. When the
specified procedure is an instance method then the function delegate refers to both the instance and the method. Then, when
the function delegate is invoked the specified method of the specified instance is called.
The AddressOf operator can be used as the operand of a delegate constructor or it can be used in a context in which the type
of the delegate can be determined by the compiler.
Example
This example uses the AddressOf operator to designate a delegate to handle the Click event of a button.
VB
' Add the following line to Sub Form1_Load().
AddHandler Button1.Click, AddressOf Button1_Click
The following example uses the AddressOf operator to designate the startup function for a thread.
VB
Public Sub CountSheep()
Dim i As Integer = 1 ' Sheep do not count from 0.
Do While (True) ' Endless loop.
Console.WriteLine("Sheep " & i & " Baah")
i = i + 1
System.Threading.Thread.Sleep(1000) 'Wait 1 second.
Loop
End Sub
Sub UseThread()
Dim t As New System.Threading.Thread(AddressOf CountSheep)
t.Start()
End Sub
See Also
Reference
Declare Statement
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Concepts
Delegates and the AddressOf Operator
Visual Basic Language Reference
Parts
result
Required. Any Boolean or numeric expression. For Boolean comparison, result is the logical conjunction of two Boolean
values. For bitwise operations, result is a numeric value representing the bitwise conjunction of two numeric bit patterns.
expression1
Required. Any Boolean or numeric expression.
expression2
Required. Any Boolean or numeric expression.
Remarks
For Boolean comparison, result is True if and only if both expression1 and expression2 evaluate to True. The following table
illustrates how result is determined.
If expression1 is And expression2 is The value of result is
True True True
When applied to numeric values, the And operator performs a bitwise comparison of identically positioned bits in two numeric
expressions and sets the corresponding bit in result according to the following table.
If bit in expression1 is And bit in expression2 is The bit in result is
1 1 1
1 0 0
0 1 0
0 0 0
Note
Since the logical and bitwise operators have a lower precedence than other arithmetic and relational operators, any bitwise o
perations should be enclosed in parentheses to ensure accurate results.
Data Types
If the operands consist of one Boolean expression and one numeric expression, Visual Basic converts the Boolean expression
to a numeric value (–1 for True and 0 for False) and performs a bitwise operation.
For a Boolean comparison, the data type of the result is Boolean. For a bitwise comparison, the result data type is a numeric
type appropriate for the data types of expression1 and expression2. See the "Relational and Bitwise Comparisons" table in
Data Types of Operator Results.
Note
The And operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has t
he type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redef
ined behavior. For more information, see Operator Procedures.
Example
The following example uses the And operator to perform a logical conjunction on two expressions. The result is a Boolean
value that represents whether both of the expressions are True.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck As Boolean
firstCheck = a > b And b > c
secondCheck = b > a And b > c
AndAlso Operator
Performs short-circuiting logical conjunction on two expressions.
Parts
result
Required. Any Boolean expression. The result is the Boolean result of comparison of the two expressions.
expression1
Required. Any Boolean expression.
expression2
Required. Any Boolean expression.
Remarks
A logical operation is said to be short-circuiting if the compiled code can bypass the evaluation of one expression depending
on the result of another expression. If the result of the first expression evaluated determines the final result of the operation,
there is no need to evaluate the second expression, because it cannot change the final result. Short-circuiting can improve
performance if the bypassed expression is complex, or if it involves procedure calls.
If both expressions evaluate to True, result is True. The following table illustrates how result is determined.
If expression1 is And expression2 is The value of result is
True True True
One use of the AndAlso operator is to test for the existence of an object instance before attempting to access one of its
members. The following code line illustrates this.
If newObject AndAlso newObject.initFinished Then
The access to the initFinished property in the preceding code line could throw a NullReferenceException exception if the
newObject variable did not have an object instance assigned to it. However, the AndAlso operator causes the compiler to
bypass the access to initFinished if newObject is Nothing, because Nothing evaluates to False.
Data Types
The AndAlso operator is defined only for the Boolean Data Type (Visual Basic). Visual Basic converts each operand as
necessary to Boolean and performs the operation entirely in Boolean. If you assign the result to a numeric type, Visual Basic
converts it from Boolean to that type. This could produce unexpected behavior. For example, 5 AndAlso 12 results in –1 when
converted to Integer.
Overloading
The And Operator (Visual Basic) and the IsFalse Operator can be overloaded, which means that a class or structure can redefine
their behavior when an operand has the type of that class or structure. Overloading the And and IsFalse operators affects the
behavior of the AndAlso operator. If your code uses AndAlso on a class or structure that overloads And and IsFalse, be sure
you understand their redefined behavior. For more information, see Operator Procedures.
Example
The following example uses the AndAlso operator to perform a logical conjunction on two expressions. The result is a
Boolean value that represents whether the entire conjoined expression is true. If the first expression is False, the second is not
evaluated.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck, thirdCheck As Boolean
firstCheck = a > b AndAlso b > c
secondCheck = b > a AndAlso b > c
thirdCheck = a > b AndAlso c > b
The preceding example produces results of True, False, and False, respectively. In the calculation of secondCheck, the second
expression is not evaluated because the first is already False. However, the second expression is evaluated in the calculation of
thirdCheck.
The following example shows a Function procedure that searches for a given value among the elements of an array. If the
array is empty, or if the array length has been exceeded, the While statement does not test the array element against the
search value.
VB
Public Function findValue(ByVal arr() As Double, _
ByVal searchValue As Double) As Double
Dim i As Integer = 0
While i <= UBound(arr) AndAlso arr(i) <> searchValue
' If i is greater than UBound(arr), searchValue is not checked.
i += 1
End While
If i > UBound(arr) Then i = -1
Return i
End Function
See Also
Reference
Logical/Bitwise Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
And Operator (Visual Basic)
IsFalse Operator
Concepts
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Reference
GetType Operator
Returns a Type object for the specified type. The Type object provides information about the type such as its properties,
methods, and events.
GetType(typename)
Parameters
typename
The name of the type for which you desire information.
Remarks
The GetType operator returns the Type object for the specified typename. You can pass the name of any defined type in
typename. This includes the following:
Any Visual Basic data type, such as Boolean or Date.
Any .NET Framework class, structure, module, or interface, such as System.ArgumentException or System.Double.
Any class, structure, module, or interface defined by your application.
Any array defined by your application.
Any delegate defined by your application.
Any enumeration defined by Visual Basic, the .NET Framework, or your application.
If you want to get the type object of an object variable, use the System.Type.GetType method.
The GetType operator can be useful in the following circumstances:
You need to access the metadata for a type at run time. The Type object supplies metadata such as type members and
deployment information. You need this, for example, to reflect over an assembly. For more information, see
System.Reflection.
You want to compare two object references to see if they refer to instances of the same type. If they do, GetType returns
references to the same Type object.
Example
The following examples show the GetType operator in use.
VB
' The following statement returns the Type object for Integer.
MsgBox(GetType(Integer).ToString())
' The following statement returns the Type object for one-dimensional string arrays.
MsgBox(GetType(String()).ToString())
See Also
Reference
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Operators and Expressions in Visual Basic
Visual Basic Language Reference
Parts
result
Required. Any Boolean value.
object1
Required. Any Object name.
object2
Required. Any Object name.
Remarks
The Is operator determines if two object references refer to the same object. However, it does not perform value comparisons.
If object1 and object2 both refer to the exact same object instance, result is True; if they do not, result is False.
Is can also be used with the TypeOf keyword to make a TypeOf...Is expression, which tests whether an object variable is
compatible with a data type.
Example
The following example uses the Is operator to compare pairs of object references. The results are assigned to a Boolean value
representing whether the two objects are identical.
VB
Dim myObject As New Object
Dim otherObject As New Object
Dim yourObject, thisObject, thatObject As Object
Dim myCheck As Boolean
yourObject = myObject
thisObject = myObject
thatObject = otherObject
' The following statement sets myCheck to True.
myCheck = yourObject Is thisObject
' The following statement sets myCheck to False.
myCheck = thatObject Is thisObject
' The following statement sets myCheck to False.
myCheck = myObject Is thatObject
thatObject = myObject
' The following statement sets myCheck to True.
myCheck = thisObject Is thatObject
As the preceding example demonstrates, you can use the Is operator to test both early bound and late bound objects.
See Also
Reference
TypeOf Operator (Visual Basic)
IsNot Operator
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Comparison Operators in Visual Basic
Operators and Expressions in Visual Basic
Visual Basic Language Reference
IsFalse Operator
Determines whether an expression is False.
You cannot call IsFalse explicitly in your code, but the Visual Basic compiler can use it to generate code from AndAlso clauses.
If you define a class or structure and then use a variable of that type in an AndAlso clause, you must define IsFalse on that
class or structure.
The compiler considers the IsFalse and IsTrue operators as a matched pair. This means that if you define one of them, you
must also define the other one.
Note
The IsFalse operator can be overloaded, which means that a class or structure can redefine its behavior when its operand ha
s the type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its re
defined behavior. For more information, see Operator Procedures.
Example
The following code example defines the outline of a structure that includes definitions for the IsFalse and IsTrue operators.
VB
Public Structure p
Dim a As Double
Public Shared Operator IsFalse(ByVal w As p) As Boolean
Dim b As Boolean
' Insert code to calculate IsFalse of w.
Return b
End Operator
Public Shared Operator IsTrue(ByVal w As p) As Boolean
Dim b As Boolean
' Insert code to calculate IsTrue of w.
Return b
End Operator
End Structure
See Also
Tasks
How to: Define an Operator
Reference
IsTrue Operator
AndAlso Operator
Visual Basic Language Reference
IsNot Operator
Compares two object reference variables.
Parts
result
Required. A Boolean value.
object1
Required. Any Object variable or expression.
object2
Required. Any Object variable or expression.
Remarks
The IsNot operator determines if two object references refer to different objects. However, it does not perform value
comparisons. If object1 and object2 both refer to the exact same object instance, result is False; if they do not, result is True.
IsNot is the opposite of the Is operator. The advantage of IsNot is that you can avoid awkward syntax with Not and Is, which
can be difficult to read.
You can use the Is and IsNot operators to test both early-bound and late-bound objects.
Example
The following code example uses both the Is operator and the IsNot operator to accomplish the same comparison.
VB
Dim o1, o2 As New Object
If Not o1 Is o2 Then MsgBox("o1 and o2 do not refer to the same instance.")
If o1 IsNot o2 Then MsgBox("o1 and o2 do not refer to the same instance.")
See Also
Tasks
How to: Test Whether Two Objects Are the Same
Reference
Is Operator (Visual Basic)
Operator Precedence in Visual Basic
Visual Basic Language Reference
IsTrue Operator
Determines whether an expression is True.
You cannot call IsTrue explicitly in your code, but the Visual Basic compiler can use it to generate code from OrElse clauses. If
you define a class or structure and then use a variable of that type in an OrElse clause, you must define IsTrue on that class or
structure.
The compiler considers the IsTrue and IsFalse operators as a matched pair. This means that if you define one of them, you
must also define the other one.
Compiler Use of IsTrue
When you have defined a class or structure, you can use a variable of that type in a For, If, Else If, or While statement, or in a
When clause. If you do this, the compiler requires an operator that converts your type into a Boolean value so it can test a
condition. It searches for a suitable operator in the following order:
1. A widening conversion operator from your class or structure to Boolean.
2. The IsTrue operator on your class or structure.
3. A narrowing conversion operator from your class or structure to Boolean.
If you have not defined any conversion to Boolean or an IsTrue operator, the compiler signals an error.
Note
The IsTrue operator can be overloaded, which means that a class or structure can redefine its behavior when its operand has
the type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its rede
fined behavior. For more information, see Operator Procedures.
Example
The following code example defines the outline of a structure that includes definitions for the IsFalse and IsTrue operators.
VB
Public Structure p
Dim a As Double
Public Shared Operator IsFalse(ByVal w As p) As Boolean
Dim b As Boolean
' Insert code to calculate IsFalse of w.
Return b
End Operator
Public Shared Operator IsTrue(ByVal w As p) As Boolean
Dim b As Boolean
' Insert code to calculate IsTrue of w.
Return b
End Operator
End Structure
See Also
Tasks
How to: Define an Operator
Reference
IsFalse Operator
OrElse Operator
Visual Basic Language Reference
Like Operator
Compares a string against a pattern.
Parts
result
Required. Any Boolean variable. The result is a Boolean value indicating whether or not the string satisfies the pattern.
string
Required. Any String expression.
pattern
Required. Any String expression conforming to the pattern-matching conventions described in "Remarks."
Remarks
If the value in string satisfies the pattern contained in pattern, result is True. If the string does not satisfy the pattern, result is
False. If both string and pattern are empty strings, the result is True.
Comparison Method
The behavior of the Like operator depends on the Option Compare Statement. The default string comparison method for each
source file is Option Compare Binary.
Pattern Options
Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to match
each character in string against a specific character, a wildcard character, a character list, or a character range. The following
table shows the characters allowed in pattern and what they match.
Characters in pattern Matches in string
? Any single character
See Also
Tasks
How to: Match a String against a Pattern
Reference
Comparison Operators (Visual Basic)
InStr Function (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Option Compare Statement
StrComp Function (Visual Basic)
Concepts
Operators and Expressions in Visual Basic
Visual Basic Language Reference
Parts
number1
Required. Any numeric expression.
number2
Required. Any numeric expression.
Supported Types
All numeric types, including the unsigned and floating-point types and Decimal.
Result
The result is the remainder after number1 is divided by number2. For example, the expression 14 Mod 4 evaluates to 2.
Remarks
If either number1 or number2 is a floating-point value, the floating-point remainder of the division is returned. The data type
of the result is the smallest data type that can hold all possible values resulting from division with the data types of number1
and number2.
If number1 or number2 evaluates to Nothing, it is treated as zero.
Related operators include the following:
The \ Operator returns the integer quotient of a division. For example, the expression 14 \ 4 evaluates to 3.
The / Operator (Visual Basic) returns the full quotient, including the remainder, as a floating-point number. For example,
the expression 14 / 4 evaluates to 3.5.
Attempted Division by Zero
If number2 evaluates to zero, the behavior of the Mod operator depends on the data type of the operands. An integral division
throws a DivideByZeroException exception. A floating-point division returns NaN.
Equivalent Formula
The expression a Mod b is equivalent to either of the following formulas:
a - (b * (a \ b))
a - (b * Fix(a / b))
Floating-point Imprecision
When you work with floating-point numbers, keep in mind that they do not always have a precise representation in memory.
This could lead to unexpected results from certain operations, such as value comparison and the Mod operator. For more
information, see Troubleshooting Data Types.
Overloading
The Mod operator can be overloaded, which means that a class or structure can redefine its behavior. If your code applies
Mod to an instance of a class or structure that includes such an overload, be sure you understand its redefined behavior. For
more information, see Operator Procedures.
Example
The following example uses the Mod operator to divide two numbers and return only the remainder. If either number is a
floating-point number, the result is a floating-point number representing the remainder.
VB
Dim testResult As Double
testResult = 10 Mod 5
testResult = 10 Mod 3
testResult = 12 Mod 4.3
testResult = 12.6 Mod 5
testResult = 47.9 Mod 9.35
The expressions in the preceding example return values of 0, 1, 3.4, 2.6, and 1.15.
The following example demonstrates the potential imprecision of floating-point operands. In the first statement, the operands
are Double, and 0.2 is an infinitely repeating binary fraction with a stored value of 0.20000000000000001. In the second
statement, the literal type character D forces both operands to Decimal, and 0.2 has a precise representation.
VB
firstResult = 2.0 Mod 0.2
' Double operation returns 0.2, not 0.
secondResult = 2D Mod 0.2D
' Decimal operation returns 0.
See Also
Tasks
Troubleshooting Data Types
Reference
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Int, Fix Functions (Visual Basic)
\ Operator
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference
Parts
result
Required. Any Boolean or numeric expression.
expression
Required. Any Boolean or numeric expression.
Remarks
For Boolean expressions, the following table illustrates how result is determined.
If expression is The value of result is
True False
False True
For numeric expressions, the Not operator inverts the bit values of any numeric expression and sets the corresponding bit in
result according to the following table.
If bit in expression is The bit in result is
1 0
0 1
Note
Since the logical and bitwise operators have a lower precedence than other arithmetic and relational operators, any bitwise o
perations should be enclosed in parentheses to ensure accurate execution.
Data Types
For a Boolean negation, the data type of the result is Boolean. For a bitwise negation, the result data type is the same as that of
expression. However, if expression is Decimal, the result is Long.
Overloading
The Not operator can be overloaded, which means that a class or structure can redefine its behavior when its operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefined
behavior. For more information, see Operator Procedures.
Example
The following example uses the Not operator to perform logical negation on a Boolean expression. The result is a Boolean
value that represents the reverse of the value of the expression.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck As Boolean
firstCheck = Not (a > b)
secondCheck = Not (b > a)
The preceding example produces results of False and True, respectively.
The following example uses the Not operator to perform logical negation of the individual bits of a numeric expression. The bit
in the result pattern is set to the reverse of the corresponding bit in the operand pattern, including the sign bit.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstPattern, secondPattern, thirdPattern As Integer
firstPattern = (Not a)
secondPattern = (Not b)
thirdPattern = (Not c)
The preceding example produces results of –11, –9, and –7, respectively.
See Also
Reference
Logical/Bitwise Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Reference
Parts
result
Required. Any Boolean or numeric expression. For Boolean comparison, result is the inclusive logical disjunction of two
Boolean values. For bitwise operations, result is a numeric value representing the inclusive bitwise disjunction of two
numeric bit patterns.
expression1
Required. Any Boolean or numeric expression.
expression2
Required. Any Boolean or numeric expression.
Remarks
For Boolean comparison, result is False if and only if both expression1 and expression2 evaluate to False. The following table
illustrates how result is determined.
If expression1 is And expression2 is The value of result is
True True True
For bitwise operations, the Or operator performs a bitwise comparison of identically positioned bits in two numeric
expressions and sets the corresponding bit in result according to the following table.
If bit in expression1 is And bit in expression2 is The bit in result is
1 1 1
1 0 1
0 1 1
0 0 0
Note
Since the logical and bitwise operators have a lower precedence than other arithmetic and relational operators, any bitwise o
perations should be enclosed in parentheses to ensure accurate execution.
Data Types
If the operands consist of one Boolean expression and one numeric expression, Visual Basic converts the Boolean expression
to a numeric value (–1 for True and 0 for False) and performs a bitwise operation.
For a Boolean comparison, the data type of the result is Boolean. For a bitwise comparison, the result data type is a numeric
type appropriate for the data types of expression1 and expression2. See the "Relational and Bitwise Comparisons" table in
Data Types of Operator Results.
Overloading
The Or operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefined
behavior. For more information, see Operator Procedures.
Example
The following example uses the Or operator to perform an inclusive logical disjunction on two expressions. The result is a
Boolean value that represents whether either of the two expressions is True.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck, thirdCheck As Boolean
firstCheck = a > b Or b > c
secondCheck = b > a Or b > c
thirdCheck = b > a Or c > b
The preceding example produces results of True, True, and False, respectively.
The following example uses the Or operator to perform inclusive logical disjunction on the individual bits of two numeric
expressions. The bit in the result pattern is set if either of the corresponding bits in the operands is set to 1.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstPattern, secondPattern, thirdPattern As Integer
firstPattern = (a Or b)
secondPattern = (a Or c)
thirdPattern = (b Or c)
The preceding example produces results of 10, 14, and 14, respectively.
See Also
Reference
Logical/Bitwise Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
OrElse Operator
Concepts
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Reference
OrElse Operator
Performs short-circuiting inclusive logical disjunction on two expressions.
Parts
result
Required. Any Boolean expression.
expression1
Required. Any Boolean expression.
expression2
Required. Any Boolean expression.
Remarks
A logical operation is said to be short-circuiting if the compiled code can bypass the evaluation of one expression depending
on the result of another expression. If the result of the first expression evaluated determines the final result of the operation,
there is no need to evaluate the second expression, because it cannot change the final result. Short-circuiting can improve
performance if the bypassed expression is complex, or if it involves procedure calls.
If either or both expressions evaluate to True, result is True. The following table illustrates how result is determined.
If expression1 is And expression2 is The value of result is
True (not evaluated) True
The following example shows an If...Then statement containing two procedure calls. If the first call returns True, the second
procedure is not called. This could produce unexpected results if the second procedure performs important tasks that should
always be performed when this section of the code runs.
VB
If testFunction(5) = True OrElse otherFunction(4) = True Then
' If testFunction(5) is True, otherFunction(4) is not called.
' Insert code to be executed.
End If
See Also
Reference
Logical/Bitwise Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
Or Operator (Visual Basic)
IsTrue Operator
Concepts
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Reference
Parts
result
Returned. A Boolean value.
objectexpression
Required. Any expression that evaluates to a reference type.
typename
Required. Any data type name.
Remarks
The TypeOf operator determines whether the run-time type of objectexpression is compatible with typename. The
compatibility depends on the type category of typename. The following table shows how compatibility is determined.
Type category of typename Compatibility criterion
Class objectexpression is of type typename or inherits from typename
Interface objectexpression implements typename or inherits from a class that implements typename
If the run-time type of objectexpression satisfies the compatibility criterion, result is True. Otherwise, result is False.
TypeOf is always used with the Is keyword to construct a TypeOf...Is expression.
Example
The following example uses TypeOf...Is expressions to test the type compatibility of two object reference variables with various
data types.
VB
Dim refInteger As Object = 2
MsgBox("TypeOf Object[Integer] Is Integer? " & TypeOf refInteger Is Integer)
MsgBox("TypeOf Object[Integer] Is Double? " & TypeOf refInteger Is Double)
Dim refForm As Object = New System.Windows.Forms.Form
MsgBox("TypeOf Object[Form] Is Form? " & TypeOf refForm Is System.Windows.Forms.Form)
MsgBox("TypeOf Object[Form] Is Label? " & TypeOf refForm Is System.Windows.Forms.Label)
MsgBox("TypeOf Object[Form] Is Control? " & TypeOf refForm Is System.Windows.Forms.Control)
MsgBox("TypeOf Object[Form] Is IComponent? " & TypeOf refForm Is System.ComponentModel.ICom
ponent)
The variable refInteger has a run-time type of Integer. It is compatible with Integer but not with Double. The variable
refForm has a run-time type of Form. It is compatible with Form because that is its type, with Control because Form inherits
from Control, and with IComponent because Form inherits from Component, which implements IComponent. However,
refForm is not compatible with Label.
See Also
Reference
Is Operator (Visual Basic)
IsNot Operator
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Comparison Operators in Visual Basic
Operators and Expressions in Visual Basic
Visual Basic Language Reference
Parts
result
Required. Any Boolean or numeric variable. For Boolean comparison, result is the logical exclusion (exclusive logical
disjunction) of two Boolean values. For bitwise operations, result is a numeric value representing the bitwise exclusion
(exclusive bitwise disjunction) of two numeric bit patterns.
expression1
Required. Any Boolean or numeric expression.
expression2
Required. Any Boolean or numeric expression.
Remarks
For Boolean comparison, result is True if and only if exactly one of expression1 and expression2 evaluates to True, that is, if and
only if expression1 and expression2 evaluate to opposite Boolean values. The following table illustrates how result is
determined.
If expression1 is And expression2 is The value of result is
True True False
For bitwise operations, the Xor operator performs a bitwise comparison of identically positioned bits in two numeric
expressions and sets the corresponding bit in result according to the following table.
If bit in expression1 is And bit in expression2 is The bit in result is
1 1 0
1 0 1
0 1 1
0 0 0
Note
Since the logical and bitwise operators have a lower precedence than other arithmetic and relational operators, any bitwise o
perations should be enclosed in parentheses to ensure accurate execution.
For example, 5 Xor 3 is 6. To see why this is so, convert 5 and 3 to their binary representations, 101 and 011. Then use the
preceding table to determine that 101 Xor 011 is 110, which is the binary representation of the decimal number 6.
Data Types
If the operands consist of one Boolean expression and one numeric expression, Visual Basic converts the Boolean expression
to a numeric value (–1 for True and 0 for False) and performs a bitwise operation.
For a Boolean comparison, the data type of the result is Boolean. For a bitwise comparison, the result data type is a numeric
type appropriate for the data types of expression1 and expression2. See the "Relational and Bitwise Comparisons" table in
Data Types of Operator Results.
Overloading
The Xor operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefined
behavior. For more information, see Operator Procedures.
Example
The following example uses the Xor operator to perform logical exclusion (exclusive logical disjunction) on two expressions.
The result is a Boolean value that represents whether exactly one of the expressions is True.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck, thirdCheck As Boolean
firstCheck = a > b Xor b > c
secondCheck = b > a Xor b > c
thirdCheck = b > a Xor c > b
The preceding example produces results of False, True, and False, respectively.
The following example uses the Xor operator to perform logical exclusion (exclusive logical disjunction) on the individual bits
of two numeric expressions. The bit in the result pattern is set if exactly one of the corresponding bits in the operands is set to
1.
VB
Dim a As Integer = 10 ' 1010 in binary
Dim b As Integer = 8 ' 1000 in binary
Dim c As Integer = 6 ' 0110 in binary
Dim firstPattern, secondPattern, thirdPattern As Integer
firstPattern = (a Xor b) ' 2, 0010 in binary
secondPattern = (a Xor c) ' 12, 1100 in binary
thirdPattern = (b Xor c) ' 14, 1110 in binary
The ^ operator is defined only for the Double data type. Visual Basic widens each operand as necessary to Double before the
operation, and the result data type is always Double.
Integer Arithmetic
The result data type of an integer operation depends on the data types of the operands. In general, Visual Basic uses the
following policies for determining the result data type:
If both operands of a binary operator have the same data type, the result has that data type. An exception is Boolean,
which is forced to Short.
If an unsigned operand participates with a signed operand, the result has a signed type with at least as large a range as
either operand.
Otherwise, the result usually has the larger of the two operand data types.
Note that the result data type might not be the same as either operand data type.
Note
The result data type is not always large enough to hold all possible values resulting from the operation. An
OverflowException exception can occur if the value is too large for the result data type.
Unary + Short SByte Byte Short UShort Integer UInteger Long ULong
Unary – Short SByte Short Short Integer Integer Long Long Decimal
<< and >> Operators
The following table shows the result data types for the two bit-shift operators, << and >>. Visual Basic treats each bit-shift
operator as a unary operator on its left operand (the bit pattern to be shifted).
<<, >> Short SByte Byte Short UShort Integer UInteger Long ULong
If the left operand is Decimal, Single, Double, or String, Visual Basic attempts to convert it to Long before the operation, and
the result data type is Long. The right operand (the number of bit positions to shift) must be Integer or a type that widens to
Integer.
Binary +, –, *, and Mod Operators
The following table shows the result data types for the binary + and – operators and the * and Mod operators. Note that this
table is symmetric; for a given combination of operand data types, the result data type is the same regardless of the order of
the operands.
Boolean Short SByte Short Short Integer Integer Long Long Decimal
SByte SByte SByte Short Short Integer Integer Long Long Decimal
Byte Short Short Byte Short UShort Integer UInteger Long ULong
Short Short Short Short Short Integer Integer Long Long Decimal
UShort Integer Integer UShort Integer UShort Integer UInteger Long ULong
Integer Integer Integer Integer Integer Integer Integer Long Long Decimal
UInteger Long Long UInteger Long UInteger Long UInteger Long ULong
Long Long Long Long Long Long Long Long Long Decimal
ULong Decimal Decimal ULong Decimal ULong Decimal ULong Decimal ULong
\ Operator
The following table shows the result data types for the \ operator. Note that this table is symmetric; for a given combination of
operand data types, the result data type is the same regardless of the order of the operands.
Boolean Short SByte Short Short Integer Integer Long Long Long
SByte SByte SByte Short Short Integer Integer Long Long Long
Byte Short Short Byte Short UShort Integer UInteger Long ULong
Short Short Short Short Short Integer Integer Long Long Long
UShort Integer Integer UShort Integer UShort Integer UInteger Long ULong
Integer Integer Integer Integer Integer Integer Integer Long Long Long
UInteger Long Long UInteger Long UInteger Long UInteger Long ULong
Long Long Long Long Long Long Long Long Long Long
ULong Long Long ULong Long ULong Long ULong Long ULong
If either operand of the \ operator is Decimal, Single, or Double, Visual Basic attempts to convert it to Long before the
operation, and the result data type is Long.
Relational and Bitwise Comparisons
The result data type of a relational operation (=, <>, <, >, <=, >=) is always BooleanBoolean Data Type (Visual Basic). The
same is true for logical operations (And, AndAlso, Not, Or, OrElse, Xor) on Boolean operands.
The result data type of a bitwise logical operation depends on the data types of the operands. Note that AndAlso and OrElse
are defined only for Boolean, and Visual Basic converts each operand as necessary to Boolean before performing the
operation.
=, <>, <, >, <=, and >= Operators
If both operands are Boolean, Visual Basic considers True to be less than False. If a numeric type is compared with a String,
Visual Basic attempts to convert the String to Double before the operation. A Char or Date operand can be compared only
with another operand of the same data type. The result data type is always Boolean.
Bitwise Not Operator
The following table shows the result data types for the bitwise Not operator.
Not Boolean SByte Byte Short UShort Integer UInteger Long ULong
If the operand is Decimal, Single, Double, or String, Visual Basic attempts to convert it to Long before the operation, and the
result data type is Long.
Bitwise And, Or, and Xor Operators
The following table shows the result data types for the bitwise And, Or, and Xor operators. Note that this table is symmetric;
for a given combination of operand data types, the result data type is the same regardless of the order of the operands.
Boolean SByte Byte Short UShort Integer UInteger Long ULong
Boolean Boolean SByte Short Short Integer Integer Long Long Long
SByte SByte SByte Short Short Integer Integer Long Long Long
Byte Short Short Byte Short UShort Integer UInteger Long ULong
Short Short Short Short Short Integer Integer Long Long Long
UShort Integer Integer UShort Integer UShort Integer UInteger Long ULong
Integer Integer Integer Integer Integer Integer Integer Long Long Long
UInteger Long Long UInteger Long UInteger Long UInteger Long ULong
Long Long Long Long Long Long Long Long Long Long
ULong Long Long ULong Long ULong Long ULong Long ULong
If an operand is Decimal, Single, Double, or String, Visual Basic attempts to convert it to Long before the operation, and the
result data type is the same as if that operand had already been Long.
Miscellaneous Operators
The & operator is defined only for concatenation of String operands. Visual Basic converts each operand as necessary to
String before the operation, and the result data type is always String. For the purposes of the & operator, all conversions to
String are considered to be widening, even if Option Strict is On.
The Is and IsNot operators require both operands to be of a reference type. The TypeOf...Is expression requires the first
operand to be of a reference type and the second operand to be the name of a data type. In all these cases the result data type
is Boolean.
The Like operator is defined only for pattern matching of String operands. Visual Basic attempts to convert each operand as
necessary to String before the operation. The result data type is always Boolean.
See Also
Reference
Data Type Summary (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Arithmetic Operators (Visual Basic)
Comparison Operators (Visual Basic)
Option Strict Statement
Concepts
Operators and Expressions in Visual Basic
Arithmetic Operators in Visual Basic
Comparison Operators in Visual Basic
Other Resources
Operators (Visual Basic)
Visual Basic Language Reference
Assignment Operators
The following are the assignment operators defined in Visual Basic.
= Operator
^= Operator
*= Operator
/= Operator
\= Operator
+= Operator
-= Operator
<<= Operator
>>= Operator
&= Operator
See Also
Reference
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference
Parts
result
Required. A Boolean value representing the result of the comparison.
expression
Required. Any expression.
comparisonoperator
Required. Any relational comparison operator.
object1, object2
Required. Any reference object names.
string
Required. Any String expression.
pattern
Required. Any String expression or range of characters.
Remarks
The following table contains a list of the relational comparison operators and the conditions that determine whether result is
True or False.
Operator True if False if
< (Less than) expression1 < expression2 expression1 >= expression2
<= (Less than or equal to) expression1 <= expression2 expression1 > expression2
The Is operator, the IsNot operator, and the Like operator have specific comparison functionalities that differ from the
operators in the preceding table.
Comparing Numbers
When you compare an expression of type Single to one of type Double, the Single expression is converted to Double. This
behavior is opposite to the behavior found in Visual Basic 6.
Similarly, when you compare an expression of type Decimal to an expression of type Single or Double, the Decimal
expression is converted to Single or Double. For Decimal expressions, any fractional value less than 1E-28 might be lost.
Such fractional value loss may cause two values to compare as equal when they are not. For this reason, you should take care
when using equality (=) to compare two floating-point variables. It is safer to test whether the absolute value of the difference
between the two numbers is less than a small acceptable tolerance.
Floating-point Imprecision
When you work with floating-point numbers, keep in mind that they do not always have a precise representation in memory.
This could lead to unexpected results from certain operations, such as value comparison and the Mod Operator (Visual Basic).
For more information, see Troubleshooting Data Types.
Comparing Strings
When you compare strings, the string expressions are evaluated based on their alphabetical sort order, which depends on the
Option Compare setting.
Option Compare Binary bases string comparisons on a sort order derived from the internal binary representations of the
characters. The sort order is determined by the code page. The following example shows a typical binary sort order.
A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø
Option Compare Text bases string comparisons on a case-insensitive, textual sort order determined by your application's
locale. When you set Option Compare Text and sort the characters in the preceding example, the following text sort order
applies:
(A=a) < (À= à) < (B=b) < (E=e) < (Ê= ê) < (Ø = ø) < (Z=z)
Locale Dependence
When you set Option Compare Text, the result of a string comparison can depend on the locale in which the application is
running. Two characters might compare as equal in one locale but not in another. If you are using a string comparison to make
important decisions, such as whether to accept an attempt to log on, you should be alert to locale sensitivity. Consider either
setting Option Compare Binary or calling the StrComp Function (Visual Basic), which takes the locale into account.
Typeless Programming with Relational Comparison Operators
The use of relational comparison operators with Object expressions is not allowed under Option Strict On. When Option
Strict is Off, and either expression1 or expression2 is an Object expression, the run-time types determine how they are
compared. The following table shows how the expressions are compared and the result from the comparison, depending on
the runtime type of the operands.
If operands are Comparison is
Both String Sort comparison based on string sorting characteristics.
In the preceding example, the first comparison returns False and the remaining comparisons return True.
See Also
Tasks
Troubleshooting Data Types
Reference
= Operator (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
InvalidCastException
Concepts
Comparison Operators in Visual Basic
Visual Basic Language Reference
Logical/Bitwise Operators
The following are the logical/bitwise operators defined in Visual Basic.
And Operator (Visual Basic)
Not Operator (Visual Basic)
Or Operator (Visual Basic)
Xor Operator (Visual Basic)
AndAlso Operator
OrElse Operator
IsFalse Operator
IsTrue Operator
See Also
Reference
Operator Precedence in Visual Basic
Concepts
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Reference
Miscellaneous Operators
The following are miscellaneous operators defined in Visual Basic.
AddressOf Operator
GetType Operator
TypeOf Operator (Visual Basic)
See Also
Reference
Operators Listed by Functionality
Visual Basic Language Reference
DateString Property
Returns or sets a String value representing the current date according to your system.
Exceptions
Exception type Error number Condition
InvalidCastException 5 Invalid format used to set value of DateString.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
DateString always returns the system date as "MM-dd-yyyy", which uses the abbreviated month name. The accepted formats
for setting the date are "M-d-yyyy", "M-d-y", "M/d/yyyy", and "M/d/y". These formats are culture-invariant, which means they
do not change even if you change the Regional Options in Control Panel.
To get or set the current system time as a String, use the TimeString Property.
To get the current system date or time in the format of your locale, or in a custom format, supply the Now Property to the
Format Function, specifying either Predefined Date/Time Formats (Format Function) or
User-Defined Date/Time Formats (Format Function). The following example demonstrates this.
To access the current system date as a Date, use the Today Property.
Security Note
Setting the system date or time requires unmanaged code permission, which might affect its execution in partial-trust situati
ons. For more information, see SecurityPermission and Code Access Permissions.
Example
The following example uses the DateString property to display the current system date.
VB
MsgBox("The current date is " & DateString)
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because DateString is a member of a module, rather than of a class, you do not need to create an object on which to access
DateString.
Smart Device Developer Notes
You can get, but not set, the system date using the DateString property.
See Also
Reference
Now Property
TimeString Property
Today Property
Date Data Type (Visual Basic)
DateTime
Visual Basic Language Reference
Now Property
Returns a Date value containing the current date and time according to your system.
Remarks
To set the system date, use the Today Property. To set the system time, use the TimeOfDay Property.
Example
The following example uses the Now property to return the current system date and time.
VB
Dim ThisMoment As Date
' The following statement calls the Get procedure of the Visual Basic Now property.
ThisMoment = Now
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because Now is a member of a module, rather than of a class, you do not need to create an object on which to access Now.
See Also
Reference
Day Function (Visual Basic)
Hour Function (Visual Basic)
Minute Function
Month Function (Visual Basic)
Second Function (Visual Basic)
Weekday Function (Visual Basic)
Year Function (Visual Basic)
Date Data Type (Visual Basic)
DateTime
Visual Basic Language Reference
ScriptEngine Property
Returns a String representing the runtime currently in use.
Remarks
The ScriptEngine property returns the string "VB".
You can use ScriptEngine when your application is running as a standalone program, in a script, or in a host application.
Example
The following example uses the ScriptEngine property and related properties to return a string describing the current run-
time information:
VB
Function getRuntimeInfo() As String
Dim runtime As String = ScriptEngine & " Version "
runtime &= CStr(ScriptEngineMajorVersion) & "."
runtime &= CStr(ScriptEngineMinorVersion) & "."
runtime &= CStr(ScriptEngineBuildVersion)
' Return the current runtime information.
Return runtime
End Function
ScriptEngineBuildVersion Property
Returns an Integer containing the build version number of the runtime currently in use.
Remarks
The returned value corresponds directly to the version information contained in the DLL for the current runtime.
You can use ScriptEngineBuildVersion when your application is running as a standalone program, in a script, or in a host
application.
Example
The following example uses the ScriptEngineBuildVersion property and related properties to return a string describing the
current run-time information:
VB
Function getRuntimeInfo() As String
Dim runtime As String = ScriptEngine & " Version "
runtime &= CStr(ScriptEngineMajorVersion) & "."
runtime &= CStr(ScriptEngineMinorVersion) & "."
runtime &= CStr(ScriptEngineBuildVersion)
' Return the current runtime information.
Return runtime
End Function
ScriptEngineMajorVersion Property
Returns an Integer containing the major version number of the runtime currently in use.
Remarks
The returned value corresponds directly to the version information contained in the DLL for the current runtime.
You can use ScriptEngineMajorVersion when your application is running as a standalone program, in a script, or in a host
application.
Example
The following example uses the ScriptEngineMajorVersion property and related properties to return a string describing the
current run-time information:
VB
Function getRuntimeInfo() As String
Dim runtime As String = ScriptEngine & " Version "
runtime &= CStr(ScriptEngineMajorVersion) & "."
runtime &= CStr(ScriptEngineMinorVersion) & "."
runtime &= CStr(ScriptEngineBuildVersion)
' Return the current runtime information.
Return runtime
End Function
ScriptEngineMinorVersion Property
Returns an Integer containing the minor version number of the runtime currently in use.
Remarks
The returned value corresponds directly to the version information contained in the DLL for the current runtime.
You can use ScriptEngineMinorVersion when your application is running as a standalone program, in a script, or in a host
application.
Example
The following example uses the ScriptEngineMinorVersion property and related properties to return a string describing the
current run-time information:
VB
Function getRuntimeInfo() As String
Dim runtime As String = ScriptEngine & " Version "
runtime &= CStr(ScriptEngineMajorVersion) & "."
runtime &= CStr(ScriptEngineMinorVersion) & "."
runtime &= CStr(ScriptEngineBuildVersion)
' Return the current runtime information.
Return runtime
End Function
TimeOfDay Property
Returns or sets a Date value containing the current time of day according to your system.
Remarks
The Date data type includes date components. When returning the system time, TimeOfDay sets these all to 1, so the
returned value represents the first day of the year 1. When setting the system time, TimeOfDay ignores the date components.
To access the current system time as a String, use the TimeString Property.
To get or set the current system date, use the Today Property.
Security Note
Setting the system date or time requires unmanaged code permission, which might affect its execution in partial-trust situati
ons. For more information, see SecurityPermission and Code Access Permissions.
Example
This example uses the TimeOfDay property to return the current system time.
VB
Dim currentTime As Date
currentTime = TimeOfDay
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because TimeOfDay is a member of a module, rather than of a class, you do not need to create an object on which to access
TimeOfDay.
Smart Device Developer Notes
You can get, but not set, the current time of day using the TimeOfDay property.
See Also
Reference
Timer Property
Date Data Type (Visual Basic)
DateTime
Visual Basic Language Reference
Timer Property
Returns a Double value representing the number of seconds elapsed since midnight.
Remarks
The Timer property returns both the seconds and the milliseconds since the most recent midnight. The seconds are in the
integral part of the return value, and the milliseconds are in the fractional part.
Example
This example uses the Timer property to pause the application. It can perform other processing during the pause.
VB
Public Sub waitFiveSeconds()
If TimeOfDay >= #11:59:55 PM# Then
MsgBox("The current time is within 5 seconds of midnight" & _
vbCrLf & "The timer returns to 0.0 at midnight")
Return
End If
Dim start, finish, totalTime As Double
If (MsgBox("Press Yes to pause for 5 seconds", MsgBoxStyle.YesNo)) _
= MsgBoxResult.Yes Then
start = Microsoft.VisualBasic.DateAndTime.Timer
' Set end time for 5-second duration.
finish = start + 5.0
Do While Microsoft.VisualBasic.DateAndTime.Timer < finish
' Do other processing while waiting for 5 seconds to elapse.
Loop
totalTime = Microsoft.VisualBasic.DateAndTime.Timer - start
MsgBox("Paused for " & totalTime & " seconds")
End If
End Sub
Note that you must qualify the Timer property with the Microsoft.VisualBasic namespace, because Timer is also a defined
class in the System.Threading, System.Timers, and System.Windows.Forms namespaces.
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because Timer is a member of a module, rather than of a class, you do not need to create an object on which to access Timer.
See Also
Reference
Randomize Function (Visual Basic)
TimeOfDay Property
Today Property
System
System.Windows.Forms
DateTime
ArgumentException
ArgumentOutOfRangeException
Visual Basic Language Reference
TimeString Property
Returns or sets a String value representing the current time of day according to your system.
Exceptions
Exception type Error number Condition
InvalidCastException 5 Invalid format used to set value of TimeString.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
TimeString always returns the system time as "HH:mm:ss", which is a 24-hour format. This format is culture-invariant, which
means it does not change even if you change the Regional Options in Control Panel.
To get or set the current system date as a String, use the DateString Property.
To get the current system date or time in the format of your locale, or in a custom format, supply the Now Property to the
Format Function, specifying either Predefined Date/Time Formats (Format Function) or
User-Defined Date/Time Formats (Format Function). The following example demonstrates this.
To access the current system time as a Date, use the TimeOfDay Property.
Security Note
Setting the system date or time requires unmanaged code permission, which might affect its execution in partial trust situati
ons. For more information, see SecurityPermission and Code Access Permissions.
Example
This example uses the TimeString property to display the current system time.
VB
MsgBox("The current time is " & TimeString)
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because TimeString is a member of a module, rather than of a class, you do not need to create an object on which to access
TimeString.
Smart Device Developer Notes
You can get, but not set, the system time using the TimeString property.
See Also
Reference
Now Property
DateString Property
TimeOfDay Property
Date Data Type (Visual Basic)
DateTime
Visual Basic Language Reference
Today Property
Returns or sets a Date value containing the current date according to your system.
Remarks
The Date data type includes time components. When returning the system date, Today sets all of these to 0, so the returned
value represents midnight (00:00:00). When setting the system date, Today ignores the time components.
To access the current system date as a String, use the DateString Property.
To get or set the current system time, use the TimeOfDay Property.
Security Note
Setting the system date or time requires unmanaged code permission, which might affect its execution in partial-trust situati
ons. For more information, see SecurityPermission and Code Access Permissions.
Example
This example uses the Today property to return the current system date.
VB
Dim thisDate As Date
thisDate = Today
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because Today is a member of a module, rather than of a class, you do not need to create an object on which to access Today.
Smart Device Developer Notes
You can get but not set the current system date using the Today property.
See Also
Reference
Format Function
Now Property
Date Data Type (Visual Basic)
DateTime
Visual Basic Language Reference
A-E Statements
The following table contains a listing of Visual Basic language statements.
AddHandler Statement
Associates an event with an event handler at run time.
Parts
event
The name of the event to handle.
eventhandler
The name of a procedure that handles the event.
Remarks
The AddHandler and RemoveHandler statements allow you to start and stop event handling at any time during program
execution.
The signature of the eventhandler procedure must match the signature of the event event.
The Handles keyword and the AddHandler statement both allow you to specify that particular procedures handle particular
events, but there are differences. The AddHandler statement connects procedures to events at run time. Use the Handles
keyword when defining a procedure to specify that it handles a particular event. For more information, see Handles.
For custom events, the AddHandler statement invokes the event's AddHandler accessor. For more information on custom
events, see Event Statement.
Example
VB
Sub TestEvents()
Dim Obj As New Class1
' Associate an event handler with an event.
AddHandler Obj.Ev_Event, AddressOf EventHandler
' Call the method to raise the event.
Obj.CauseSomeEvent()
' Stop handling events.
RemoveHandler Obj.Ev_Event, AddressOf EventHandler
' This event will not be handled.
Obj.CauseSomeEvent()
End Sub
Sub EventHandler()
' Handle the event.
MsgBox("EventHandler caught event.")
End Sub
Public Class Class1
' Declare an event.
Public Event Ev_Event()
Sub CauseSomeEvent()
' Raise an event.
RaiseEvent Ev_Event()
End Sub
End Class
See Also
Reference
RemoveHandler Statement
Handles
Event Statement
Concepts
Events and Event Handlers
AddHandler and RemoveHandler
Visual Basic Language Reference
Parts
procedureName
Required. Name of the procedure to call.
argumentList
Optional. List of variables or expressions representing arguments that are passed to the procedure when it is called. Multiple
arguments are separated by commas. If you include argumentList, you must enclose it in parentheses.
Remarks
You normally use the Call statement to call a procedure that does not return a value. If the procedure returns a value, the Call
statement discards it.
You are not required to use the Call statement when calling a procedure. However, it improves the readability of your code.
Example
This example illustrates how the Call statement is used to transfer control to a Sub procedure, an intrinsic function, and a
dynamic-link library (DLL) procedure.
VB
' (1) Call a Sub procedure.
Call printToDebugWindow("Hello World")
...
' The above statement passes control to the following Sub procedure.
Sub printToDebugWindow(ByVal anyString As String)
Debug.WriteLine(anyString)
End Sub
VB
' (2) Call a Visual Basic run-time function (Shell), discard the return value.
Call Shell("C:\WINNT\system32\calc.exe", AppWinStyle.NormalFocus)
' The preceding path is for Windows 2000;
' The Windows XP path is C:\Windows\system32\calc.exe.
VB
' (3) Call a Microsoft Windows DLL procedure. The Declare statement
' must be Private in a class, not in a module.
Private Declare Sub MessageBeep Lib "User32" (ByVal N As Integer)
Sub callBeepDll()
Call MessageBeep(-1)
End Sub
See Also
Reference
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Declare Statement
Visual Basic Language Reference
Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
Shadows
Optional. See Shadows.
MustInherit
Optional. See MustInherit.
NotInheritable
Optional. See NotInheritable.
Partial
Optional. Indicates a partial definition of the class. See Partial (Visual Basic).
name
Required. Name of this class. See Declared Element Names.
Of
Optional. Specifies that this is a generic class.
typelist
Required if you use the Of keyword. List of type parameters for this class. See Type List.
Inherits
Optional. Indicates that this class inherits the members of another class. See Inherits Statement.
classname
Required if you use the Inherits statement. The name of the class from which this class derives.
Implements
Optional. Indicates that this class implements the members of one or more interfaces. See Implements Statement.
interfacenames
Required if you use the Implements statement. The names of the interfaces this class implements.
statements
Optional. Statements which define the members of this class.
End Class
Required. Terminates the Class definition.
Remarks
A Class statement defines a new data type. A class is a fundamental building block of object-oriented programming (OOP). For
more information, see Object-Oriented Programming in Visual Basic and Classes: Blueprints for Objects.
You can use Class only at namespace or module level. This means the declaration context for a class must be a source file,
namespace, class, structure, module, or interface, and cannot be a procedure or block. For more information, see
Declaration Contexts and Default Access Levels.
Each instance of a class has a lifetime independent of all other instances. This lifetime begins when it is created by a
New (Visual Basic) clause or by a function such as CreateObject Function (Visual Basic). It ends when all variables pointing to
the instance have been set to Nothing (Visual Basic) or to instances of other classes.
Classes default to Friend (Visual Basic) access. You can adjust their access levels with the access modifiers. For more
information, see Access Levels in Visual Basic.
Rules
Nesting. You can define one class within another. The outer class is called the containing class, and the inner class is
called a nested class.
Inheritance. If the class uses the Inherits Statement, you can specify only one base class or interface. A class cannot
inherit from more than one element.
A class cannot inherit from another class with a more restrictive access level. For example, a Public class cannot inherit
from a Friend class.
A class cannot inherit from a class nested within it.
Implementation. If the class uses the Implements Statement, you must implement every member defined by every
interface you specify in interfacenames. An exception to this is reimplementation of a base class member. For more
information, see "Reimplementation" in Implements (Visual Basic).
Default Property. A class can specify at most one property as its default property. For more information, see
Default Properties.
Behavior
Access Level. Within a class, you can declare each member with its own access level. Class members default to
Public (Visual Basic) access, except variables and constants, which default to Private (Visual Basic) access. When a class
has more restricted access than one of its members, the class access level takes precedence.
Scope. A class is in scope throughout its containing namespace, class, structure, or module.
The scope of every class member is the entire class.
Lifetime. Visual Basic does not support static classes. The functional equivalent of a static class is provided by a module.
For more information, see Module Statement.
Class members have lifetimes depending on how and where they are declared. For more information, see
Lifetime in Visual Basic.
Qualification. Code outside a class must qualify a member's name with the name of that class.
If code inside a nested class makes an unqualified reference to a programming element, Visual Basic searches for the
element first in the nested class, then in its containing class, and so on out to the outermost containing element. For more
information, see Resolving a Reference When Multiple Variables Have the Same Name.
Classes and Modules
These elements have many similarities, but there are some important differences as well.
Terminology. Previous versions of Visual Basic recognize two types of modules: class modules (.cls files) and standard
modules (.bas files). The current version calls these classes and modules, respectively.
Shared Members. You can control whether a member of a class is a shared or instance member.
Object Orientation. Classes are object-oriented, but modules are not. You can create one or more instances of a class.
For more information, see Classes vs. Modules.
Example
The following example uses a Class statement to define a class and several members.
VB
Class bankAccount
Shared interestRate As Decimal
Private accountNumber As String
Private accountBalance As Decimal
Public holdOnAccount As Boolean = False
See Also
Tasks
How to: Use a Generic Class
Reference
Interface Statement (Visual Basic)
Module Statement
Property Statement
Concepts
Structures and Classes
Object Lifetime: How Objects Are Created and Destroyed
Generic Types in Visual Basic
Other Resources
Understanding Classes
Visual Basic Language Reference
Parts
attributelist
Optional. List of attributes that apply to all the constants declared in this statement. See Attribute List in angle brackets ("<"
and ">").
accessmodifier
Optional. Use this to specify what code can access these constants. Can be Public (Visual Basic), Protected (Visual Basic),
Friend (Visual Basic), Protected Friend, or Private (Visual Basic).
Shadows
Optional. Use this to redeclare and hide a programming element in a base class. See Shadows.
constantlist
Required. List of constants being declared in this statement.
constant [ , constant ... ]
Part Description
constantname Required. Name of the constant. See Declared Element Names.
initializer Required. Expression that is evaluated at compile time and assigned to the constant.
Remarks
If you have a value that never changes in your application, you can define a named constant and use it in place of a literal
value. A name is easier to remember than a value. You can define the constant just once and use it in many places in your code.
If in a later version you need to redefine the value, the Const statement is the only place you need to make a change.
You can use Const only at module or procedure level. This means the declaration context for a variable must be a class,
structure, module, procedure, or block, and cannot be a source file, namespace, or interface. For more information, see
Declaration Contexts and Default Access Levels.
Local constants (inside a procedure) default to public access, and you cannot use any access modifiers on them. Class and
module member constants (outside any procedure) default to private access, and structure member constants default to public
access. You can adjust their access levels with the access modifiers.
Rules
Declaration Context. A constant declared at module level, outside any procedure, is a member constant; it is a member
of the class, structure, or module that declares it.
A constant declared at procedure level is a local constant; it is local to the procedure or block that declares it.
Attributes. You can apply attributes only to member constants, not to local constants. An attribute contributes
information to the assembly's metadata, which is not meaningful for temporary storage such as local constants.
Modifiers. By default, all constants are Shared, Static, and ReadOnly. You cannot use any of these keywords when
declaring a constant.
At procedure level, you cannot use Shadows or any access modifiers to declare local constants.
Multiple Constants. You can declare several constants in the same declaration statement, specifying the constantname
part for each one. Multiple constants are separated by commas.
Data Type Rules
Data Types. The Const statement can declare the data type of a variable. You can specify any data type or the name of
an enumeration.
Default Type. If you do not specify datatype, the constant takes the data type of initializer. If you specify both datatype
and initializer, the data type of initializer must be convertible to datatype. If neither datatype nor initializer is present, the
data type defaults to Object.
Different Types. You can specify different data types for different constants by using a separate As clause for each
variable you declare. However, you cannot declare several constants to be of the same type by using a common As
clause.
Initialization. You must initialize the value of every constant in constantlist. You use initializer to supply an expression
to be assigned to the constant. The expression can be any combination of literals, other constants that are already
defined, and enumeration members that are already defined. You can use arithmetic and logical operators to combine
such elements.
You cannot use variables or functions in initializer. However, you can use conversion keywords such as CByte and
CShort. You can also use AscW if you call it with a constant String or Char argument, since that can be evaluated at
compile time.
Behavior
Scope. Local constants are accessible only from within their procedure or block. Member constants are accessible from
anywhere within their class, structure, or module.
Qualification. Code outside a class, structure, or module must qualify a member constant's name with the name of that
class, structure, or module. Code outside a procedure or block cannot refer to any local constants within that procedure
or block.
Example
The following example uses the Const statement to declare constants for use in place of literal values.
VB
' The following statements declare constants.
Const maximum As Long = 459
Public Const helpString As String = "HELP"
Private Const startValue As Integer = 5
If you define a constant with data type Object, the Visual Basic compiler gives it the type of initializer, instead of Object. In the
following example, the constant naturalLogBase has the run-time type Decimal.
VB
Const naturalLogBase As Object = CDec(2.7182818284)
MsgBox("Run-time type of constant naturalLogBase is " & _
naturalLogBase.GetType.ToString())
The preceding example uses the ToString method on the Type object returned by the GetType Operator, because Type cannot
be converted to String using CStr.
See Also
Reference
Enum Statement (Visual Basic)
#Const Directive
Dim Statement (Visual Basic)
ReDim Statement (Visual Basic)
Type Conversion Functions
Asc, AscW Functions
Concepts
Implicit and Explicit Conversions
Intrinsic Constants and Enumerations
Other Resources
Constants and Enumerations in Visual Basic
Visual Basic Language Reference
Remarks
You can transfer from inside a Do, For, or While loop to the next iteration of that loop. Control passes immediately to the loop
condition test, which is equivalent to transferring to the For or While statement, or to the Do or Loop statement that contains
the Until or While clause.
You can use Continue at any place in the loop that permits transfers. The rules allowing transfer of control are the same as
with the GoTo Statement.
For example, if a loop is totally contained within a Try block, a Catch block, or a Finally block, you can use Continue to
transfer out of the loop. If, on the other hand, the Try...End Try structure is contained within the loop, you cannot use
Continue to transfer control out of the Finally block, and you can use it to transfer out of a Try or Catch block only if you
transfer completely out of the Try...End Try structure.
If you have nested loops of the same type, for example a Do loop within another Do loop, a Continue Do statement skips to
the next iteration of the innermost Do loop that contains it. You cannot use Continue to skip to the next iteration of a
containing loop of the same type.
If you have nested loops of different types, for example a Do loop within a For loop, you can skip to the next iteration of either
loop by using either Continue Do or Continue For.
Example
The following code example uses the Continue While statement to skip to the next column of an array if a divisor is zero. The
Continue While is inside a For loop. It transfers to the While col < lastcol statement, which is the next iteration of the
innermost While loop that contains the For loop.
VB
Dim row, col As Integer
Dim lastrow As Integer = 6
Dim lastcol As Integer = 10
Dim a(,) As Double = New Double(lastrow, lastcol) {}
Dim b(7) As Double
row = -1
While row < lastrow
row += 1
col = -1
While col < lastcol
col += 1
a(row, col) = 0
For i As Integer = 0 To b.GetUpperBound(0)
If b(i) = col Then
Continue While
Else
a(row, col) += (row + b(i)) / (col - b(i))
End If
Next i
End While
End While
See Also
Tasks
How to: Skip to the Next Iteration of a Loop
Reference
Do...Loop Statement (Visual Basic)
For...Next Statement (Visual Basic)
While...End While Statement (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
Visual Basic Language Reference
Declare Statement
Declares a reference to a procedure implemented in an external file.
Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
Shadows
Optional. See Shadows.
charsetmodifier
Optional. Specifies character set and file search information. Can be one of the following:
Ansi (default)
Unicode (Visual Basic)
Auto
Sub
Optional, but either Sub or Function must appear. Indicates that the external procedure does not return a value.
Function
Optional, but either Sub or Function must appear. Indicates that the external procedure returns a value.
name
Required. Name of this external reference. For more information, see Declared Element Names.
Lib
Required. Introduces a Lib clause, which specifies the file that contains the procedure being declared.
libname
Required. Name of the file that contains the declared procedure.
Alias
Optional. Indicates that the procedure being declared cannot be identified within its file by the name specified in name. You
specify its identification in aliasname.
aliasname
Required if you use the Alias keyword. String that identifies the procedure in one of two ways:
The entry point name of the procedure within its file, within quotes ("")
-or-
A number sign (#) followed by an integer specifying the ordinal number of the procedure's entry point within its file
parameterlist
Required if the procedure takes parameters. See Parameter List.
returntype
Required if Function is specified and Option Strict is On. Data type of the value returned by the procedure.
Remarks
Sometimes you need to call a procedure defined in a file (such as a DLL or code resource) outside your project. When you do
this, the Visual Basic compiler does not have access to the information it needs to call the procedure correctly, such as where
the procedure is located, how it is identified, its calling sequence and return type, and the string character set it uses. The
Declare statement creates a reference to an external procedure and supplies this necessary information.
You can use Declare only at module level. This means the declaration context for an external reference must be a class,
structure, or module, and cannot be a source file, namespace, interface, procedure, or block. For more information, see
Declaration Contexts and Default Access Levels.
External references default to Public (Visual Basic) access. You can adjust their access levels with the access modifiers.
Rules
Attributes. You can apply attributes to an external reference. Any attribute you apply has effect only in your project, not
in the external file.
Modifiers. External procedures are implicitly Shared (Visual Basic). You cannot use the Shared keyword when declaring
an external reference, and you cannot alter its shared status.
An external procedure cannot participate in overriding, implement interface members, or handle events. Accordingly, you
cannot use the Overrides, Overridable, NotOverridable, MustOverride, Implements, or Handles keyword in a
Declare statement.
External Procedure Name. You do not have to give this external reference the same name (in name) as the procedure's
entry-point name within its external file (aliasname). You can use an Alias clause to specify the entry-point name. This
can be useful if the external procedure has the same name as a Visual Basic reserved modifier or a variable, procedure, or
any other programming element in the same scope.
Note
Entry-point names in most DLLs are case-sensitive.
External Procedure Number. Alternatively, you can use an Alias clause to specify the ordinal number of the entry
point within the export table of the external file. To do this, you begin aliasname with a number sign (#). This can be
useful if any character in the external procedure name is not allowed in Visual Basic, or if the external file exports the
procedure without a name.
Data Type Rules
Parameter Data Types. If Option Strict is On, you must specify the data type of each parameter in parameterlist. This
can be any data type or the name of an enumeration, structure, class, or interface. Within parameterlist, you use an As
clause to specify the data type of the argument to be passed to each parameter.
Note
If the external procedure was not written for the .NET Framework, you must take care that the data types correspond. F
or example, if you declare an external reference to a Visual Basic 6.0 procedure with an Integer parameter (16 bits in Vi
sual Basic 6.0), you must identify the corresponding argument as Short in the Declare statement, because that is the 1
6-bit integer type in Visual Basic. Similarly, Long has a different data width in Visual Basic 6.0, and Date is implemente
d differently.
Return Data Type. If the external procedure is a Function and Option Strict is On, you must specify the data type of
the value returned to the calling code. This can be any data type or the name of an enumeration, structure, class, or
interface.
Note
The Visual Basic compiler does not verify that your data types are compatible with those of the external procedure. If th
ere is a mismatch, the common language runtime generates a MarshalDirectiveException exception at run time.
Default Data Types. If Option Strict is Off and you do not specify the data type of a parameter in parameterlist, the
Visual Basic compiler converts the corresponding argument to the Object Data Type. Similarly, if you do not specify
returntype, the compiler takes the return data type to be Object.
Note
Because you are dealing with an external procedure that might have been written on a different platform, it is dangero
us to make any assumptions about data types or to allow them to default. It is much safer to specify the data type of ev
ery parameter and of the return value, if any. This also improves the readability of your code.
Behavior
Scope. An external reference is in scope throughout its class, structure, or module.
Lifetime. An external reference has the same lifetime as the class, structure, or module in which it is declared.
Calling an External Procedure. You call an external procedure the same way you call a Function or Sub procedure—
by using it in an expression if it returns a value, or by specifying it in a Call Statement (Visual Basic) if it does not return a
value.
You pass arguments to the external procedure exactly as specified by parameterlist in the Declare statement. Do not
take into account how the parameters were originally declared in the external file. Similarly, if there is a return value, use
it exactly as specified by returntype in the Declare statement.
Character Sets. You can specify in charsetmodifier how Visual Basic should marshal strings when it calls the external
procedure. The Ansi modifier directs Visual Basic to marshal all strings to ANSI values, and the Unicode modifier directs
it to marshal all strings to Unicode values. The Auto modifier directs Visual Basic to marshal strings according to .NET
Framework rules based on the external reference name, or aliasname if specified. The default value is Ansi.
charsetmodifier also specifies how Visual Basic should look up the external procedure within its external file. Ansi and
Unicode both direct Visual Basic to look it up without modifying its name during the search. Auto directs Visual Basic to
determine the base character set of the run-time platform and possibly modify the external procedure name, as follows:
On an ANSI platform, such as Windows 95, Windows 98, or Windows Millennium Edition, first look up the
external procedure with no name modification. If that fails, append "A" to the end of the external procedure name
and look it up again.
On a Unicode platform, such as Windows NT, Windows 2000, or Windows XP, first look up the external
procedure with no name modification. If that fails, append "W" to the end of the external procedure name and
look it up again.
Mechanism. Visual Basic uses the .NET Framework platform invoke (PInvoke) mechanism to resolve and access external
procedures. The Declare statement and the DllImportAttribute class both use this mechanism automatically, and you do
not need any knowledge of PInvoke. For more information, see Walkthrough: Calling Windows APIs.
Security Note
If the external procedure runs outside the common language runtime (CLR), it is unmanaged code. When you call such a pro
cedure, for example a Win32 API function or a COM method, you might expose your application to security risks. For more in
formation, see Unmanaged Code.
Example
The following example declares an external reference to a Function procedure that returns the current user name. It then calls
the external procedure GetUserNameA as part of the getUser procedure.
VB
Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA" _
(ByVal lpBuffer As String, ByRef nSize As Integer) As Integer
Sub getUser()
Dim buffer As String = New String(CChar(" "), 25)
Dim retVal As Integer = getUserName(buffer, 25)
Dim userName As String = Strings.Left(buffer, InStr(buffer, Chr(0)) - 1)
MsgBox(userName)
End Sub
The DllImportAttribute provides an alternative way of using functions in unmanaged code. The following example declares
an imported function without using a Declare statement.
VB
' Add an Imports statement at the top of the class, structure, or
' module that uses the DllImport attribute.
Imports System.Runtime.InteropServices
VB
<DllImportAttribute("kernel32.dll", EntryPoint:="MoveFileW", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function moveFile(ByVal src As String, _
ByVal dst As String) As Boolean
' This function copies a file from the path src to the path dst.
' Leave this function empty. The DLLImport attribute forces calls
' to moveFile to be forwarded to MoveFileW in KERNEL32.DLL.
End Function
See Also
Tasks
Walkthrough: Calling Windows APIs
Reference
Imports Statement
AddressOf Operator
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Parameter List
Call Statement (Visual Basic)
LastDllError Property (Err Object)
Concepts
Data Type Changes for Visual Basic 6.0 Users
Integer Data Type for Visual Basic 6.0 Users
Visual Basic Language Reference
Delegate Statement
Used to declare a delegate. A delegate is a reference type that refers to a Shared method of a type or to an instance method of
an object. Any procedure with matching parameter types and return type may be used to create an instance of this delegate
class. The procedure can then later be invoked by means of the delegate instance.
[ <attrlist> ] [ accessmodifier ] _
[ Shadows ] Delegate [ Sub | Function ] name [( Of typeparamlist )] [([ parameterlist ])] [
As type ]
Parts
attrlist
Optional. List of attributes that apply to this delegate. Multiple attributes are separated by commas. You must enclose the
Attribute List in angle brackets ("<" and ">").
accessmodifier
Optional. Specifies what code can access the delegate. Can be one of the following:
Public. Any code that can access the element that declares the delegate can access it.
Protected. Only code within the delegate's class or a derived class can access it.
Friend. Only code within the same assembly can access the delegate.
Private. Only code within the element that declares the delegate can access it.
You can specify Protected Friend to allow access from code within the delegate's class, a derived class, or the same
assembly.
Shadows
Optional. Indicates that this delegate redeclares and hides an identically named programming element, or set of overloaded
elements, in a base class. You can shadow any kind of declared element with any other kind.
A shadowed element is unavailable from within the derived class that shadows it, except from where the shadowing element
is inaccessible. For example, if a Private element shadows a base class element, code that does not have permission to
access the Private element accesses the base class element instead.
Sub
Optional, but either Sub or Function must appear. Declares this procedure as a delegate Sub procedure that does not return
a value.
Function
Optional, but either Sub or Function must appear. Declares this procedure as a delegate Function procedure that returns a
value.
name
Required. Name of the delegate type; follows standard variable naming conventions.
typeparamlist
Optional. List of type parameters for this delegate. Multiple type parameters are separated by commas. You must enclose the
Type List in parentheses and introduce it with the Of keyword.
parameterlist
Optional. List of parameters that are passed to the procedure when it is called. You must enclose the Parameter List in
parentheses.
type
Required if you specify a Function procedure. Data type of the return value.
Remarks
The Delegate statement defines the parameter types and return type of a delegate class. Any procedure with matching
parameters types and return type may be used to create an instance of this delegate class. The procedure can then later be
invoked by means of the delegate instance, by calling the delegate's Invoke method.
Delegates can be declared at the namespace, module, class, or structure level, but not within a procedure.
Each delegate class defines a constructor that is passed the specification of an object method. An argument to a delegate
constructor must be an expression of the form:
AddressOf [expression.]methodname
The compile-time type of the expression must be the name of a class or an interface that contains a method of the specified
name whose signature matches the signature of the delegate class. The methodname can be either a shared method or an
instance method. The methodname is not optional, even if you create a delegate for the default method of the class.
Example
The following example uses the Delegate statement to declare a delegate for operating on two numbers and returning a
number. The DelegateTest method takes an instance of a delegate of this type and uses it to operate on pairs of numbers.
VB
Delegate Function MathOperator( _
ByVal x As Double, _
ByVal y As Double _
) As Double
Function AddNumbers( _
ByVal x As Double, _
ByVal y As Double _
) As Double
Return x + y
End Function
Function SubtractNumbers( _
ByVal x As Double, _
ByVal y As Double _
) As Double
Return x - y
End Function
Sub DelegateTest( _
ByVal x As Double, _
ByVal op As MathOperator, _
ByVal y As Double _
)
Dim ret As Double
ret = op.Invoke(x, y) ' Call the method.
MsgBox(ret)
End Sub
See Also
Tasks
How to: Use a Generic Class
Reference
AddressOf Operator
Of
Concepts
Generic Types in Visual Basic
Other Resources
Delegates in Visual Basic
Visual Basic Language Reference
Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
Shared
Optional. See Shared.
Shadows
Optional. See Shadows.
Static
Optional. See Static.
ReadOnly
Optional. See ReadOnly.
WithEvents
Optional. Specifies that these are object variables that refer to instances of a class that can raise events. See WithEvents.
variablelist
Required. List of variables being declared in this statement.
variable [ , variable ... ]
Part Description
variablename Required. Name of the variable. See Declared Element Names.
New Optional. Creates a new instance of the class when the Dim statement runs.
Remarks
You should declare every variable you use in your program, to tell the Visual Basic compiler the variable's data type and other
information such as what code can access it. The following example declares a variable to hold an Integer value.
You can use Dim only at module or procedure level. This means the declaration context for a variable must be a class,
structure, module, procedure, or block, and cannot be a source file, namespace, or interface. For more information, see
Declaration Contexts and Default Access Levels.
If Option Explicit is On (the default), the compiler requires a declaration for every variable you use. If you turn Option
Explicit Off, every undeclared variable defaults to the Object Data Type, which might not be your intention.
You can specify each variable's data type in the Dim statement. You can also specify an initial value. If you do not, Visual Basic
uses default settings. For more information, see "Data Type Rules" and "Default Values" under "Detailed Information" on this
Help page. The following example declares and initializes a String variable.
You can specify what code can access a variable by supplying an accessmodifier in the Dim statement. For more information,
see "Modifiers" and "Access Level" under "Detailed Information" on this Help page.
You can declare a variable to hold an array, which can hold multiple values. For more information, see "Array Rules" under
"Detailed Information" on this Help page. For more information on arrays, see Arrays in Visual Basic. The following example
declares an Integer array variable.
In general, you should put all your Dim statements at the beginning of the code region in which you use the variables. For
more information, see "Troubleshooting" under "Detailed Information" on this Help page.
Detailed Information
This section covers the following areas in detail:
Declaration
Data types
Arrays
Behavior
Troubleshooting
Declaration Rules
Declaration Context. A variable declared at module level, outside any procedure, is a member variable or field; it is a
member of the class, structure, or module that declares it.
A variable declared at procedure level is a local variable; it is local to the procedure or block that declares it.
Attributes. You can apply attributes only to member variables, not to local variables. An attribute contributes
information to the assembly's metadata, which is not meaningful for temporary storage such as local variables.
Implicit Use of Dim. If you specify any of the modifiers Public, Protected, Friend, Protected Friend, Private, Shared,
Shadows, Static, ReadOnly, or WithEvents, you can optionally omit the Dim keyword.
Default Type. If you do not specify datatype, the variable takes the data type of initializer. If neither datatype nor
initializer is present, the data type defaults to the Object Data Type. If you specify both datatype and initializer, the data
type of initializer must be convertible to datatype.
Different Types. You can specify different data types for different variables by using a separate As clause for each
variable you declare. Alternatively, you can declare several variables to be of the same type by using a common As
clause. Each variable takes the data type specified in the first As clause encountered after its variablename part.
Initialization. The Dim statement can initialize the contents of selected variables in variablelist. For a value type, you
use initializer to supply an expression to be assigned to the variable. The expression must evaluate to a constant that can
be calculated at compile time.
For a reference type, you use the New keyword to create a new instance of the class or structure specified by datatype. If
you use New, you do not use an initializer expression. Instead, you supply arguments, if required, to the constructor of
the class from which you are creating the variable.
If you declare more than one variable with the same As clause, you cannot supply an initializer for that group of
variables.
Array Rules
Array Variables. To specify that a variable in variablelist is an array, you follow its variablename immediately with
parentheses. If the array has more than one dimension, you must include commas between the parentheses to indicate
the number of dimensions.
The following statement declares a two-dimensional array of type Double. The array has 4 rows (3 + 1) of 6 columns (5
+ 1) each.
Note that an upper bound represents the highest possible value for that index, not the length of that dimension, which is
the upper bound plus one.
Blank Array Bounds. You can leave all the bounds blank in an array declaration. If you do this, the array has the number
of dimensions you specify, but it is uninitialized, so it has a value of Nothing until you initialize at least some of its
elements. The Dim statement must specify bounds either for all dimensions or for none of them.
Empty Arrays. It is possible to use -1 to declare the upper bound of an array dimension. This signifies that the array is
empty but not Nothing, a distinction required by certain common language runtime functions. However, Visual Basic
code cannot successfully access such an array. If you attempt to do so, an IndexOutOfRangeException error occurs during
execution. For more information, see How to: Create an Array with No Elements.
Array Initialization. You can initialize the values of an array by surrounding the initialization values with braces ({}).
For multidimensional arrays, the initialization for each separate dimension is surrounded by braces within the outer
dimension. The elements are specified in row-major order.
Behavior
Default Values. If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data
type. The following table shows the default initialization values.
Data type Default value
All numeric types (including Byte and SByte) 0
Char Binary 0
All reference types (including Object, String, and all array Nothing
s)
Boolean False
Date 12:00 AM of January 1 of the year 1 (01/01/0001 12:00:00 A
M)
Each element of a structure is initialized as if it were a separate variable. If you declare the length of an array but do not
initialize its elements, each element is initialized as if it were a separate variable.
Access Level. Local variables (inside a procedure) default to public access, and you cannot use any access modifiers on
them.
Class and module member variables (outside any procedure) default to private access, and structure member variables
default to public access. You can adjust their access levels with the access modifiers.
Scope. Local variables are in scope only within their procedure or block. Member variables are in scope throughout their
class, structure, or module.
Qualification. Code outside a class, structure, or module must qualify a member variable's name with the name of that
class, structure, or module. Code outside a procedure or block cannot refer to any local variables within that procedure or
block.
Lifetime. A Static local variable has a longer lifetime than that of the procedure in which it is declared. The boundaries
of the variable's lifetime depend on where the procedure is declared and whether or not it is Shared.
Procedure declarat Variable initialized Variable ceases to exist
ion
In a module The first time the procedure is called When your program terminates exe
cution
In a class or structure The first time the procedure is called either on a specific insta When your program terminates exe
, Shared nce or on the class or structure itself cution
In a class or structure The first time the procedure is called on a specific instance When the instance is released for ga
, not Shared rbage collection (GC)
Troubleshooting
Execution Order. The Dim statement is not itself an executable statement. However, if it initializes one or more
variables, the initializations are treated as assignment statements. This means that a variable's value undergoes the
following steps:
1. On the first entry into the code element declaring the variable, Visual Basic initializes it to the default value for its
data type.
2. When execution arrives at the variable's Dim statement, Visual Basic initializes it to the value supplied in the Dim
statement.
3. Whenever execution returns to the variable's Dim statement, Visual Basic sets it once again to the value supplied in
the Dim statement.
This has the following implications when you use a Dim statement to initialize a variable:
If you use the variable before executing the Dim statement, its value is the default for its data type, not the value
supplied in the Dim statement.
If execution never reaches the Dim statement, the variable is never initialized to the value supplied in the Dim
statement.
If you alter the value but then return to the Dim statement, your altered value is replaced by the value supplied in
the Dim statement.
If you put all your Dim statements at the beginning of the code region in which they appear, for example a module or a
procedure, your code initializes them as you intend.
Example
The following example declares variables using the Dim statement with various options.
VB
' The following statement declares and initializes a Long variable.
Dim startingAmount As Long = 500
VB
' The following statement declares a variable that refers to a Button
' object, creates a new Button object, and assigns it to the variable.
Dim switchButton As New System.Windows.Forms.Button
VB
' The following statement declares a variable that can only be
' accessed by code in the same class, structure, or module.
Private homeTelephone As String = ""
VB
' The following statement declares a local variable that always retains
' its value, even after its procedure returns to the calling code.
Static totalSales As Double
VB
' The following statement declares a variable that refers to an array.
Dim highTemperature(31) As Integer
VB
' The following statement declares and initializes an array variable
' that holds 4 Boolean check values.
Dim checkValues() As Boolean = {False, False, True, False}
See Also
Tasks
How to: Declare an Array Variable
How to: Declare an Array Variable
Reference
Const Statement (Visual Basic)
ReDim Statement (Visual Basic)
Option Explicit Statement (Visual Basic)
Concepts
Variable Declaration in Visual Basic
Visual Basic Language Reference
Parts
While
Required unless Until is used. Repeat the loop until condition is False.
Until
Required unless While is used. Repeat the loop until condition is True.
condition
Optional. Boolean expression. If condition is Nothing, Visual Basic treats it as False.
statements
Optional. One or more statements that are repeated while, or until, condition is True.
Exit Do
Optional. Transfers control out of the Do loop.
Loop
Required. Terminates the definition of the Do loop.
Remarks
Use a Do...Loop structure when you want to repeat a set of statements an indefinite number of times, until a condition is
satisfied. If you want to repeat the statements a set number of times, the For...Next Statement is usually a better choice.
The Do...Loop structure gives you more flexibility than the While...End While Statement (Visual Basic) because it allows you to
choose whether to end the loop when condition stops being True or when it first becomes True. It also allows you to test
condition at either the beginning or the end of the loop.
Rules
Nature of Condition. The condition usually results from a comparison of two values, but it can be any expression that
evaluates to a Boolean Data Type (Visual Basic) value (True or False). This includes values of other data types, such as
numeric types, that have been converted to Boolean.
Testing the Condition. You can test condition only once, at either the beginning or the end of the loop. You can use
either While or Until to specify condition, but not both.
Number of Iterations. If you test condition at the beginning of the loop (in the Do statement), the loop might never run
even once. If you test at the end of the loop (in the Loop statement), the loop always runs at least once.
Nesting Loops. You can nest Do loops by placing one loop within another. You can also nest different kinds of control
structures within one another. For more information, see Nested Control Structures.
Transferring Out of the Loop. The Exit Statement (Visual Basic) transfers control immediately to the statement
following the Loop statement. You might want to exit a loop if you detect a condition that makes it unnecessary or
impossible to continue iterating, such as an erroneous value or a termination request. You can place any number of Exit
Do statements anywhere in the Do loop. Exit Do is often used after evaluating some condition, for example in an
If...Then...Else structure.
Endless Loops
One use of Exit Do is to test for a condition that could cause an endless loop, which is a loop that could run an extremely large
or even infinite number of times. If you detect such a condition, you can use Exit Do to escape the loop. Otherwise, the loop
continues running.
In the following example, number is assigned a value that could cause the loop to run more than 2 ^ 31 times. The If statement
checks for this condition and exits if it exists, preventing endless looping.
VB
Sub exitDoExample()
Dim counter As Integer = 0
Dim number As Integer = 8
Do Until number = 10
If number <= 0 Then Exit Do
number -= 1
counter += 1
Loop
MsgBox("The loop ran " & counter & " times.")
End Sub
Note
To stop an endless loop, press ESC or CTRL+BREAK.
Example
The following example illustrates nested Do...Loop structures, as well as the use of While and Until, and testing at the
beginning (Do statement) and end (Loop statement) of the loop.
VB
Dim check As Boolean = True
Dim counter As Integer = 0
Do
Do While counter < 20
counter += 1
If counter = 10 Then
check = False
Exit Do
End If
Loop
Loop Until check = False
End Sub
In the preceding example, the inner Do...Loop structure loops 10 times, sets the value of the flag to False, and exits
prematurely using the Exit Do statement. The outer loop exits immediately upon checking the value of the flag.
See Also
Tasks
How to: Improve the Performance of a Loop
Reference
For...Next Statement (Visual Basic)
Boolean Data Type (Visual Basic)
Exit Statement (Visual Basic)
While...End While Statement (Visual Basic)
Concepts
Loop Structures
Nested Control Structures
Visual Basic Language Reference
End Statement
Terminates execution immediately.
End
Remarks
You can place the End statement anywhere in a procedure to force the entire application to stop running. End closes any files
opened with an Open statement and clears all the application's variables. The application closes as soon as there are no other
programs holding references to its objects and none of its code is running.
Note
The End statement stops code execution abruptly, without invoking the Dispose or Finalize method, or any other Visual Bas
ic code. Object references held by other programs are invalidated. If an End statement is encountered within a Try or Catch
block, control does not pass to the corresponding Finally block.
The Stop statement suspends execution, but unlike End, it does not close any files or clear any variables, unless it is
encountered in a compiled executable (.exe) file.
Because End terminates your application without attending to any resources that might be open, you should try to close down
cleanly before using it. For example, if your application has any forms open, you should close them before control reaches the
End statement.
You should use End sparingly, and only when you need to stop immediately. The normal ways to terminate a procedure
(Return Statement (Visual Basic) and Exit Statement (Visual Basic)) not only close down the procedure cleanly but also give the
calling code the opportunity to close down cleanly. A console application, for example, can simply Return from the Main
procedure.
Security Note
The End statement calls the Exit method of the Environment class in the System namespace. Exit requires that you have
UnmanagedCode permission. If you do not, a SecurityException error occurs.
When followed by an additional keyword, End (Visual Basic) delineates the end of the definition of the appropriate procedure
or block. For example, End Function terminates the definition of a Function procedure.
Example
The following example uses the End statement to terminate code execution if the user requests it.
VB
Sub Form_Load()
Dim answer As MsgBoxResult
answer = MsgBox("Do you want to quit now?", MsgBoxStyle.YesNo)
If answer = MsgBoxResult.Yes Then
MsgBox("Terminating program")
End
End If
End Sub
Parts
attribute list
Optional. List of attributes that apply to this enumeration. You must enclose the Attribute List in angle brackets ("<" and ">").
access modifier
Optional. Specifies what code can access this enumeration. Can be one of the following:
Public
Protected
Friend
Private
You can specify Protected Friend to allow access from code within the enumeration's class, a derived class, or the same
assembly.
Shadows
Optional. Specifies that this enumeration redeclares and hides an identically named programming element, or set of
overloaded elements, in a base class. You can specify Shadows only on the enumeration itself, not on any of its members.
enumeration name
Required. Name of the enumeration. For information on valid names, see Declared Element Names.
data type
Required if Option Strict is On. Data type of the enumeration and all its members.
member list
Required. List of member constants being declared in this statement. Multiple members appear on individual source code
lines.
Each member has the following syntax and parts: [<attribute list>] member name [ = initializer ]
Part Description
member name Required. Name of this member.
initializer Optional. Expression that is evaluated at compile time and assigned to this member.
End Enum
Terminates the Enum block.
Remarks
If you have a set of unchanging values that are logically related to each other, you can define them together in an enumeration.
This provides meaningful names for the enumeration and its members, which are easier to remember than their values. You
can then use the enumeration members in many places in your code. This also improves the readability of your code because
all the related values use the same enumeration name.
You can use Enum only at namespace or module level. This means the declaration context for an enumeration must be a
source file, namespace, class, structure, module, or interface, and cannot be a procedure. For more information, see
Declaration Contexts and Default Access Levels.
The Enum statement can declare the data type of an enumeration. Each member takes the enumeration's data type. You can
specify Byte, Integer, Long, SByte, Short, UInteger, ULong, or UShort.
If you do not specify initializer for a member, Visual Basic initializes it either to zero (if it is the first member in member list), or
to a value greater by one than that of the immediately preceding member.
Class, structure, module, and interface member enumerations default to public access. You can adjust their access levels with
the access modifiers. Namespace member enumerations default to friend access. You can adjust their access levels to public,
but not to private or protected. For more information, see Access Levels in Visual Basic.Rules
Declaration Context. An enumeration declared at module level, outside any procedure, is a member enumeration; it is
a member of the class, structure, module, or interface that declares it.
An enumeration declared at namespace level, outside any class, structure, module, or interface, is a member only of the
namespace in which it appears.
Attributes. You can apply attributes to an enumeration as a whole, but not to its members individually. An attribute
contributes information to the assembly's metadata.
Modifiers. By default, all enumerations are types and their fields are constants. Therefore the Shared, Static, and
ReadOnly keywords cannot be used when declaring an enumeration or its members.
Data Type Rules
Default Type. If you do not specify data type for the enumeration, each member takes the data type of its initializer. If
you specify both data type and initializer, the data type of initializer must be convertible to data type. If neither data type
nor initializer is present, the data type defaults to Integer.
Initialization. The Enum statement can initialize the contents of selected members in member list. You use initializer to
supply an expression to be assigned to the member.
The expression supplied in each initializer can be any combination of literals, other constants that are already defined,
and enumeration members that are already defined, including a previous member of this enumeration. You can use
arithmetic and logical operators to combine such elements.
You cannot use variables or functions in initializer. However, you can use conversion keywords such as CByte and
CShort. You can also use AscW if you call it with a constant String or Char argument, since that can be evaluated at
compile time.
Behavior
Access Level. All enumeration members have public access, and you cannot use any access modifiers on them.
However, if the enumeration itself has a more restricted access level, the specified enumeration access level takes
precedence..
Scope. Member enumerations are accessible from anywhere within their class, structure, module, or interface.
Namespace member enumerations are accessible from any code within that namespace.
Qualification. Code outside a class, structure, or module must qualify a member enumeration's name with the name of
that class, structure, or module.
Invalid Values. If the value of a member exceeds the allowable range for the underlying data type, or if you initialize any
member to the maximum value allowed by the underlying data type, the compiler reports an error.
Enumeration variables are variables declared to be of an Enum type. Declaring a variable in this way helps you to control the
values you assign to it. However, you can still assign a value that is not an enumeration member, provided its data type can be
converted to the enumeration's data type. This is useful when the enumeration is a flag field and you assign a combination of
flags to the enumeration variable. The following example shows an assignment of multiple flags to an enumeration variable.
VB
Enum filePermissions
create = 1
read = 2
write = 4
delete = 8
End Enum
VB
Dim file1Perm As filePermissions
file1Perm = filePermissions.create Or filePermissions.read
You must qualify every reference to an enumeration member, either with the name of an enumeration variable or with the
enumeration name itself. For example, in the preceding example, you can refer to the first member asfilePermissions.create,
but not as create.
Example
The following example uses the Enum statement to define a related set of named constant values. In this case, the values are
colors you might choose to design data entry forms for a database.
VB
Public Enum InterfaceColors
MistyRose = &HE1E4FF&
SlateGray = &H908070&
DodgerBlue = &HFF901E&
DeepSkyBlue = &HFFBF00&
SpringGreen = &H7FFF00&
ForestGreen = &H228B22&
Goldenrod = &H20A5DA&
Firebrick = &H2222B2&
End Enum
The following example shows values that include both positive and negative numbers.
VB
Enum SecurityLevel
IllegalEntry = -1
MinimumSecurity = 0
MaximumSecurity = 1
End Enum
See Also
Reference
Const Statement (Visual Basic)
Dim Statement (Visual Basic)
Type Conversion Functions
Asc, AscW Functions
Concepts
Implicit and Explicit Conversions
Intrinsic Constants and Enumerations
Other Resources
Constants and Enumerations in Visual Basic
Visual Basic Language Reference
Erase arraylist
Parts
arraylist
Required. List of array variables to be erased. Multiple variables are separated by commas.
Remarks
The Erase statement can appear only at procedure level. This means you can release arrays inside a procedure but not at class
or module level.
The Erase statement is equivalent to assigning Nothing to each array variable.
Example
The following example uses the Erase statement to clear two arrays and free their memory (1000 and 100 storage elements,
respectively). The ReDim statement then assigns a new array instance to the three-dimensional array.
VB
Dim threeDimArray(9, 9, 9), twoDimArray(9, 9) As Integer
Erase threeDimArray, twoDimArray
ReDim threeDimArray(4, 4, 9)
See Also
Reference
Nothing (Visual Basic)
ReDim Statement (Visual Basic)
Visual Basic Language Reference
Error Statement
Simulates the occurrence of an error.
Error errornumber
Parts
errornumber
Required. Can be any valid error number.
Remarks
The Error statement is supported for backward compatibility. In new code, especially when creating objects, use the Err object's
Raise method to generate run-time errors.
If errornumber is defined, the Error statement calls the error handler after the properties of the Err object are assigned the
following default values:
Propert Value
y
Numbe Value specified as argument to Error statement. Can be any valid error number.
r
Descrip String expression corresponding to the return value of the Error function for the specified Number, if this string exist
tion s. If the string does not exist, Description contains a zero-length string ("").
HelpFil The fully qualified drive, path, and file name of the appropriate Visual Basic Help file.
e
HelpCo The appropriate Visual Basic Help file context ID for the error corresponding to the Number property.
ntext
LastDL Zero.
LError
If no error handler exists, or if none is enabled, an error message is created and displayed from the Err object properties.
Note
Some Visual Basic host applications cannot create objects. See your host application's documentation to determine whether i
t can create classes and objects.
Example
This example uses the Error statement to generate error number 11.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Get Information about Visual Basic Run-Time Errors
Reference
Clear Method (Err Object)
Err Object (Visual Basic)
On Error Statement (Visual Basic)
Raise Method (Err Object)
Resume Statement
Visual Basic Language Reference
Event Statement
Declares a user-defined event.
[ <attrlist> ] [ accessmodifier ] _
[ Shared ] [ Shadows ] Event eventname[(parameterlist)] _
[ Implements implementslist ]
' -or-
[ <attrlist> ] [ accessmodifier ] _
[ Shared ] [ Shadows ] Event eventname As delegatename _
[ Implements implementslist ]
' -or-
[ <attrlist> ] [ accessmodifier ] _
[ Shared ] [ Shadows ] Custom Event eventname As delegatename _
[ Implements implementslist ]
[ <attrlist> ] AddHandler(ByVal value As delegatename)
[ statements ]
End AddHandler
[ <attrlist> ] RemoveHandler(ByVal value As delegatename)
[ statements ]
End RemoveHandler
[ <attrlist> ] RaiseEvent(delegatesignature)
[ statements ]
End RaiseEvent
End Event
Parts
Part Description
attrlist Optional. List of attributes that apply to this event. Multiple attributes are separated by commas. You must enclose the
Attribute List in angle brackets ("<" and ">").
accessm Optional. Specifies what code can access the event. Can be one of the following:
odifier
Public—any code that can access the element that declares it can access it.
Protected—only code within its class or a derived class can access it.
Friend—only code within the same assembly can access it.
Private—only code within the element that declares it can access it.
You can specify Protected Friend to allow access from code within the event's class, a derived class, or the same ass
embly.
Shared Optional. Specifies that this event is not associated with a specific instance of a class or structure.
Shado Optional. Indicates that this event redeclares and hides an identically named programming element, or set of overloa
ws ded elements, in a base class. You can shadow any kind of declared element with any other kind.
A shadowed element is unavailable from within the derived class that shadows it, except from where the shadowing e
lement is inaccessible. For example, if a Private element shadows a base-class element, code that does not have perm
ission to access the Private element accesses the base-class element instead.
eventna Required. Name of the event; follows standard variable naming conventions.
me
parame Optional. List of local variables representing the parameters of this event. You must enclose the Parameter List in pare
terlist ntheses.
Imple Optional. Indicates that this event implements an event of an interface.
ments
implem Required if Implements is supplied. List of Sub procedures being implemented. Multiple procedures are separated b
entslist y commas:
implementedprocedure [ , implementedprocedure ... ]
Each implementedprocedure has the following syntax and parts:
interface.definedname
Part Description
interfac Required. Name of an interface that this procedure's containing class or structure is implementing.
e
defined Required. Name by which the procedure is defined in interface. This does not have to be the same as name, t
name he name that this procedure is using to implement the defined procedure.
Custo Required. Events declared as Custom must define custom AddHandler, RemoveHandler, and RaiseEvent accessor
m s.
delegat Optional. The name of a delegate that specifies the event-handler signature.
ename
AddHa Required. Declares an AddHandler accessor, which specifies the statements to execute when an event handler is add
ndler ed, either explicitly using the AddHandler statement or implicitly using the Handles clause.
Remov Required. Declares a RemoveHandler accessor, which specifies the statements to execute when an event handler is r
eHandl emoved using the RemoveHander statement.
er
RaiseE Required. Declares a RaiseEvent accessor, which specifies the statements to execute when the event is raised using t
vent he RaiseEvent statement. Typically, this invokes a list of delegates maintained by the AddHandler and RemoveHan
dler accessors.
delegat Required. List of parameters that matches the parameters required by the delegatename delegate. You must enclose t
esignat he Parameter List in parentheses.
ure
stateme Optional. Statements that contain the bodies of the AddHandler, RemoveHander, and RaiseEvent methods.
nts
End Ev Required. Terminates the Event block.
ent
Remarks
Once the event has been declared, use the RaiseEvent statement to raise the event. A typical event might be declared and
raised as shown in the following fragments:
VB
Public Class EventSource
' Declare an event.
Public Event LogonCompleted(ByVal UserName As String)
Sub CauseEvent()
' Raise an event on successful logon.
RaiseEvent LogonCompleted("AustinSteele")
End Sub
End Class
Note
You can declare event arguments just as you do arguments of procedures, with the following exceptions: events cannot have
named arguments, ParamArray arguments, or Optional arguments. Events do not have return values.
To handle an event, you must associate it with an event handler subroutine using either the Handles or AddHandler
statement. The signatures of the subroutine and the event must match. To handle a shared event, you must use the
AddHandler statement.
You can use Event only at module level. This means the declaration context for an event must be a class, structure, module, or
interface, and cannot be a source file, namespace, procedure, or block. For more information, see
Declaration Contexts and Default Access Levels.
In most circumstances, you can use the first syntax in the Syntax section of this topic for declaring events. However, some
scenarios require that you have greater control over the detailed behavior of the event. The last syntax in the Syntax section of
this topic, which uses the Custom keyword, provides that control by allowing you to define custom events. In a custom event,
you specify exactly what happens when code adds or removes an event handler to or from the event, or when code raises the
event. For examples, see How to: Declare Events That Conserve Memory Use and How to: Declare Events That Avoid Blocking.
Example
The following example uses events to count down seconds from 10 to 0. The code illustrates several of the event-related
methods, properties, and statements, including the RaiseEvent statement.
The class that raises an event is the event source, and the methods that process the event are the event handlers. An event
source can have multiple handlers for the events it generates. When the class raises the event, that event is raised on every
class that has elected to handle events for that instance of the object.
The example also uses a form (Form1) with a button (Button1) and a text box (TextBox1). When you click the button, the first
text box displays a countdown from 10 to 0 seconds. When the full time (10 seconds) has elapsed, the first text box displays
"Done".
The code for Form1 specifies the initial and terminal states of the form. It also contains the code executed when events are
raised.
To use this example, open a new Windows Forms project. Then add a button named Button1 and a text box named TextBox1 to
the main form, named Form1. Then right-click the form and click View Code to open the code editor.
Add a WithEvents variable to the declarations section of the Form1 class:
VB
Private WithEvents mText As TimerState
Add the following code to the code for Form1. Replace any duplicate procedures that may exist, such as Form_Load or
Button_Click.
VB
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Button1.Text = "Start"
mText = New TimerState
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
mText.StartCountdown(10.0, 0.1)
End Sub
Class TimerState
Public Event UpdateTime(ByVal Countdown As Double)
Public Event Finished()
Public Sub StartCountdown(ByVal Duration As Double, _
ByVal Increment As Double)
Dim Start As Double = DateAndTime.Timer
Dim ElapsedTime As Double = 0
Press F5 to run the preceding example, and click the button labeled Start. The first text box starts to count down the seconds.
When the full time (10 seconds) has elapsed, the first text box displays "Done".
Note
The My.Application.DoEvents method does not process events in exactly the same way the form does. To allow the form t
o handle the events directly, you can use multithreading. For more information, see Multithreading in Visual Basic.
See Also
Tasks
How to: Add Events to a Class
How to: Declare Events That Conserve Memory Use
How to: Declare Events That Avoid Blocking
Reference
RaiseEvent Statement
Implements Statement
AddHandler Statement
RemoveHandler Statement
Handles
Delegate Statement
Shared (Visual Basic)
Shadows
Other Resources
Events in Visual Basic
Visual Basic Language Reference
Parts
Do
Immediately exits the Do loop in which it appears. Execution continues with the statement following the Loop statement.
Exit Do can be used only inside a Do loop. When used within nested Do loops, Exit Do exits the innermost loop and
transfers control to the next higher level of nesting.
For
Immediately exits the For loop in which it appears. Execution continues with the statement following the Next statement.
Exit For can be used only inside a For...Next or For Each...Next loop. When used within nested For loops, Exit For exits the
innermost loop and transfers control to the next higher level of nesting.
Function
Immediately exits the Function procedure in which it appears. Execution continues with the statement following the
statement that called the Function procedure. Exit Function can be used only inside a Function procedure.
Property
Immediately exits the Property procedure in which it appears. Execution continues with the statement that called the
Property procedure, that is, with the statement requesting or setting the property's value. Exit Property can be used only
inside a property's Get or Set procedure.
Select
Immediately exits the Select Case block in which it appears. Execution continues with the statement following the End
Select statement. Exit Select can be used only inside a Select Case statement.
Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement
that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.
Try
Immediately exits the Try or Catch block in which it appears. Execution continues with the Finally block if there is one, or
with the statement following the End Try statement otherwise. Exit Try can be used only inside a Try or Catch block, and
not inside a Finally block.
While
Immediately exits the While loop in which it appears. Execution continues with the statement following the End While
statement. Exit While can be used only inside a While loop. When used within nested While loops, Exit While transfers
control to the loop that is one nested level above the loop where Exit While occurs.
Remarks
Do not confuse Exit statements with End statements. Exit does not define the end of a statement.
Example
The following example uses the Exit statement to exit a For...Next loop, a Do loop, and a Sub procedure.
VB
Sub exitStatementDemo()
Dim demoNum As Single
' Set up an infinite loop.
Do
For i As Integer = 1 To 10000000
demoNum = Int(Rnd() * 100)
Select Case demoNum
Case 7 : Exit For
Case 29 : Exit Do
Case 54 : Exit Sub
End Select
Next i
Loop
End Sub
See Also
Reference
Do...Loop Statement (Visual Basic)
End Statement
For Each...Next Statement (Visual Basic)
For...Next Statement (Visual Basic)
Function Statement (Visual Basic)
Stop Statement (Visual Basic)
Sub Statement (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
For Each...Next Statement (Visual Basic)
Visual Basic Language Reference
F-P Statements
The following table contains a listing of Visual Basic language statements.
Parts
element
Required in the For Each statement. Optional in the Next statement. Variable. Used to iterate through the elements of the
collection.
datatype
Required if element is not already declared. Data type of element.
group
Required. Object variable. Refers to the collection over which the statements are to be repeated.
statements
Optional. One or more statements between For Each and Next that run on each item in group.
Exit For
Optional. Transfers control out of the For Each loop.
Next
Required. Terminates the definition of the For Each loop.
Remarks
Use a For Each...Next loop when you want to repeat a set of statements for each element of a collection or array.
A For...Next Statement (Visual Basic) works well when you can associate each iteration of a loop with a control variable and
determine that variable's initial and final values. However, when you are dealing with a collection, the concept of initial and
final values is not meaningful, and you do not necessarily know how many elements the collection has. In this case, a For
Each...Next loop is a better choice.
Rules
Data Types. The data type of element must be such that the data type of the elements of group can be converted to it.
The data type of group must be a reference type that refers to a collection or an array. This means that group must refer
to an object that implements the IEnumerable interface of the System.Collections namespace or the IEnumerable
interface of the System.Collections.Generic namespace. IEnumerable defines the GetEnumerator method, which returns
an enumerator object for the collection. The enumerator object implements the IEnumerator interface of the
System.Collections namespace and exposes the Current property and the Reset and MoveNext methods. Visual Basic
uses these to traverse the collection.
The elements of group are usually of type Object but can have any run-time data type.
Declaration. If element has not been declared outside this loop, you must declare it within the For Each statement. In
this case, the scope of element is the body of the loop. However, you cannot declare element both outside and inside the
loop.
Number of Iterations. Visual Basic evaluates the collection only once, before the loop begins. If your statement block
changes element or group, these changes do not affect the iteration of the loop.
Nesting Loops. You can nest For Each loops by placing one loop within another. However, each loop must have a
unique element variable.
You can also nest different kinds of control structures within one another. For more information, see
Nested Control Structures.
Note
If a Next statement of an outer nesting level is encountered before the Next of an inner level, the compiler signals an e
rror. However, the compiler can detect this overlapping error only if you specify element in every Next statement.
Identifying the Control Variable. You can optionally specify element in the Next statement. This improves the
readability of your program, especially if you have nested For Each loops. You must specify the same variable as the one
that appears in the corresponding For Each statement.
Transferring Out of the Loop. The Exit Statement (Visual Basic) transfers control immediately to the statement
following the Next statement. You might want to exit a loop if you detect a condition that makes it unnecessary or
impossible to continue iterating, such as an erroneous value or a termination request. Also, if you catch an exception in a
Try...Catch...Finally statement, you can use Exit For at the end of the Finally block.
You can place any number of Exit For statements anywhere in the For Each loop. Exit For is often used after evaluating
some condition, for example in an If...Then...Else structure.
Endless Loops. One use of Exit For is to test for a condition that could cause an endless loop, which is a loop that could
run an extremely large or even infinite number of times. If you detect such a condition, you can use Exit For to escape
the loop. For more information, see Do...Loop Statement (Visual Basic).
Behavior
Entry into the Loop. When execution of the For Each...Next loop begins, Visual Basic verifies that group refers to a
valid collection object. If not, it throws an exception. Otherwise, it calls the MoveNext method and the Current property
of the enumerator object to return the first element. If MoveNext indicates that there is no next element, that is, if the
collection is empty, then the For Each loop terminates and control passes to the statement following the Next statement.
Otherwise, Visual Basic sets element to the first element and runs the statement block.
Iterations of the Loop. Each time Visual Basic encounters the Next statement, it returns to the For Each statement.
Again it calls MoveNext and Current to return the next element, and again it either runs the block or terminates the
loop depending on the result. This process continues until MoveNext indicates that there is no next element or an Exit
For statement is encountered.
Termination of the Loop. When all the elements in the collection have been successively assigned to element, the For
Each loop terminates and control passes to the statement following the Next statement.
Changing Iteration Values. Changing the value of element while inside a loop can make it more difficult to read and
debug your code. Changing the value of group does not affect the collection or its elements, which were determined
when the loop was first entered.
Traversal Order. When you execute a For Each...Next loop, traversal of the collection is under the control of the
enumerator object returned by the GetEnumerator method. The order of traversal is not determined by Visual Basic, but
rather by the MoveNext method of the enumerator object. This means that you might not be able to predict which
element of the collection is the first to be returned in element, or which is the next to be returned after a given element.
If your code depends on traversing a collection in a particular order, a For Each...Next loop is not the best choice unless
you know the characteristics of the enumerator object the collection exposes. You might achieve more reliable results
using a different loop structure, such as For...Next or Do...Loop.
Modifying the Collection. The enumerator object returned by GetEnumerator normally does not allow you to alter
the collection by adding, deleting, replacing, or reordering any elements. If you alter the collection after you have initiated
a For Each...Next loop, the enumerator object becomes invalid, and the next attempt to access an element results in an
InvalidOperationException exception.
However, this blocking of modification is not determined by Visual Basic, but rather by the implementation of the
IEnumerable interface. It is possible to implement IEnumerable in such a way as to allow modification during iteration.
If you are considering doing such dynamic modification, be sure you understand the characteristics of the IEnumerable
implementation on the collection you are using.
Modifying Collection Elements. The Current property of the enumerator object is ReadOnly (Visual Basic), and it
returns a local copy of each collection element. This means that you cannot modify the elements themselves in a For
Each...Next loop. Any modification you make affects only the local copy from Current and is not reflected back into the
underlying collection. However, if an element is a reference type, you can modify the members of the instance to which it
points. The following example illustrates this.
The preceding example can modify the BackColor member of each thisControl element, although it cannot modify
thisControl itself.
Traversing Arrays. Because the Array class implements the IEnumerable interface, all arrays expose the GetEnumerator
method. This means that you can iterate through an array with a For Each...Next loop. However, you can only read the
array elements, not change them. For an illustration, see
How to: Run Several Statements for Each Element in a Collection or Array.
Example
The following example uses the For Each...Next statement to search all elements in a collection for the string "Hello". The
example assumes that the collection thisCollection has already been created and that its elements are of type String.
VB
Dim found As Boolean = False
Dim thisCollection As New Collection
For Each thisObject As String In thisCollection
If thisObject = "Hello" Then
found = True
Exit For
End If
Next thisObject
See Also
Tasks
How to: Run Several Statements for Each Element in a Collection or Array
How to: Improve the Performance of a Loop
Reference
While...End While Statement (Visual Basic)
Do...Loop Statement (Visual Basic)
Concepts
Loop Structures
Collections in Visual Basic
Visual Basic Language Reference
Parts
counter
Required in the For statement. Numeric variable. The control variable for the loop.
datatype
Required if counter is not already declared. Data type of counter.
start
Required. Numeric expression. The initial value of counter.
end
Required. Numeric expression. The final value of counter.
step
Optional. Numeric expression. The amount by which counter is incremented each time through the loop.
statements
Optional. One or more statements between For and Next that run the specified number of times.
Exit For
Optional. Transfers control out of the For loop.
Next
Required. Terminates the definition of the For loop.
Remarks
Use a For...Next structure when you want to repeat a set of statements a set number of times.
A While...End While Statement (Visual Basic) or Do...Loop Statement (Visual Basic) works well when you do not know in
advance how many times you need to run the statements in the loop. However, when you expect to run the loop a specific
number of times, a For...Next loop is a better choice. You determine the number of iterations when you first enter the loop.
The value of step can be either positive or negative. It determines loop processing as follows:
Step value Loop executes if
Positive or zero counter <= end
For i As Integer = 1 To 10
For j As Integer = 1 To 10
For k As Integer = 1 To 10
' Insert statements to operate with current values of i, j, and k.
Next k
Next j
Next i
You can also nest different kinds control structures within one another. For more information, see
Nested Control Structures.
Note
If a Next statement of an outer nesting level is encountered before the Next of an inner level, the compiler signals an e
rror. However, the compiler can detect this overlapping error only if you specify counter in every Next statement.
Identifying the Control Variable. You can optionally specify counter in the Next statement. This improves the
readability of your program, especially if you have nested For loops. You must specify the same variable as the one that
appears in the corresponding For statement.
Transferring Out of the Loop. The Exit Statement (Visual Basic) transfers control immediately to the statement
following the Next statement. You might want to exit a loop if you detect a condition that makes it unnecessary or
impossible to continue iterating, such as an erroneous value or a termination request. Also, if you catch an exception in a
Try...Catch...Finally, you can use Exit For at the end of the Finally block.
You can place any number of Exit For statements anywhere in the For loop. Exit For is often used after evaluating some
condition, for example in an If...Then...Else structure.
Endless Loops. One use of Exit For is to test for a condition that could cause an endless loop, which is a loop that could
run an extremely large or even infinite number of times. If you detect such a condition, you can use Exit For to escape
the loop. For more information, see Do...Loop Statement (Visual Basic).
Behavior
Entry into the Loop. When execution of the For...Next loop begins, Visual Basic evaluates start, end, and step for the
only time. It then assigns start to counter. Before it runs the statement block, it compares counter to end. If counter is
already past the end value, the For loop terminates and control passes to the statement following the Next statement.
Otherwise the statement block runs.
Iterations of the Loop. Each time Visual Basic encounters the Next statement, it increments counter by step and returns
to the For statement. Again it compares counter to end, and again it either runs the block or terminates the loop
depending on the result. This process continues until counter passes end or an Exit For statement is encountered.
Termination of the Loop. The loop does not terminate until counter has passed end. If counter is equal to end, the loop
continues. The comparison that determines whether to run the block is counter <= end if step is positive and
counter >= end if step is negative.
Changing Iteration Values. Changing the value of counter while inside a loop can make it more difficult to read and
debug your code. Changing the value of start, end, or step does not affect the iteration values determined when the loop
was first entered.
Example
The following example demonstrates nested For...Next structures with different step values.
VB
Dim words, digit As Integer
Dim thisString As String = ""
For words = 10 To 1 Step -1
For digit = 0 To 9
thisString &= CStr(digit)
Next digit
thisString &= " "
Next words
The preceding example creates a string that contains 10 instances of the numbers 0 through 9, each string separated from the
other by a single space. The outer loop decrements a loop counter variable each time through the loop.
See Also
Tasks
How to: Improve the Performance of a Loop
Reference
While...End While Statement (Visual Basic)
Do...Loop Statement (Visual Basic)
Exit Statement (Visual Basic)
For Each...Next Statement (Visual Basic)
Concepts
Loop Structures
Nested Control Structures
Visual Basic Language Reference
Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
proceduremodifiers
Optional. Can be one of the following:
Overloads
Overrides
Overridable
NotOverridable
MustOverride
MustOverride Overrides
NotOverridable Overrides
Shared
Optional. See Shared.
Shadows
Optional. See Shadows.
name
Required. Name of the procedure. See Declared Element Names.
typeparamlist
Optional. List of type parameters for a generic procedure. See Type List.
parameterlist
Optional. List of local variable names representing the parameters of this procedure. See Argument List.
returntype
Required if Option Strict is On. Data type of the value returned by this procedure.
Implements
Optional. Indicates that this procedure implements one or more Function procedures, each one defined in an interface
implemented by this procedure's containing class or structure. See Implements Statement.
implementslist
Required if Implements is supplied. List of Function procedures being implemented.
implementedprocedure [ , implementedprocedure ... ]
Part Description
interface Required. Name of an interface implemented by this procedure's containing class or structure.
Handles
Optional. Indicates that this procedure can handle one or more specific events. See Handles.
eventlist
Required if Handles is supplied. List of events this procedure handles.
eventspecifier [ , eventspecifier ... ]
Part Description
eventvariable Required. Object variable declared with the data type of the class or structure that raises the event.
statements
Optional. Block of statements to be executed within this procedure.
End Function
Terminates the definition of this procedure.
Remarks
All executable code must be inside a procedure. Each procedure in turn is declared within a class, structure, or module, which is
called the containing class, structure, or module.
Use a Function procedure when you need to return a value to the calling code. Use a Sub procedure when you do not need to
return a value.
You can use Function only at module level. This means the declaration context for a function must be a class, structure,
module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see
Declaration Contexts and Default Access Levels.
Function procedures default to public access. You can adjust their access levels with the access modifiers.
You can use a Function procedure on the right side of an expression when you want to use the value returned by the function.
You use the Function procedure the same way you use any library function such as Sqrt, Cos, or ChrW.
You call a Function procedure by using the procedure name, followed by the argument list in parentheses, in an expression.
You can omit the parentheses only if you are not supplying any arguments. However, your code is more readable if you always
include the parentheses.
A function can also be called using the Call statement, in which case the return value is ignored.
Rules
Return Type. The Function statement can declare the data type of the value it returns. You can specify any data type or
the name of an enumeration, structure, class, or interface.
If you do not specify returntype, the procedure returns Object.
Implementation. If this procedure uses the Implements keyword, the containing class or structure must also have an
Implements statement immediately following its Class or Structure statement. The Implements statement must
include each interface specified in implementslist. However, the name by which an interface defines the Function (in
definedname) does not have to be the same as the name of this procedure (in name).
Behavior
Returning from a Procedure. When the Function procedure returns to the calling code, execution continues with the
statement following the statement that called it.
The Exit Function and Return statements cause an immediate exit from a Function procedure. Any number of Exit
Function and Return statements can appear anywhere in the procedure, and you can mix Exit Function and Return
statements.
Return Value. To return a value from a function, you can either assign the value to the function name or include it in a
Return statement. The following example assigns the return value to the function name myFunction and then uses the
Exit Function statement to return.
VB
Function myFunction(ByVal j As Integer) As Double
myFunction = 3.87 * j
Exit Function
End Function
If you use Exit Function without assigning a value to name, the procedure returns the default value for the data type
specified in returntype. If returntype is not specified, the procedure returns Nothing, the default value for Object.
The Return statement simultaneously assigns the return value and exits the function. The following example shows this.
VB
Function myFunction(ByVal j As Integer) As Double
Return 3.87 * j
End Function
Troubleshooting
Order of Execution. Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. For that
reason, avoid using a Function procedure in an arithmetic expression when the function changes the value of variables
in the same expression.
Example
The following example uses the Function statement to declare the name, parameters, and code that form the body of a
Function procedure. The ParamArray modifier enables the function to accept a variable number of arguments.
VB
Public Function calcSum(ByVal ParamArray args() As Double) As Double
calcSum = 0
If args.Length <= 0 Then Exit Function
For i As Integer = 0 To UBound(args, 1)
calcSum += args(i)
Next i
End Function
The following example invokes the function declared in the preceding example.
VB
Dim returnedValue As Double = calcSum(4, 3, 2, 1)
' The function's local variables are assigned the following values:
' args(0) = 4, args(1) = 3, and so on.
See Also
Tasks
How to: Use a Generic Class
Troubleshooting Procedures
Reference
Sub Statement (Visual Basic)
Parameter List
Dim Statement (Visual Basic)
Call Statement (Visual Basic)
Of
Concepts
Parameter Arrays
Visual Basic Language Reference
Get Statement
Declares a Get property procedure used to retrieve the value of a property.
Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional on at most one of the Get and Set statements in this property. Can be one of the following:
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
statements
Optional. One or more statements that run when the Get property procedure is called.
End Get
Required. Terminates the definition of the Get property procedure.
Remarks
Every property must have a Get property procedure unless the property is marked WriteOnly. The Get procedure is used to
return the current value of the property.
Visual Basic automatically calls a property's Get procedure when an expression requests the property's value.
The body of the property declaration can contain only the property's Get and Set procedures between the Property Statement
and the End Property statement. It cannot store anything other than those procedures. In particular, it cannot store the
property's current value. You must store this value outside the property, because if you store it inside either of the property
procedures, the other property procedure cannot access it. The usual approach is to store the value in a Private (Visual Basic)
variable declared at the same level as the property. You must define a Get procedure inside the property to which it applies.
The Get procedure defaults to the access level of its containing property unless you use accessmodifier in the Get statement.
Rules
Mixed Access Levels. If you are defining a read-write property, you can optionally specify a different access level for
either the Get or the Set procedure, but not both. If you do this, the procedure access level must be more restrictive than
the property's access level. For example, if the property is declared Friend, you can declare the Get procedure Private,
but not Public.
If you are defining a ReadOnly property, the Get procedure represents the entire property. You cannot declare a
different access level for Get, because that would set two access levels for the property.
Return Type. The Property Statement can declare the data type of the value it returns. The Get procedure automatically
returns that data type. You can specify any data type or the name of an enumeration, structure, class, or interface.
If the Property statement does not specify returntype, the procedure returns Object.
Behavior
Returning from a Procedure. When the Get procedure returns to the calling code, execution continues within the
statement that requested the property value.
Get property procedures can return a value using either the Return Statement (Visual Basic) or by assigning the return
value to the property name. For more information, see "Return Value" in Function Statement (Visual Basic).
The Exit Property and Return statements cause an immediate exit from a property procedure. Any number of Exit
Property and Return statements can appear anywhere in the procedure, and you can mix Exit Property and Return
statements.
Return Value. To return a value from a Get procedure, you can either assign the value to the property name or include it
in a Return Statement (Visual Basic). The Return statement simultaneously assigns the Get procedure return value and
exits the procedure.
If you use Exit Property without assigning a value to the property name, the Get procedure returns the default value for
the property's data type. For more information, see "Return Value" in Function Statement (Visual Basic).
The following example illustrates two ways the read-only property quoteForTheDay can return the value held in the
private variable quoteValue.
VB
Private quoteValue As String = "No quote assigned yet."
VB
ReadOnly Property quoteForTheDay() As String
Get
quoteForTheDay = quoteValue
Exit Property
End Get
End Property
VB
ReadOnly Property quoteForTheDay() As String
Get
Return quoteValue
End Get
End Property
Example
The following example uses the Get statement to return the value of a property.
VB
Class propClass
' Define a private local variable to store the property value.
Private currentTime As String
' Define the read-only property.
Public ReadOnly Property dateAndTime() As String
Get
' The Get procedure is called automatically when the
' value of the property is retrieved.
currentTime = CStr(Now)
' Return the date and time As a string.
Return currentTime
End Get
End Property
End Class
See Also
Tasks
How to: Add Fields and Properties to a Class
Reference
Set Statement (Visual Basic)
Property Statement
Exit Statement (Visual Basic)
Visual Basic Language Reference
GoTo Statement
Branches unconditionally to a specified line within a procedure.
GoTo line
Part
line
Required. Any line label.
Remarks
The GoTo statement can branch only to lines within the procedure in which it appears. The line must have a line label that
GoTo can refer to. For more information, see How to: Label Statements.
Note
GoTo statements can make code difficult to read and maintain. Whenever possible, use a control structure instead. For more
information, see Control Flow in Visual Basic.
You cannot use a GoTo statement to branch from outside a For...Next, For Each...Next, SyncLock...End SyncLock,
Try...Catch...Finally, With...End With, or Using...End Using construction to a label inside.
Branching and Try Constructions
Within a Try...Catch...Finally construction, the following rules apply to branching with the GoTo statement.
Block or reg Branching in from outside Branching out from inside
ion
Try block Only from a Catch block of the same con Only to outside the entire construction
struction 1
Catch block Never allowed Only to outside the entire construction, or to the Try block of the sam
e construction 1
1 If one Try...Catch...Finally construction is nested within another, a Catch block can branch into the Try block at its own
nesting level, but not into any other Try block. A nested Try...Catch...Finally construction must be contained entirely within a
Try or Catch block of the construction within which it is nested.
The following illustration shows one Try construction nested within another. Various branches among the blocks of the two
constructions are indicated as valid or invalid.
Valid and invalid branches in Try constructions
Example
The following example uses the GoTo statement to branch to line labels within a procedure.
VB
Sub gotoStatementDemo()
Dim number As Integer = 1
Dim sampleString As String
' Evaluate number and branch to appropriate label.
If number = 1 Then GoTo Line1 Else GoTo Line2
Line1:
sampleString = "Number equals 1"
GoTo LastLine
Line2:
' The following statement never gets executed because number = 1.
sampleString = "Number equals 2"
LastLine:
' Write "Number equals 1" in the Debug window.
Debug.WriteLine(sampleString)
End Sub
See Also
Reference
Do...Loop Statement (Visual Basic)
For...Next Statement (Visual Basic)
For Each...Next Statement (Visual Basic)
If...Then...Else Statement (Visual Basic)
Select...Case Statement (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
While...End While Statement (Visual Basic)
With...End With Statement (Visual Basic)
Visual Basic Language Reference
If condition [ Then ]
[ statements ]
[ ElseIf elseifcondition [ Then ]
[ elseifstatements ] ]
[ Else
[ elsestatements ] ]
End If
-or-
If condition Then [ statements ] [ Else [ elsestatements ] ]
Parts
condition
Required. Expression. Must evaluate to True or False, or to a data type that is implicitly convertible to Boolean.
Then
Required in the single-line form, optional in the multiple-line form.
statements
Optional. One or more statements following If...Then that are executed if condition evaluates to True.
elseifcondition
Required if ElseIf is present. Expression. Must evaluate to True or False, or to a data type that is implicitly convertible to
Boolean.
elseifstatements
Optional. One or more statements following ElseIf...Then that are executed if elseifcondition evaluates to True.
elsestatements
Optional. One or more statements that are executed if no previous condition or elseifcondition expression evaluates to True.
End If
Terminates the If...Then...Else block.
Remarks
You can use the single-line form for short, simple tests. However, the multiple-line form provides more structure and flexibility
than the single-line form and is usually easier to read, maintain, and debug.
When a multiple-line If...Then...Else is encountered, condition is tested. If condition is True, the statements following Then are
executed. If condition is False, each ElseIf statement is evaluated in order. When a True elseifcondition is found, the statements
immediately following the associated Then are executed. If no elseifcondition evaluates to True, or if there are no ElseIf
statements, the statements following Else are executed. After executing the statements following Then, ElseIf, or Else,
execution continues with the statement following End If.
Tip
The Select...Case Statement (Visual Basic) might be more useful when evaluating a single expression that has several possible
values.
In the single-line form, it is possible to have multiple statements executed as the result of an If...Then decision. All statements
must be on the same line and be separated by colons. The following example demonstrates this.
If A > 10 Then A = A + 1 : B = B + A : C = C + B
In the multiple-line form, the If statement must be the only statement on the first line. The ElseIf, Else, and End If statements
can be preceded only by a line label. The multiple-line If...Then...Else block must end with an End If statement.
To determine whether or not an If statement introduces a multiple-line form, examine what follows the Then keyword. If
anything other than a comment appears after Then in the same statement, the statement is treated as a single-line If
statement. If Then is absent, it must be the beginning of a multiple-line If...Then...Else.
The ElseIf and Else clauses are both optional. You can have as many ElseIf clauses as you want in a multiple-line
If...Then...Else, but none can appear after an Else clause. Multiple-line forms can be nested within one another.
Example
The following example shows both the multiple- and single-line forms of the If...Then...Else statement.
VB
Dim number, digits As Integer
Dim myString As String
number = 53
If number < 10 Then
digits = 1
ElseIf number < 100 Then
digits = 2
Else
digits = 3
End If
If digits = 1 Then myString = "One" Else myString = "More than one"
In the preceding example, the ElseIf condition evaluates to True, and digits is assigned a value of 2. The last statement then
assigns a value of "More than one" to myString.
See Also
Reference
#If...Then...#Else Directives
Choose Function
Select...Case Statement (Visual Basic)
Switch Function
Visual Basic Language Reference
Implements Statement
Specifies one or more interfaces, or interface members, that must be implemented in the class or structure definition in which
it appears.
Parts
interfacename
Required. An interface whose properties, procedures, and events are to be implemented by corresponding members in the
class or structure.
interfacemember
Required. The member of an interface that is being implemented.
Remarks
An interface is a collection of prototypes representing the members (properties, procedures, and events) the interface
encapsulates. Interfaces contain only the declarations for members; classes and structures implement these members.
The Implements statement must immediately follow the Class or Structure statement.
When you implement an interface, you must implement all the members declared in the interface. Omitting any member is
considered to be a syntax error. To implement an individual member, you specify the Implements (Visual Basic) keyword
(which is separate from the Implements statement) when you declare the member in the class or structure. For more
information, see Implements Keyword and Implements Statement.
Classes can use Private (Visual Basic) implementations of properties and procedures, but these members are accessible only by
casting an instance of the implementing class into a variable declared to be of the type of the interface.
Example
The following example shows how to use the Implements statement to implement members of an interface. It defines an
interface named ICustomerInfo with an event, a property, and a procedure. The class customerInfo implements all the
members defined in the interface.
VB
Public Interface ICustomerInfo
Event updateComplete()
Property customerName() As String
Sub updateCustomerStatus()
End Interface
Note that the class customerInfo uses the Implements statement on a separate source code line to indicate that the class
implements all the members of the ICustomerInfo interface. Then each member in the class uses the Implements keyword as
part of its member declaration to indicate that it implements that interface member.
The following two procedures show how you could use the interface implemented in the preceding example. To test the
implementation, add these procedures to your project and call the testImplements procedure.
VB
Public Sub testImplements()
' This procedure tests the interface implementation by
' creating an instance of the class that implements ICustomerInfo.
Dim cust As ICustomerInfo = New customerInfo()
' Associate an event handler with the event that is raised by
' the cust object.
AddHandler cust.updateComplete, AddressOf handleUpdateComplete
' Set the customerName Property
cust.customerName = "Fred"
' Retrieve and display the customerName property.
MsgBox("Customer name is: " & cust.customerName)
' Call the updateCustomerStatus procedure, which raises the
' updateComplete event.
cust.updateCustomerStatus()
End Sub
Sub handleUpdateComplete()
' This is the event handler for the updateComplete event.
MsgBox("Update is complete.")
End Sub
See Also
Reference
Implements (Visual Basic)
Interface Statement (Visual Basic)
Concepts
How Visual Basic Provides Polymorphism
Other Resources
Interfaces in Visual Basic
Polymorphism
Visual Basic Language Reference
Imports Statement
Imports namespaces or programming elements defined in referenced projects and assemblies. Also imports namespaces or
elements defined within the same project.
Parts
aliasname
Optional. An import alias or name by which code can refer to namespace instead of the full qualification string. See
Declared Element Names.
namespace
Required. The fully qualified name of the namespace being imported. Can be a string of namespaces nested to any level.
element
Optional. The name of a programming element declared in the namespace. Can be any container element.
Remarks
Each source file can contain any number of Imports statements. These must follow any option declarations such as the Option
Strict statement, and they must precede any programming element declarations such as Module or Class statements.
You can use Imports only at file level. This means the declaration context for importation must be a source file, and cannot be
a namespace, class, structure, module, interface, procedure, or block.
Import aliases are useful when you need to use items with the same name that are declared in one or more namespaces. For
more information and an example, see "Classes with the Same Name" in
Resolving a Reference When Multiple Variables Have the Same Name.
Note that the Imports statement does not make elements from other projects and assemblies available to your project.
Importing does not take the place of setting a reference. It only removes the need to qualify names that are already available to
your project. For more information, see "Importing Containing Elements" in
Resolving a Reference When Multiple Variables Have the Same Name.
Rules
Alias Name. You should not declare a member at module level with the same name as aliasname. If you do, the Visual
Basic compiler uses aliasname only for the declared member and no longer recognizes it as an import alias.
Namespace Name. You can supply a single namespace name or a string of nested namespaces. Each nested
namespace is separated from the next higher level namespace by a period (.), as the following example illustrates.
Imports System.Collections.Generic
Element Type. If you supply element, it must represent a container element, that is, a programming element that can
contain other elements. Container elements include classes, structures, modules, interfaces, and enumerations.
Behavior
Scope. The scope of the elements made available by an Imports statement depends on whether you specify element. If
you specify only namespace, all uniquely named members of that namespace, and members of container elements
within that namespace, are available without qualification. If you specify both namespace and element, only the members
of that element are available without qualification.
Qualification. Code outside a namespace or container element must normally qualify a member's name with the name
of that namespace of container element. The Imports statement makes such qualification unnecessary unless your
project has access to another member with the same name. In such a case you can specify an aliasname in each Imports
statement. Then you need only the import aliases to qualify the members with the same name.
Example
The following example imports the Microsoft.VisualBasic.Strings class and assigns an alias, str, that can be used to access the
Left method.
VB
' Place Imports statements at the top of your program.
Imports str = Microsoft.VisualBasic.Strings
VB
Class testClass1
Sub showHello()
' Display only the word "Hello"
MsgBox(str.Left("Hello World", 5))
End Sub
End Class
Notice that the preceding example imports a nested namespace, Strings within VisualBasic within Microsoft. When the
MsgBox Function (Visual Basic) accesses the Left method, it can use the alias str instead of the entire qualification string
Microsoft.VisualBasic.Strings.
See Also
Reference
Namespace Statement
Concepts
Introduction to the .NET Framework Class Library in Visual Studio
Namespaces in Visual Basic
Other Resources
Visual Basic and the .NET Framework
Visual Basic Language Reference
Inherits Statement
Causes the current class or interface to inherit the attributes, variables, properties, procedures, and events from another class
or set of interfaces.
Inherits basetypenames
Parts
basetypenames
Required. The name of the class from which this class derives.
-or-
The names of the interfaces from which this interface derives. Use commas to separate multiple names.
Remarks
If used, the Inherits statement must be the first non-blank, non-comment line in a class or interface definition. It should
immediately follow the Class or Interface statement.
You can use Inherits only in a class or interface. This means the declaration context for an inheritance cannot be a source file,
namespace, structure, module, procedure, or block.
Rules
Class Inheritance. If a class uses the Inherits statement, you can specify only one base class.
A class cannot inherit from a class nested within it.
Interface Inheritance. If an interface uses the Inherits statement, you can specify one or more base interfaces. You can
inherit from two interfaces even if they each define a member with the same name. If you do so, the implementing code
must use name qualification to specify which member it is implementing.
An interface cannot inherit from another interface with a more restrictive access level. For example, a Public interface
cannot inherit from a Friend interface.
An interface cannot inherit from an interface nested within it.
An example of class inheritance in the .NET Framework is the ArgumentException class, which inherits from the
SystemException class. This provides to ArgumentException all the predefined properties and procedures required by
system exceptions, such as the Message property and the ToString method.
An example of interface inheritance in the .NET Framework is the ICollection interface, which inherits from the IEnumerable
interface. This causes ICollection to inherit the definition of the enumerator required to traverse a collection.
Example
The following example uses the Inherits statement to show how a class named thisClass can inherit all the members of a
base class named anotherClass.
VB
Public Class thisClass
Inherits anotherClass
' Add code to override, overload, or extend members
' inherited from the base class.
' Add new variable, property, procedure, and event declarations.
End Class
The interface named thisInterface now includes all the definitions in the IComparable, IDisposable, and IFormattable
interfaces The inherited members provide respectively for type-specific comparison of two objects, releasing allocated
resources, and expressing the value of an object as a String. A class that implements thisInterface must implement every
member of every base interface.
See Also
Reference
MustInherit
NotInheritable
MyBase
MyClass
Concepts
Interface Implementation Examples in Visual Basic
Other Resources
Inheritance in Visual Basic
Visual Basic Language Reference
Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
Shadows
Optional. See Shadows.
name
Required. Name of this interface. See Declared Element Names.
Of
Optional. Specifies that this is a generic interface.
typelist
Required if you use the Of keyword. List of type parameters for this interface. See Type List.
Inherits
Optional. Indicates that this interface inherits the attributes and members of another interface or interfaces. See
Inherits Statement.
interfacenames
Required if you use the Inherits statement. The names of the interfaces from which this interface derives.
modifiers
Optional. Appropriate modifiers for the interface member being defined.
Property
Optional. Defines a property that is a member of the interface.
Function
Optional. Defines a Function procedure that is a member of the interface.
Sub
Optional. Defines a Sub procedure that is a member of the interface.
Event
Optional. Defines an event that is a member of the interface.
Interface
Optional. Defines an interface that is a nested within this interface. The nested interface definition must terminate with an
End Interface statement.
Class
Optional. Defines a class that is a member of the interface. The member class definition must terminate with an End Class
statement.
Structure
Optional. Defines a structure that is a member of the interface. The member structure definition must terminate with an End
Structure statement.
membername
Required for each property, procedure, event, interface, class, or structure defined as a member of the interface. The name of
the member.
End Interface
Terminates the Interface definition.
Remarks
An interface defines a set of members, such as properties and procedures, that classes and structures can implement. The
interface defines only the signatures of the members and not their internal workings.
A class or structure implements the interface by supplying code for every member defined by the interface. Finally, when the
application creates an instance from that class or structure, an object exists and runs in memory. For more information, see
Object-Oriented Programming in Visual Basic and Interfaces in Visual Basic.
For a comparison of interfaces and classes, see Interfaces Overview.
You can use Interface only at namespace or module level. This means the declaration context for an interface must be a
source file, namespace, class, structure, module, or interface, and cannot be a procedure or block. For more information, see
Declaration Contexts and Default Access Levels.
Interfaces default to Friend (Visual Basic) access. You can adjust their access levels with the access modifiers. For more
information, see Access Levels in Visual Basic.
Rules
Nesting Interfaces. You can define one interface within another. The outer interface is called the containing interface,
and the inner interface is called a nested interface.
Member Declaration. When you declare a property or procedure as a member of an interface, you are defining only
the signature of that property or procedure. This includes the element type (property or procedure), its parameters and
parameter types, and its return type. Because of this, the member definition uses only one line of code, and terminating
statements such as End Function or End Property are not valid in an interface.
In contrast, when you define an enumeration or structure, or a nested class or interface, it is necessary to include their
data members.
Member Modifiers. You cannot use any access modifiers when defining module members, nor can you specify
Shared (Visual Basic) or any procedure modifier except Overloads. You can declare any member with Shadows, and you
can use Default (Visual Basic) when defining a property, as well as ReadOnly (Visual Basic) or WriteOnly.
Inheritance. If the interface uses the Inherits Statement, you can specify one or more base interfaces. You can inherit
from two interfaces even if they each define a member with the same name. If you do so, the implementing code must
use name qualification to specify which member it is implementing.
An interface cannot inherit from another interface with a more restrictive access level. For example, a Public interface
cannot inherit from a Friend interface.
An interface cannot inherit from an interface nested within it.
Implementation. When a class uses the Implements (Visual Basic) statement to implement this interface, it must
implement every member defined within the interface. Furthermore, each signature in the implementing code must
exactly match the corresponding signature defined in this interface. However, the name of the member in the
implementing code does not have to match the member name as defined in the interface.
When a class is implementing a procedure, it cannot designate the procedure as Shared.
Default Property. An interface can specify at most one property as its default property, which can be referenced without
using the property name. You specify such a property by declaring it with the Default (Visual Basic) modifier. For more
information, see Default Properties.
Notice that this means that an interface can define a default property only if it inherits none.
Behavior
Access Level. All interface members implicitly have Public (Visual Basic) access. You cannot use any access modifier
when defining a member. However, a class implementing the interface can declare an access level for each implemented
member.
If you assign a class instance to a variable, the access level of its members can depend on whether the data type of the
variable is the underlying interface or the implementing class. The following example illustrates this.
VB
Public Interface IDemo
Sub doSomething()
End Interface
Public Class implementIDemo
Implements IDemo
Private Sub doSomething() Implements IDemo.doSomething
End Sub
End Class
Dim varAsInterface As IDemo = New implementIDemo()
Dim varAsClass As implementIDemo = New implementIDemo()
If you access class members through varAsInterface, they all have public access. However, if you access members
through varAsClass, the Sub procedure doSomething has private access.
Scope. An interface is in scope throughout its namespace, class, structure, or module.
The scope of every interface member is the entire interface.
Lifetime. An interface does not itself have a lifetime, nor do its members. When a class implements an interface and an
object is created as an instance of that class, the object has a lifetime within the application in which it is running. For
more information, see "Lifetime" in Class Statement (Visual Basic).
Example
The following example uses the Interface statement to define an interface named thisInterface, which must be implemented
with a Property statement and a Function statement.
VB
Public Interface thisInterface
Property thisProp(ByVal thisStr As String) As Char
Function thisFunc(ByVal thisInt As Integer) As Integer
End Interface
Note that the Property and Function statements do not introduce blocks ending with End Property and End Function
within the interface. The interface defines only the signatures of its members. The full Property and Function blocks appear in
a class that implements thisInterface.
See Also
Reference
Class Statement (Visual Basic)
Module Statement
Structure Statement
Property Statement
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Concepts
Generic Types in Visual Basic
Other Resources
Interfaces in Visual Basic
Visual Basic Language Reference
Mid Statement
Replaces a specified number of characters in a String variable with characters from another string.
Mid( _
ByRef Target As String, _
ByVal Start As Integer, _
Optional ByVal Length As Integer _
) = StringExpression
Parts
Target
Required. Name of the String variable to modify.
Start
Required. Integer expression. Character position in Target where the replacement of text begins. Start uses a one-based
index.
Length
Optional. Integer expression. Number of characters to replace. If omitted, all of String is used.
StringExpression
Required. String expression that replaces part of Target.
Exceptions
Exception type Error number Condition
ArgumentException 5 Start <= 0 or Length < 0.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The number of characters replaced is always less than or equal to the number of characters in Target.
Visual Basic has a Mid Function (Visual Basic) and a Mid statement. These elements both operate on a specified number of
characters in a string, but the Mid function returns the characters while the Mid statement replaces the characters. For more
information, see Mid Function (Visual Basic).
Note
The MidB statement of earlier versions of Visual Basic replaces a substring in bytes, rather than characters. It is used primaril
y for converting strings in double-byte character set (DBCS) applications. All Visual Basic strings are in Unicode, and MidB is
no longer supported.
Example
This example uses the Mid statement to replace a specified number of characters in a string variable with characters from
another string.
VB
Dim TestString As String
' Initializes string.
TestString = "The dog jumps"
' Returns "The fox jumps".
Mid(TestString, 5, 3) = "fox"
' Returns "The cow jumps".
Mid(TestString, 5) = "cow"
' Returns "The cow jumpe".
Mid(TestString, 5) = "cow jumped over"
' Returns "The duc jumpe".
Mid(TestString, 5, 3) = "duck"
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Mid Function (Visual Basic)
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference
Module Statement
Declares the name of a module and introduces the definition of the variables, properties, events, and procedures that the
module comprises.
Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Friend
See Access Levels in Visual Basic.
name
Required. Name of this module. See Declared Element Names.
statements
Optional. Statements which define the variables, properties, events, procedures, and nested types of this module.
End Module
Terminates the Module definition.
Remarks
A Module statement defines a reference type available throughout its namespace. A module (sometimes called a standard
module) is similar to a class but with some important distinctions. Every module has exactly one instance and does not need to
be created or assigned to a variable. Modules do not support inheritance or implement interfaces. Notice that a module is not a
type in the sense that a class or structure is — you cannot declare a programming element to have the data type of a module.
You can use Module only at namespace level. This means the declaration context for a module must be a source file or
namespace, and cannot be a class, structure, module, interface, procedure, or block. You cannot nest a module within another
module, or within any type. For more information, see Declaration Contexts and Default Access Levels.
A module has the same lifetime as your program. Because its members are all Shared, they also have lifetimes equal to that of
the program.
Modules default to Friend (Visual Basic) access. You can adjust their access levels with the access modifiers. For more
information, see Access Levels in Visual Basic.
All members of a module are implicitly Shared.
Classes and Modules
These elements have many similarities, but there are some important differences as well.
Terminology. Previous versions of Visual Basic recognize two types of modules: class modules (.cls files) and standard
modules (.bas files). The current version calls these classes and modules, respectively.
Shared Members. You can control whether a member of a class is a shared or instance member.
Object Orientation. Classes are object-oriented, but modules are not. So only classes can be instantiated as objects. For
more information, see Classes vs. Modules.
Rules
Modifiers. All module members are implicitly Shared (Visual Basic). You cannot use the Shared keyword when
declaring a member, and you cannot alter the shared status of any member.
Inheritance. A module cannot inherit from any type other than Object, from which all modules inherit. In particular, one
module cannot inherit from another.
You cannot use the Inherits Statement in a module definition, even to specify Object.
Default Property. You cannot define any Default Properties in a module.
Behavior
Access Level. Within a module, you can declare each member with its own access level. Module members default to
Public (Visual Basic) access, except variables and constants, which default to Private (Visual Basic) access. When a module
has more restricted access than one of its members, the specified module access level takes precedence.
Scope. A module is in scope throughout its namespace.
The scope of every module member is the entire module. Notice that all members undergo type promotion, which
causes their scope to be promoted to the namespace containing the module. For more information, see Type Promotion.
Qualification. You can have multiple modules in a project, and you can declare members with the same name in two or
more modules. However, you must qualify any reference to such a member with the appropriate module name if the
reference is from outside that module. For more information, see
Resolving a Reference When Multiple Variables Have the Same Name.
Example
VB
Public Module thisModule
Sub Main()
Dim userName As String = InputBox("What is your name?")
MsgBox("User name is" & userName)
End Sub
' Insert variable, property, procedure, and event declarations.
End Module
See Also
Reference
Class Statement (Visual Basic)
Namespace Statement
Structure Statement
Interface Statement (Visual Basic)
Property Statement
Concepts
Type Promotion
Visual Basic Language Reference
Namespace Statement
Declares the name of a namespace and causes the source code following the declaration to be compiled within that
namespace.
Parts
name
Required. A unique name that identifies the namespace. Must be a valid Visual Basic identifier. For more information, see
Declared Element Names.
componenttypes
Optional. Elements that make up the namespace. These include (but are not limited to) enumerations, structures, interfaces,
classes, modules, delegates, and other namespaces.
End Namespace
Terminates a Namespace block.
Remarks
Namespaces are used as an organizational system. They provide a way of classifying and presenting programming elements
that are exposed to other programs and applications. Note that a namespace is not a type in the sense that a class or structure
is — you cannot declare a programming element to have the data type of a namespace.
You can use a Namespace statement only at the file or namespace level. This means the declaration context for a namespace
must be a source file or another namespace, and cannot be a class, structure, module, interface, or procedure. For more
information, see Declaration Contexts and Default Access Levels.
Namespaces are treated as if they had a Public access level. A namespace can be accessed from code anywhere within the
same project, from other projects that reference the project, and from any assembly built from the project.
Rules
Attributes. You cannot apply attributes to a namespace. An attribute contributes information to the assembly's
metadata, which is not meaningful for source classifiers such as namespaces.
Modifiers. You cannot apply any access or procedure modifiers, or any other modifiers, to a namespace. Because it is
not a type, these modifiers are not meaningful.
Nesting. You can declare one namespace within another. There is no strict limit to the levels of nesting you can declare,
but keep in mind that when other code accesses the elements declared in the innermost namespace, it must use a
qualification string containing all the namespace names in the nesting hierarchy.
Behavior
Access Level. Programming elements declared at namespace level, meaning within a namespace but not inside any
other element, can have Public or Friend access. If not specified, the access level of such an element defaults to Friend.
Elements you can declare at namespace level include classes, structures, modules, interfaces, enumerations, and
delegates. For more information, see Declaration Contexts and Default Access Levels.
Compilation. All programming elements declared following a Namespace statement belong to that namespace. Visual
Basic continues to compile elements into the last declared namespace until it encounters either an End Namespace
statement or another Namespace statement.
Adding to a Namespace. If a namespace is already defined, even outside your project, you can add programming
elements to it. To do this, you use a Namespace statement to direct Visual Basic to compile the following elements into
that namespace.
The following example defines the skeleton of a new generic list class and adds it to the System.Collections.Generic
namespace.
Namespace System.Collections.Generic
Class specialSortedList(Of T)
Inherits List(Of T)
' Insert code to define the special generic list class.
End Class
End Namespace
Root Namespace. All namespace names in your project are based on a root namespace. Visual Studio assigns your
project name as the default root namespace for all code in your project. For example, if your project is named Payroll, its
programming elements belong to namespace Payroll. If you declare Namespace funding, the full name of that
namespace is Payroll.funding.
If you wish to specify an existing namespace in a Namespace statement, such as in the generic list class example, you
can set your root namespace to a null value. You do this by choosing Project Properties from the Project menu and
then clearing the Root namespace entry so that the box is empty. If you did not do this in the generic list class example,
the Visual Basic compiler would take System.Collections.Generic as a new namespace within project Payroll, with the
full name of Payroll.System.Collections.Generic.
Alternatively, you can use the Global keyword to refer to elements of namespaces defined outside your project. Doing so
allows you to retain your project name as the root namespace. This reduces the chance of unintentionally merging your
programming elements with those of existing namespaces.
Troubleshooting
Undefined Types. The root namespace can lead to unexpected concatenations of namespace names. If you make
reference to namespaces defined outside your project, the Visual Basic compiler can construe them as nested
namespaces within your root namespace. In such a case, the compiler does not recognize any types that have been
already defined in the external namespaces. To avoid this, either set your root namespace to a null value as described in
"Root Namespace", or use the Global keyword to access elements of external namespaces.
Example
The following example declares two namespaces, one nested within the other.
VB
Namespace n1
Namespace n2
Class a
' Insert class definition.
End Class
End Namespace
End Namespace
The following example declares multiple nested namespaces on a single line, and it is equivalent to the previous example.
VB
Namespace n1.n2
Class a
' Insert class definition.
End Class
End Namespace
The following example accesses the class defined in the previous examples.
VB
Dim instance As New n1.n2.a
See Also
Reference
Imports Statement
Global
Concepts
Declared Element Names
Namespaces in Visual Basic
Visual Basic Language Reference
Parts
GoTo line
Enables the error-handling routine that starts at the line specified in the required line argument. The line argument is any line
label or line number. If a run-time error occurs, control branches to the specified line, making the error handler active. The
specified line must be in the same procedure as the On Error statement, or a compile-time error will occur.
GoTo 0
Disables enabled error handler in the current procedure and resets it to Nothing.
GoTo -1
Disables enabled exception in the current procedure and resets it to Nothing.
Resume Next
Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the
error occurred, and execution continues from that point. Use this form rather than On Error GoTo when accessing objects.
Remarks
An "enabled" error handler is one that is turned on by an On Error statement. An "active" error handler is an enabled handler
that is in the process of handling an error.
If an error occurs while an error handler is active (between the occurrence of the error and a Resume, Exit Sub, Exit
Function, or Exit Property statement), the current procedure's error handler cannot handle the error. Control returns to the
calling procedure.
If the calling procedure has an enabled error handler, it is activated to handle the error. If the calling procedure's error handler
is also active, control passes back through previous calling procedures until an enabled, but inactive, error handler is found. If
no such error handler is found, the error is fatal at the point at which it actually occurred.
Each time the error handler passes control back to a calling procedure, that procedure becomes the current procedure. Once an
error is handled by an error handler in any procedure, execution resumes in the current procedure at the point designated by
the Resume statement.
Note
An error-handling routine is not a Sub procedure or a Function procedure. It is a section of code marked by a line label or a
line number.
Number Property
Error-handling routines rely on the value in the Number property of the Err object to determine the cause of the error. The
routine should test or save relevant property values in the Err object before any other error can occur or before a procedure
that might cause an error is called. The property values in the Err object reflect only the most recent error. The error message
associated with Err.Number is contained in Err.Description.
Throw Statement
An error that is raised with the Err.Raise method sets the Exception property to a newly created instance of the Exception
class. In order to support the raising of exceptions of derived exception types, a Throw statement is supported in the language.
This takes a single parameter that is the exception instance to be thrown. The following example shows how these features can
be used with the existing exception handling support:
VB
On Error GoTo Handler
Throw New DivideByZeroException()
Handler:
If (TypeOf Err.GetException() Is DivideByZeroException) Then
' Code for handling the error is entered here.
End If
Notice that the On Error GoTo statement traps all errors, regardless of the exception class.
On Error Resume Next
On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the
run-time error, or with the statement immediately following the most recent call out of the procedure containing the On Error
Resume Next statement. This statement allows execution to continue despite a run-time error. You can place the error-
handling routine where the error would occur rather than transferring control to another location within the procedure. An On
Error Resume Next statement becomes inactive when another procedure is called, so you should execute an On Error
Resume Next statement in each called routine if you want inline error handling within that routine.
Note
The On Error Resume Next construct may be preferable to On Error GoTo when handling errors generated during access t
o other objects. Checking Err after each interaction with an object removes ambiguity about which object was accessed by th
e code. You can be sure which object placed the error code in Err.Number, as well as which object originally generated the e
rror (the object specified in Err.Source).
On Error GoTo 0
On Error GoTo 0 disables error handling in the current procedure. It doesn't specify line 0 as the start of the error-handling
code, even if the procedure contains a line numbered 0. Without an On Error GoTo 0 statement, an error handler is
automatically disabled when a procedure is exited.
On Error GoTo -1
On Error GoTo -1 disables the exception in the current procedure. It does not specify line -1 as the start of the error-handling
code, even if the procedure contains a line numbered -1. Without an On Error GoTo -1 statement, an exception is
automatically disabled when a procedure is exited.
To prevent error-handling code from running when no error has occurred, place an Exit Sub, Exit Function, or Exit Property
statement immediately before the error-handling routine, as in the following fragment:
VB
Public Sub InitializeMatrix(ByVal Var1 As Object, ByVal Var2 As Object)
On Error GoTo ErrorHandler
' Insert code that might generate an error here
Exit Sub
ErrorHandler:
' Insert code to handle the error here
Resume Next
End Sub
Here, the error-handling code follows the Exit Sub statement and precedes the End Sub statement to separate it from the
procedure flow. You can place error-handling code anywhere in a procedure.
Untrapped Errors
Untrapped errors in objects are returned to the controlling application when the object is running as an executable file. Within
the development environment, untrapped errors are returned to the controlling application only if the proper options are set.
See your host application's documentation for a description of which options should be set during debugging, how to set
them, and whether the host can create classes.
If you create an object that accesses other objects, you should try to handle any unhandled errors they pass back. If you cannot,
map the error codes in Err.Number to one of your own errors and then pass them back to the caller of your object. You
should specify your error by adding your error code to the VbObjectError constant. For example, if your error code is 1052,
assign it as follows:
VB
Err.Number = vbObjectError + 1052
Caution
System errors during calls to Windows dynamic-link libraries (DLLs) do not raise exceptions and cannot be trapped with Visu
al Basic error trapping. When calling DLL functions, you should check each return value for success or failure (according to th
e API specifications), and in the event of a failure, check the value in the Err object's LastDLLError property.
Example
This example first uses the On Error GoTo statement to specify the location of an error-handling routine within a procedure. In
the example, an attempt to divide by zero generates error number 6. The error is handled in the error-handling routine, and
control is then returned to the statement that caused the error. The On Error GoTo 0 statement turns off error trapping. Then
the On Error Resume Next statement is used to defer error trapping so that the context for the error generated by the next
statement can be known for certain. Note that Err.Clear is used to clear the Err object's properties after the error is handled.
VB
Public Sub OnErrorDemo()
On Error GoTo ErrorHandler ' Enable error-handling routine.
Dim x As Integer = 32
Dim y As Integer = 0
Dim z As Integer
z = x / y ' Creates a divide by zero error
On Error GoTo 0 ' Turn off error trapping.
On Error Resume Next ' Defer error trapping.
z = x / y ' Creates a divide by zero error again
If Err.Number = 6 Then
' Tell user what happened. Then clear the Err object.
Dim Msg As String
Msg = "There was an error attempting to divide by zero!"
MsgBox(Msg, , "Divide by zero error")
Err.Clear() ' Clear Err object fields.
End If
Exit Sub ' Exit to avoid handler.
ErrorHandler: ' Error-handling routine.
Select Case Err.Number ' Evaluate error number.
Case 6 ' Divide by zero error
MsgBox("You attempted to divide by zero!")
' Insert code to handle this error
Case Else
' Insert code to handle other situations here...
End Select
Resume Next ' Resume execution at same line
' that caused the error.
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Get Information about Visual Basic Run-Time Errors
Reference
End Statement
Err Object (Visual Basic)
Exit Statement (Visual Basic)
LastDllError Property (Err Object)
Resume Statement
Visual Basic Language Reference
Operator Statement
Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.
Parts
attrlist
Optional. See Attribute List.
Public
Required. Indicates that this operator procedure has Public (Visual Basic) access.
Overloads
Optional. See Overloads.
Shared
Required. Indicates that this operator procedure is a Shared (Visual Basic) procedure.
Shadows
Optional. See Shadows.
Widening
Required for a conversion operator unless you specify Narrowing. Indicates that this operator procedure defines a
Widening conversion. See "Widening and Narrowing Conversions" on this Help page.
Narrowing
Required for a conversion operator unless you specify Widening. Indicates that this operator procedure defines a
Narrowing conversion. See "Widening and Narrowing Conversions" on this Help page.
operatorsymbol
Required. The symbol or identifier of the operator that this operator procedure defines.
operand1
Required. The name and type of the single operand of a unary operator (including a conversion operator) or the left operand
of a binary operator.
operand2
Required for binary operators. The name and type of the right operand of a binary operator.
operand1 and operand2 have the following syntax and parts:
[ ByVal ] operandname [ As operandtype ]
Part Description
ByVal Optional, but the passing mechanism must be ByVal.
operandname Required. Name of the variable representing this operand. See Declared Element Names.
operandtype Optional unless Option Strict is On. Data type of this operand.
type
Optional unless Option Strict is On. Data type of the value the operator procedure returns.
statements
Optional. Block of statements that the operator procedure runs.
returnvalue
Required. The value that the operator procedure returns to the calling code.
End Operator
Required. Terminates the definition of this operator procedure.
Remarks
You can use Operator only in a class or structure. This means the declaration context for an operator cannot be a source file,
namespace, module, interface, procedure, or block. For more information, see Declaration Contexts and Default Access Levels.
All operators must be Public Shared. You cannot specify ByRef, Optional, or ParamArray for either operand.
You cannot use the operator symbol or identifier to hold a return value. You must use the Return statement, and it must
specify a value. Any number of Return statements can appear anywhere in the procedure.
Defining an operator in this way is called operator overloading, whether or not you use the Overloads keyword. The following
table lists the operators you can define.
Type Operators
Unary +, -, IsFalse, IsTrue, Not
Binary +, -, *, /, \, &, ^, >>, <<, =, <>, >, >=, <, <=, And, Like, Mod, Or, Xor
Note that the = operator in the binary list is the comparison operator, not the assignment operator.
When you define CType, you must specify either Widening or Narrowing.
Matched Pairs
You must define certain operators as matched pairs. If you define either operator of such a pair, you must define the other as
well. The matched pairs are the following:
= and <>
> and <
>= and <=
IsTrue and IsFalse
Data Type Restrictions
Every operator you define must involve the class or structure on which you define it. This means that the class or structure
must appear as the data type of the following:
The operand of a unary operator.
At least one of the operands of a binary operator.
Either the operand or the return type of a conversion operator.
Certain operators have additional data type restrictions, as follows:
If you define the IsTrue and IsFalse operators, they must both return the Boolean type.
If you define the << and >> operators, they must both specify the Integer type for the operandtype of operand2.
The return type does not have to correspond to the type of either operand. For example, a comparison operator such as = or
<> can return Boolean even if neither operand is Boolean.
Logical and Bitwise Operators
The And, Or, Not, and Xor operators can perform either logical or bitwise operations in Visual Basic. However, if you define
one of these operators on a class or structure, you can define only its bitwise operation.
You cannot define the AndAlso operator directly with an Operator statement. However, you can use AndAlso if you have
fulfilled the following conditions:
You have defined And on the same operand types you want to use for AndAlso.
Your definition of And returns the same type as the class or structure on which you have defined it.
You have defined the IsFalse operator on the class or structure on which you have defined And.
Similarly, you can use OrElse if you have defined Or on the same operands, with the return type of the class or structure, and
you have defined IsTrue on the class or structure.
Widening and Narrowing Conversions
A widening conversion always succeeds at run time, while a narrowing conversion can fail at run time. For more information,
see Widening and Narrowing Conversions.
If you declare a conversion procedure to be Widening, your procedure code must not generate any failures. This means the
following:
It must always return a valid value of type type.
It must handle all possible exceptions and other error conditions.
It must handle any error returns from any procedures it calls.
If there is any possibility that a conversion procedure might not succeed, or that it might cause an unhandled exception, you
must declare it to be Narrowing.
Example
The following code example uses the Operator statement to define the outline of a structure that includes operator procedures
for the And, Or, IsFalse, and IsTrue operators. And and Or each take two operands of type abc and return type abc. IsFalse
and IsTrue each take a single operand of type abc and return Boolean. These definitions allow the calling code to use And,
AndAlso, Or, and OrElse with operands of type abc.
VB
Public Structure abc
Dim d As Date
Public Shared Operator And(ByVal x As abc, ByVal y As abc) As abc
Dim r As New abc
' Insert code to calculate And of x and y.
Return r
End Operator
Public Shared Operator Or(ByVal x As abc, ByVal y As abc) As abc
Dim r As New abc
' Insert code to calculate Or of x and y.
Return r
End Operator
Public Shared Operator IsFalse(ByVal z As abc) As Boolean
Dim b As Boolean
' Insert code to calculate IsFalse of z.
Return b
End Operator
Public Shared Operator IsTrue(ByVal z As abc) As Boolean
Dim b As Boolean
' Insert code to calculate IsTrue of z.
Return b
End Operator
End Structure
See Also
Tasks
How to: Define an Operator
How to: Define a Conversion Operator
How to: Call an Operator Procedure
How to: Use a Class that Defines Operators
Reference
IsFalse Operator
IsTrue Operator
Widening
Narrowing
Concepts
Widening and Narrowing Conversions
Operator Procedures
Visual Basic Language Reference
Parts
Binary
Optional. Results in string comparisons based on a sort order derived from the internal binary representations of the
characters.
Text
Optional. Results in string comparisons based on a case-insensitive text sort order determined by your system's locale.
Remarks
If used, the Option Compare statement must appear in a file before any other source code statements.
The Option Compare statement specifies the string comparison method (Binary or Text) for a class, module or structure. If
an Option Compare statement is not included, the default text comparison method is Binary.
In Microsoft Windows, sort order is determined by the code page. For more information, see Code Pages.
In the following example, characters in the English/European code page (ANSI 1252) are sorted using Option Compare
Binary, which produces a typical binary sort order.
A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø
When the same characters in the same code page are sorted using Option Compare Text, the following text sort order is
produced.
(A=a) < (À = à) < (B=b) < (E=e) < (Ê = ê) < (Z=z) < (Ø = ø)
You can also set Option Compare in the Visual Studio integrated development environment (IDE) or on a command line.
To set Option Compare in the integrated development environment (IDE)
1. On the Tools menu, choose Options.
2. Open the Projects and Solutions node.
3. Choose VB Defaults.
4. Modify the Option Compare setting.
To set Option Compare on the command line
Include the /optioncompare compiler option in the vbc command.
Example
The following example uses the Option Compare statement to set the binary comparison as the default string comparison
method.
VB
' Set the string comparison method to Binary ("AAA" < "aaa").
Option Compare Binary
The following example uses the Option Compare statement to set the case-insensitive text sort order as the default string
comparison method.
VB
' Set the string comparison method to Text ("AAA" = "aaa").
Option Compare Text
See Also
Reference
Comparison Operators (Visual Basic)
InStr Function (Visual Basic)
InStrRev Function (Visual Basic)
Replace Function (Visual Basic)
Split Function (Visual Basic)
StrComp Function (Visual Basic)
/optioncompare
Option Explicit Statement (Visual Basic)
Option Strict Statement
/optionexplicit
/optionstrict
Visual Basic Defaults, Projects, Options Dialog Box
Visual Basic Language Reference
Parts
On
Optional. Enables Option Explicit checking. If On or Off is not specified, the default is On.
Off
Optional. Disables Option Explicit checking.
Remarks
If used, the Option Explicit statement must appear in a file before any other source code statements.
When Option Explicit appears in a file, you must explicitly declare all variables using the Dim or ReDim statements. If you
attempt to use an undeclared variable name, an error occurs at compile time.
Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope
of the variable is not clear. If you do not use the Option Explicit statement, all undeclared variables are of Object type.
Note
The compiler default is Option Explicit On if you do not specify Option Explicit in your code.
You can also set Option Explicit in the Visual Studio integrated development environment (IDE) or on a command line.
To set Option Explicit in the integrated development environment (IDE)
1. On the Tools menu, choose Options.
2. Open the Projects and Solutions node.
3. Choose VB Defaults.
4. Modify the Option Explicit setting.
VB
Dim thisVar As Integer
thisVar = 10
' The following assignment produces a COMPILER ERROR because
' the variable is not declared and Option Explicit is On.
thisInt = 10 ' causes ERROR
See Also
Reference
Dim Statement (Visual Basic)
ReDim Statement (Visual Basic)
Option Compare Statement
Option Strict Statement
/optioncompare
/optionexplicit
/optionstrict
Visual Basic Defaults, Projects, Options Dialog Box
Visual Basic Language Reference
Parts
On
Optional. Enables Option Strict checking.
Off
Optional. Disables Option Strict checking. If On or Off is not specified, the default is Off.
Remarks
If used, the Option Strict statement must appear in a file before any other source code statements.
Visual Basic allows conversions of many data types to other data types. Data loss can occur when the value of one data type is
converted to a data type with less precision or smaller capacity. A run-time error occurs if such a narrowing conversion fails.
Option Strict ensures compile-time notification of these narrowing conversions so they can be avoided.
In addition to disallowing implicit narrowing conversions, Option Strict generates an error for late binding. An object is late
bound when it is assigned to a variable that is declared to be of type Object.
Because Option Strict On provides strong typing, prevents unintended type conversions with data loss, disallows late binding,
and improves performance, its use is strongly recommended.
Note
The compiler default is Option Strict Off if you do not specify Option Strict in your code.
You can also set Option Strict in the Visual Studio integrated development environment (IDE) or on a command line.
To set Option Strict in the integrated development environment (IDE)
1. On the Tools menu, choose Options.
2. Open the Projects and Solutions node.
3. Choose VB Defaults.
4. Modify the Option Strict setting.
To set Option Strict on the command line
Include the /optionstrict compiler option in the vbc command.
Example
The following example demonstrates how the Option Strict statement disallows late binding and conversions where data
would be lost.
VB
Option Strict On
VB
Dim thisVar As Integer
Dim thisObj As Object = New widget
thisVar = 1000 ' Declared variable does not generate error.
' Attempting to convert Double to Integer generates a COMPILER ERROR.
thisVar = 1234567890.9876542 ' causes ERROR
' Late-bound call generates a COMPILER ERROR.
Call thisObj.Method1() ' causes ERROR
See Also
Reference
Option Compare Statement
Option Explicit Statement (Visual Basic)
/optioncompare
/optionexplicit
/optionstrict
Visual Basic Defaults, Projects, Options Dialog Box
Concepts
Widening and Narrowing Conversions
Visual Basic Language Reference
Property Statement
Declares the name of a property, and the property procedures used to store and retrieve the value of the property.
Parts
attributelist
Optional. List of attributes that apply to this property or Get or Set procedure. See Attribute List.
Default
Optional. Specifies that this property is the default property for the class or structure on which it is defined. Default
properties must accept parameters and can be set and retrieved without specifying the property name. If you declare the
property as Default, you cannot use Private on the property or on either of its property procedures.
accessmodifier
Optional on the Property statement and on at most one of the Get and Set statements. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
propertymodifiers
Optional. Can be one of the following:
Overloads
Overrides
Overridable
NotOverridable
MustOverride
MustOverride Overrides
NotOverridable Overrides
Shared
Optional. See Shared (Visual Basic).
Shadows
Optional. See Shadows.
ReadOnly
Optional. See ReadOnly (Visual Basic).
WriteOnly
Optional. See WriteOnly.
name
Required. Name of the property. See Declared Element Names.
parameterlist
Optional. List of local variable names representing the parameters of this property, and possible additional parameters of the
Set procedure. See Parameter List.
returntype
Required if Option Strict is On. Data type of the value returned by this property.
Implements
Optional. Indicates that this property implements one or more properties, each one defined in an interface implemented by
this property's containing class or structure. See Implements Statement.
implementslist
Required if Implements is supplied. List of properties being implemented.
implementedproperty [ , implementedproperty ... ]
Part Description
interface Required. Name of an interface implemented by this property's containing class or structure.
Get
Required unless the property is marked WriteOnly. Starts a Get property procedure used to return the value of the
property.
statements
Optional. Block of statements to run within the Get or Set procedure.
End Get
Terminates the Get property procedure.
Set
Required unless the property is marked ReadOnly. Starts a Set property procedure used to store the value of the property.
End Set
Terminates the Set property procedure.
End Property
Terminates the definition of this property.
Remarks
The Property statement introduces the declaration of a property. A property can have a Get procedure (read only), a Set
procedure (write only), or both (read-write).
You can use Property only at module level. This means the declaration context for a property must be a class, structure,
module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see
Declaration Contexts and Default Access Levels.
Properties default to public access. You can adjust a property's access level with an access modifier on the Property statement,
and you can optionally adjust one of its property procedures to a more restrictive access level.
Visual Basic passes a parameter to the Set procedure during property assignments. If you do not supply a parameter for Set,
the integrated development environment (IDE) uses an implicit parameter named value. This parameter holds the value to be
assigned to the property. You typically store this value in a private local variable and return it whenever the Get procedure is
called.
Rules
Mixed Access Levels. If you are defining a read-write property, you can optionally specify a different access level for
either the Get or the Set procedure, but not both. If you do this, the procedure access level must be more restrictive than
the property's access level. For example, if the property is declared Friend, you can declare the Set procedure Private,
but not Public.
If you are defining a ReadOnly or WriteOnly property, the single property procedure (Get or Set, respectively)
represents the entire property. You cannot declare a different access level for such a procedure, because that would set
two access levels for the property.
Return Type. The Property statement can declare the data type of the value it returns. You can specify any data type or
the name of an enumeration, structure, class, or interface.
If you do not specify returntype, the property returns Object.
Implementation. If this property uses the Implements keyword, the containing class or structure must have an
Implements statement immediately following its Class or Structure statement. The Implements statement must
include each interface specified in implementslist. However, the name by which an interface defines the Property (in
definedname) does not have to be the same as the name of this property (in name).
Behavior
Returning from a Property Procedure. When the Get or Set procedure returns to the calling code, execution
continues with the statement following the statement that invoked it.
The Exit Property and Return statements cause an immediate exit from a property procedure. Any number of Exit
Property and Return statements can appear anywhere in the procedure, and you can mix Exit Property and Return
statements.
Return Value. To return a value from a Get procedure, you can either assign the value to the property name or include it
in a Return statement. The following example assigns the return value to the property name quoteForTheDay and then
uses the Exit Property statement to return.
VB
Private quoteValue As String = "No quote assigned yet."
VB
ReadOnly Property quoteForTheDay() As String
Get
quoteForTheDay = quoteValue
Exit Property
End Get
End Property
If you use Exit Property without assigning a value to name, the Get procedure returns the default value for the
property's data type.
The Return statement simultaneously assigns the Get procedure return value and exits the procedure. The following
example shows this.
VB
Private quoteValue As String = "No quote assigned yet."
VB
ReadOnly Property quoteForTheDay() As String
Get
Return quoteValue
End Get
End Property
Example
The following example declares a property in a class.
VB
Class Class1
' Define a local variable to store the property value.
Private propertyValue As String
' Define the property.
Public Property prop1() As String
Get
' The Get property procedure is called when the value
' of a property is retrieved.
Return propertyValue
End Get
Set(ByVal value As String)
' The Set property procedure is called when the value
' of a property is modified. The value to be assigned
' is passed in the argument to Set.
propertyValue = value
End Set
End Property
End Class
See Also
Tasks
How to: Add Fields and Properties to a Class
Reference
Get Statement
Set Statement (Visual Basic)
Parameter List
Concepts
Default Properties
Visual Basic Language Reference
Q-Z Statements
The following table contains a listing of Visual Basic language statements.
With...End With
See Also
Reference
A-E Statements
F-P Statements
Other Resources
Visual Basic Reference
Visual Basic Language Reference
RaiseEvent Statement
Triggers an event declared at module level within a class, form, or document.
Parts
eventname
Required. Name of the event to trigger.
argumentlist
Optional. Comma-delimited list of variables, arrays, or expressions. The argumentlist argument must be enclosed by
parentheses. If there are no arguments, the parentheses must be omitted.
Remarks
The required eventname is the name of an event declared within the module. It follows Visual Basic variable naming
conventions.
If the event has not been declared within the module in which it is raised, an error occurs. The following code fragment
illustrates an event declaration and a procedure in which the event is raised.
VB
' Declare an event at module level.
Event LogonCompleted(ByVal UserName As String)
You cannot use RaiseEvent to raise events that are not explicitly declared in the module. For example, all forms inherit a Click
event from System.Windows.Forms.Form, it cannot be raised using RaiseEvent in a derived form. If you declare a Click event
in the form module, it shadows the form's own Click event. You can still invoke the form's Click event by calling the OnClick
method.
By default, an event defined in Visual Basic raises its event handlers in the order that the connections are established. Because
events can have ByRef parameters, a process that connects late may receive parameters that have been changed by an earlier
event handler. After the event handlers execute, control is returned to the subroutine that raised the event.
Note
Non-shared events should not be raised within the constructor of the class in which they are declared. Although such events
do not cause run-time errors, they may fail to be caught by associated event handlers. Use the Shared modifier to create a s
hared event if you need to raise an event from a constructor.
You can change the default behavior of events by defining a custom event. For custom events, the RaiseEvent statement
invokes the event's RaiseEvent accessor. For more information on custom events, see Event Statement.
Example
The following example uses events to count down seconds from 10 to 0. The code illustrates several of the event-related
methods, properties, and statements, including the RaiseEvent statement.
The class that raises an event is the event source, and the methods that process the event are the event handlers. An event
source can have multiple handlers for the events it generates. When the class raises the event, that event is raised on every
class that has elected to handle events for that instance of the object.
The example also uses a form (Form1) with a button (Button1) and a text box (TextBox1). When you click the button, the first
text box displays a countdown from 10 to 0 seconds. When the full time (10 seconds) has elapsed, the first text box displays
"Done".
The code for Form1 specifies the initial and terminal states of the form. It also contains the code executed when events are
raised.
To use this example, open a new Windows Application project, add a button named Button1 and a text box named TextBox1 to
the main form, named Form1. Then right-click the form and click View Code to open the Code Editor.
Add a WithEvents variable to the declarations section of the Form1 class.
VB
Private WithEvents mText As TimerState
Add the following code to the code for Form1. Replace any duplicate procedures that may exist, such as Form_Load, or
Button_Click.
VB
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Button1.Text = "Start"
mText = New TimerState
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
mText.StartCountdown(10.0, 0.1)
End Sub
Press F5 to run the preceding example, and click the button labeled Start. The first text box starts to count down the seconds.
When the full time (10 seconds) has elapsed, the first text box displays "Done".
Note
The My.Application.DoEvents method does not process events in exactly the same way as the form does. To allow the for
m to handle the events directly, you can use multithreading. For more information, see Multithreading in Visual Basic.
See Also
Tasks
How to: Add Events to a Class
Reference
Event Statement
AddHandler Statement
RemoveHandler Statement
Handles
Other Resources
Events in Visual Basic
Visual Basic Language Reference
Parts
Preserve
Optional. Modifier used to preserve the data in the existing array when you change the size of only the last dimension.
name
Required. Name of the array variable. See Declared Element Names.
boundlist
Required. List of bounds of each dimension of the redefined array.
Remarks
You can use the ReDim statement to change the size of one or more dimensions of an array that has already been declared. If
you have a large array and you no longer need some of its elements, ReDim can free up memory by reducing the array size.
On the other hand, if your code determines that an array needs more elements, ReDim can add them.
The ReDim statement is intended only for arrays. It is not valid on scalars (variables containing only a single value), collections,
or structures. Note that if you declare a variable to be of type Array, the ReDim statement does not have sufficient type
information to create the new array.
You can use ReDim only at procedure level. This means the declaration context for a variable must be a procedure, and cannot
be a source file, namespace, interface, class, structure, module, or block. For more information, see
Declaration Contexts and Default Access Levels.
Rules
Modifiers. You can specify only the Preserve modifier, and you cannot omit the ReDim keyword if you do so.
Multiple Variables. You can resize several array variables in the same declaration statement, specifying the name and
boundlist parts for each one. Multiple variables are separated by commas.
Array Bounds. Each entry in boundlist can specify the lower and upper bounds of that dimension. The lower bound is
always zero, whether you specify it or not. The upper bound is the highest possible value for that subscript, not the length
of the dimension (which is the upper bound plus one). Each subscript can vary from zero through its upper bound value.
The number of dimensions in boundlist must match the original rank of the array.
Empty Arrays. It is possible to use -1 to declare the upper bound of an array dimension. This signifies that the array is
empty but not Nothing (Visual Basic). For more information, see How to: Create an Array with No Elements. However,
Visual Basic code cannot successfully access such an array. If you attempt to do so, an IndexOutOfRangeException error
occurs during execution.
Data Types. The ReDim statement cannot change the data type of an array variable or of its elements.
Initialization. The ReDim statement cannot provide new initialization values for the array elements.
Rank. The ReDim statement cannot change the rank (the number of dimensions) of the array.
Resizing with Preserve. If you use Preserve, you can resize only the last dimension of the array, and for every other
dimension you must specify the same bound it already has in the existing array.
For example, if your array has only one dimension, you can resize that dimension and still preserve all the contents of the
array, because you are changing the last and only dimension. However, if your array has two or more dimensions, you
can change the size of only the last dimension if you use Preserve.
Properties. You can use ReDim on a property that holds an array of values.
Behavior
Array Replacement. ReDim releases the existing array and creates a new array with the same rank. The new array
replaces the released array in the array variable.
Initialization without Preserve. If you do not specify Preserve, ReDim initializes the elements of the new array to the
default value for their data type.
Initialization with Preserve. If you specify the Preserve modifier, Visual Basic copies the elements from the existing
array to the new array.
Example
The following example increases the size of the last dimension of a dynamic array without losing any existing data in the array,
and then decreases the size with partial data loss. Finally, it decreases the size back to its original value and reinitializes all the
array elements.
VB
Dim intArray(10, 10, 10) As Integer
ReDim Preserve intArray(10, 10, 20)
ReDim Preserve intArray(10, 10, 15)
ReDim intArray(10, 10, 10)
The first ReDim creates a new array which replaces the existing array in variable intArray. ReDim copies all the elements
from the existing array into the new array. It also adds 10 more columns to the end of every row in every layer and initializes
the elements in these new columns to 0 (the default value of Integer, the element type of the array).
The second ReDim creates another new array, copying all the elements that fit. However, five columns are lost from the end of
every row in every layer. This is not a problem if you have finished using these columns. Reducing the size of a large array can
free up memory that you no longer need.
The third ReDim creates still another new array, removing another five columns from the end of every row in every layer. This
time it does not copy any existing elements. This reverts the array to its original size and returns all its elements to their
original default value.
See Also
Tasks
How to: Create an Array with No Elements
Reference
Const Statement (Visual Basic)
Dim Statement (Visual Basic)
Erase Statement (Visual Basic)
Nothing (Visual Basic)
IndexOutOfRangeException
Visual Basic Language Reference
REM comment
' comment
Parts
comment
Optional. The text of any comment you want to include. A space is required between the REM keyword or single quotation
mark (') and comment.
Remarks
You can put a REM statement alone on a line, or you can put it on a line following another statement. The REM statement must
be the last statement on the line. If it follows another statement, the REM must be separated from that statement by a space.
You can use a single quotation mark (') instead of REM. This is true whether your comment follows another statement on the
same line or sits alone on a line.
Note
You cannot continue a REM statement by using a line-continuation sequence ( _). Once a comment begins, the compiler does
not examine the characters for special meaning. For a multiple-line comment, use another REM statement or a comment sy
mbol (') on each line.
Example
The following example illustrates the REM statement, which is used to include explanatory remarks in a program. It also shows
the alternative of using the single quotation-mark character (') instead of REM.
VB
Dim demoStr1, demoStr2 As String
demoStr1 = "Hello" REM Comment after a statement using REM.
demoStr2 = "Goodbye" ' Comment after a statement using the ' character.
REM This entire line is a comment.
' This entire line is also a comment.
See Also
Tasks
How to: Break and Combine Statements in Code
Concepts
Comments in Code
Visual Basic Language Reference
RemoveHandler Statement
Removes the association between an event and an event handler.
Parts
event
The name of the event being handled.
eventhandler
The name of the procedure currently handling the event.
Remarks
The AddHandler and RemoveHandler statements allow you to start and stop event handling for a specific event at any time
during program execution.
For custom events, the RemoveHandler statement invokes the event's RemoveHandler accessor. For more information on
custom events, see Event Statement.
Example
VB
Sub TestEvents()
Dim Obj As New Class1
' Associate an event handler with an event.
AddHandler Obj.Ev_Event, AddressOf EventHandler
' Call the method to raise the event.
Obj.CauseSomeEvent()
' Stop handling events.
RemoveHandler Obj.Ev_Event, AddressOf EventHandler
' This event will not be handled.
Obj.CauseSomeEvent()
End Sub
Sub EventHandler()
' Handle the event.
MsgBox("EventHandler caught event.")
End Sub
Public Class Class1
' Declare an event.
Public Event Ev_Event()
Sub CauseSomeEvent()
' Raise an event.
RaiseEvent Ev_Event()
End Sub
End Class
See Also
Reference
AddHandler Statement
Handles
Event Statement
Concepts
Events and Event Handlers
AddHandler and RemoveHandler
Visual Basic Language Reference
Resume Statement
Resumes execution after an error-handling routine is finished.
Parts
Resume
Required. If the error occurred in the same procedure as the error handler, execution resumes with the statement that caused
the error. If the error occurred in a called procedure, execution resumes at the statement that last called out of the procedure
containing the error-handling routine.
Next
Optional. If the error occurred in the same procedure as the error handler, execution resumes with the statement
immediately following the statement that caused the error. If the error occurred in a called procedure, execution resumes
with the statement immediately following the statement that last called out of the procedure containing the error-handling
routine (or On Error Resume Next statement).
line
Optional. Execution resumes at the line specified in the required line argument. The line argument is a line label or line
number and must be in the same procedure as the error handler.
Remarks
If you use a Resume statement anywhere other than in an error-handling routine, an error occurs.
The Resume statement cannot be used in any procedure that contains a Try...Catch...Finally statement.
Example
This example uses the Resume statement to end error handling in a procedure and then resume execution with the statement
that caused the error. Error number 55 is generated to illustrate use of the Resume statement.
VB
Sub ResumeStatementDemo()
On Error GoTo ErrorHandler ' Enable error-handling routine.
Dim x As Integer = 32
Dim y As Integer = 0
Dim z As Integer
z = x / y ' Creates a divide by zero error
Exit Sub ' Exit Sub to avoid error handler.
ErrorHandler: ' Error-handling routine.
Select Case Err.Number ' Evaluate error number.
Case 6 ' "Divide by zero" error.
y = 1 ' Sets the value of y to 1 and tries the calculation again.
Case Else
' Handle other situations here....
End Select
Resume ' Resume execution at same line
' that caused the error.
End Sub
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Try...Catch...Finally Statement (Visual Basic)
Error Statement
On Error Statement (Visual Basic)
Visual Basic Language Reference
Return
-or-
Return expression
Part
expression
Required in a Function, Get, or Operator procedure. Expression that represents the value to be returned to the calling code.
Remarks
In a Sub or Set procedure, the Return statement is equivalent to an Exit Sub or Exit Property statement, and expression must
not be supplied.
In a Function, Get, or Operator procedure, the Return statement must include expression, and expression must evaluate to a
data type that is convertible to the return type of the procedure. In a Function or Get procedure, you also have the alternative
of assigning an expression to the procedure name to serve as the return value, and then executing an Exit Function or Exit
Property statement. In an Operator procedure, you must use Return expression.
You can include as many Return statements as appropriate in the same procedure.
Note
The code in a Finally block is run after a Return statement in a Try or Catch block is encountered, but before that Return st
atement is executed. In this situation, a Return statement in the Finally block is executed before the initial Return statement,
allowing for a different return value. To avoid this potentially confusing situation, avoid using Return statements in Finally b
locks.
Example
The following example uses the Return statement several times to return to the calling code when the procedure does not
need to do anything else.
VB
Public Function getAgePhrase(ByVal age As Integer) As String
If age > 60 Then Return "Senior"
If age > 40 Then Return "Middle-aged"
If age > 20 Then Return "Adult"
If age > 12 Then Return "Teen-aged"
If age > 4 Then Return "School-aged"
If age > 1 Then Return "Toddler"
Return "Infant"
End Function
See Also
Reference
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Get Statement
Set Statement (Visual Basic)
Operator Statement
Property Statement
Exit Statement (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
Visual Basic Language Reference
Parts
testexpression
Required. Expression. Must evaluate to one of the elementary data types (Boolean, Byte, Char, Date, Double, Decimal,
Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, and UShort).
expressionlist
Required in a Case statement. List of expression clauses representing match values for testexpression. Multiple expression
clauses are separated by commas. Each clause can take one of the following forms:
expression1 To expression2
[ Is ] comparisonoperator expression
expression
Use the To keyword to specify the boundaries of a range of match values for testexpression. The value of expression1 must
be less than or equal to the value of expression2.
Use the Is keyword with a comparison operator (=, <>, <, <=, >, or >=) to specify a restriction on the match values for
testexpression. If the Is keyword is not supplied, it is automatically inserted before comparisonoperator.
The form specifying only expression is treated as a special case of the Is form where comparisonoperator is the equal sign
(=). This form is evaluated as testexpression = expression.
The expressions in expressionlist can be of any data type, provided they are implicitly convertible to the type of testexpression
and the appropriate comparisonoperator is valid for the two types it is being used with.
statements
Optional. One or more statements following Case that run if testexpression matches any clause in expressionlist.
elsestatements
Optional. One or more statements following Case Else that run if testexpression does not match any clause in the
expressionlist of any of the Case statements.
End Select
Terminates the definition of the Select...Case construction.
Remarks
If testexpression matches any Case expressionlist clause, the statements following that Case statement run up to the next Case,
Case Else, or End Select statement. Control then passes to the statement following End Select. If testexpression matches an
expressionlist clause in more than one Case clause, only the statements following the first match run.
The Case Else statement is used to introduce the elsestatements to run if no match is found between the testexpression and an
expressionlist clause in any of the other Case statements. Although not required, it is a good idea to have a Case Else
statement in your Select Case construction to handle unforeseen testexpression values. If no Case expressionlist clause
matches testexpression and there is no Case Else statement, control passes to the statement following End Select.
You can use multiple expressions or ranges in each Case clause. For example, the following line is valid.
Case 1 To 4, 7 To 9, 11, 13, Is > maxNumber
Note
The Is keyword used in the Case and Case Else statements is not the same as the Is Operator (Visual Basic), which is used for
object reference comparison.
You can specify ranges and multiple expressions for character strings. In the following example, Case matches any string that
is exactly equal to "apples", has a value between "nuts" and "soup" in alphabetical order, or contains the exact same value as
the current value of testItem.
Case "apples", "nuts" To "soup", testItem
The setting of Option Compare can affect string comparisons. Under Option Compare Text, the strings "Apples" and
"apples" compare as equal, but under Option Compare Binary, they do not.
Note
A Case statement with multiple clauses can exhibit behavior known as short-circuiting. Visual Basic evaluates the clauses fro
m left to right, and if one produces a match with testexpression, the remaining clauses are not evaluated. Short-circuiting can
improve performance, but it can produce unexpected results if you are expecting every expression in expressionlist to be eval
uated. For more information on short-circuiting, see Boolean Expressions.
If the code within a Case or Case Else statement block does not need to run any more of the statements in the block, it can exit
the block by using the Exit Select statement. This transfers control immediately to the statement following End Select.
Select Case constructions can be nested. Each nested Select Case construction must have a matching End Select statement
and must be completely contained within a single Case or Case Else statement block of the outer Select Case construction
within which it is nested.
Example
The following example uses a Select Case construction to write a line corresponding to the value of the variable number. The
second Case statement contains the value that matches the current value of number, so the statement that writes "Between 6
and 8, inclusive" runs.
VB
Dim number As Integer = 8
Select Case number
Case 1 To 5
Debug.WriteLine("Between 1 and 5, inclusive")
' The following is the only Case clause that evaluates to True.
Case 6, 7, 8
Debug.WriteLine("Between 6 and 8, inclusive")
Case 9 To 10
Debug.WriteLine("Equal to 9 or 10")
Case Else
Debug.WriteLine("Not between 1 and 10, inclusive")
End Select
See Also
Reference
Choose Function
End Statement
If...Then...Else Statement (Visual Basic)
Option Compare Statement
Exit Statement (Visual Basic)
Visual Basic Language Reference
Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional on at most one of the Get and Set statements in this property. Can be one of the following:
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
value
Required. Parameter containing the new value for the property.
datatype
Required if Option Strict is On. Data type of the value parameter. The data type specified must be the same as the data type
of the property where this Set statement is declared.
statements
Optional. One or more statements that run when the Set property procedure is called.
End Set
Required. Terminates the definition of the Set property procedure.
Remarks
Every property must have a Set property procedure unless the property is marked ReadOnly. The Set procedure is used to set
the value of the property.
Visual Basic automatically calls a property's Set procedure when an assignment statement provides a value to be stored in the
property.
Visual Basic passes a parameter to the Set procedure during property assignments. If you do not supply a parameter for Set,
the integrated development environment (IDE) uses an implicit parameter named value. The parameter holds the value to be
assigned to the property. You typically store this value in a private local variable and return it whenever the Get procedure is
called.
The body of the property declaration can contain only the property's Get and Set procedures between the Property Statement
and the End Property statement. It cannot store anything other than those procedures. In particular, it cannot store the
property's current value. You must store this value outside the property, because if you store it inside either of the property
procedures, the other property procedure cannot access it. The usual approach is to store the value in a Private (Visual Basic)
variable declared at the same level as the property. You must define a Set procedure inside the property to which it applies.
The Set procedure defaults to the access level of its containing property unless you use accessmodifier in the Set statement.
Rules
Mixed Access Levels. If you are defining a read-write property, you can optionally specify a different access level for
either the Get or the Set procedure, but not both. If you do this, the procedure access level must be more restrictive than
the property's access level. For example, if the property is declared Friend, you can declare the Set procedure Private,
but not Public.
If you are defining a WriteOnly property, the Set procedure represents the entire property. You cannot declare a
different access level for Set, because that would set two access levels for the property.
Behavior
Returning from a Property Procedure. When the Set procedure returns to the calling code, execution continues
following the statement that provided the value to be stored.
Set property procedures can return using either the Return Statement (Visual Basic) or the Exit Statement (Visual Basic).
The Exit Property and Return statements cause an immediate exit from a property procedure. Any number of Exit
Property and Return statements can appear anywhere in the procedure, and you can mix Exit Property and Return
statements.
Example
The following example uses the Set statement to set the value of a property.
VB
Class propClass
Private propVal As Integer
Property prop1() As Integer
Get
Return propVal
End Get
Set(ByVal value As Integer)
propVal = value
End Set
End Property
End Class
See Also
Tasks
How to: Add Fields and Properties to a Class
Reference
Get Statement
Property Statement
Sub Statement (Visual Basic)
Visual Basic Language Reference
Stop
Remarks
You can place Stop statements anywhere in procedures to suspend execution. Using the Stop statement is similar to setting a
breakpoint in the code.
The Stop statement suspends execution, but unlike End, it does not close any files or clear any variables, unless it is
encountered in a compiled executable (.exe) file.
Note
If the Stop statement is encountered in code that is running outside of the integrated development environment (IDE), the de
bugger is invoked. This is true regardless of whether the code was compiled in debug or retail mode.
Example
This example uses the Stop statement to suspend execution for each iteration through the For...Next loop.
VB
Dim i As Integer
For i = 1 To 10
Debug.WriteLine(i)
' Stop during each iteration and wait for user to resume.
Stop
Next i
See Also
Reference
End Statement
Visual Basic Language Reference
Structure Statement
Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that the
structure comprises.
Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
Shadows
Optional. See Shadows.
Partial
Optional. Indicates a partial definition of the structure. See Partial (Visual Basic).
name
Required. Name of this structure. See Declared Element Names.
Of
Optional. Specifies that this is a generic structure.
typelist
Required if you use the Of keyword. List of type parameters for this structure. See Type List.
Implements
Optional. Indicates that this structure implements the members of one or more interfaces. See Implements Statement.
interfacenames
Required if you use the Implements statement. The names of the interfaces this structure implements.
datamemberdeclarations
Required. One or more Const, Dim, Enum, or Event statements declaring data members of the structure.
methodmemberdeclarations
Optional. Zero or more declarations of Function, Operator, Property, or Sub procedures, which serve as method members
of the structure.
End Structure
Required. Terminates the Structure definition.
Remarks
The Structure statement defines a composite value type that you can customize. A structure is a generalization of the user-
defined type (UDT) of previous versions of Visual Basic. For more information, see Structures: Your Own Data Types.
Structures support many of the same features as classes. For example, structures can have properties and procedures, they can
implement interfaces, and they can have parameterized constructors. However, there are significant differences between
structures and classes in areas such as inheritance, declarations, and usage. Also, classes are reference types and structures are
value types. For more information, see Structures and Classes.
You can use Structure only at namespace or module level. This means the declaration context for a structure must be a source
file, namespace, class, structure, module, or interface, and cannot be a procedure or block. For more information, see
Declaration Contexts and Default Access Levels.
Structures default to Friend (Visual Basic) access. You can adjust their access levels with the access modifiers. For more
information, see Access Levels in Visual Basic.
Rules
Nesting. You can define one structure within another. The outer structure is called the containing structure, and the
inner structure is called a nested structure. However, you cannot access a nested structure's members through the
containing structure. Instead, you must declare a variable of the nested structure's data type.
Member Declaration. You must declare every member of a structure. A structure member cannot be Protected or
Protected Friend because nothing can inherit from a structure. The structure itself, however, can be Protected or
Protected Friend.
You must declare at least one nonshared variable or nonshared, noncustom event in a structure. You cannot have only
constants, properties, and procedures, even if some of them are nonshared.
Initialization. You cannot initialize the value of any nonshared data member of a structure as part of its declaration. You
must either initialize such a data member by means of a parameterized constructor on the structure, or assign a value to
the member after you have created an instance of the structure.
Inheritance. A structure cannot inherit from any type other than ValueType, from which all structures inherit. In
particular, one structure cannot inherit from another.
You cannot use the Inherits Statement in a structure definition, even to specify ValueType.
Implementation. If the structure uses the Implements Statement, you must implement every member defined by every
interface you specify in interfacenames.
Default Property. A structure can specify at most one property as its default property, using the Default (Visual Basic)
modifier. For more information, see Default Properties.
Behavior
Access Level. Within a structure, you can declare each member with its own access level. All structure members default
to Public (Visual Basic) access. Note that if the structure itself has a more restricted access level, this automatically
restricts access to its members, even if you adjust their access levels with the access modifiers.
Scope. A structure is in scope throughout its containing namespace, class, structure, or module.
The scope of every structure member is the entire structure.
Lifetime. A structure does not itself have a lifetime. Rather, each instance of that structure has a lifetime independent of
all other instances.
The lifetime of an instance begins when it is created by a New (Visual Basic) clause. It ends when the lifetime of the
variable that holds it ends.
You cannot extend the lifetime of a structure instance. An approximation to static structure functionality is provided by a
module. For more information, see Module Statement.
Structure members have lifetimes depending on how and where they are declared. For more information, see "Lifetime"
in Class Statement (Visual Basic).
Qualification. Code outside a structure must qualify a member's name with the name of that structure.
If code inside a nested structure makes an unqualified reference to a programming element, Visual Basic searches for the
element first in the nested structure, then in its containing structure, and so on out to the outermost containing element.
For more information, see Resolving a Reference When Multiple Variables Have the Same Name.
Memory Consumption. As with all composite data types, you cannot safely calculate the total memory consumption of
a structure by adding together the nominal storage allocations of its members. Furthermore, you cannot safely assume
that the order of storage in memory is the same as your order of declaration. If you need to control the storage layout of
a structure, you can apply the StructLayoutAttribute attribute to the Structure statement.
Example
The following example uses the Structure statement to define a set of related data for an employee. It shows the use of
Public, Friend, and Private members to reflect the sensitivity of the data items. It also shows procedure, property, and event
members.
VB
Public Structure employee
' Public members, accessible from throughout declaration region.
Public firstName As String
Public middleName As String
Public lastName As String
' Friend members, accessible from anywhere within the same assembly.
Friend employeeNumber As Integer
Friend workPhone As Long
' Private members, accessible only from within the structure itself.
Private homePhone As Long
Private level As Integer
Private salary As Double
Private bonus As Double
' Procedure member, which can access structure's private members.
Friend Sub calculateBonus(ByVal rate As Single)
bonus = salary * CDbl(rate)
End Sub
' Property member to return employee's eligibility.
Friend ReadOnly Property eligible() As Boolean
Get
Return level >= 25
End Get
End Property
' Event member, raised when business phone number has changed.
Public Event changedWorkPhone(ByVal newPhone As Long)
End Structure
See Also
Reference
Class Statement (Visual Basic)
Interface Statement (Visual Basic)
Module Statement
Dim Statement (Visual Basic)
Const Statement (Visual Basic)
Enum Statement (Visual Basic)
Event Statement
Operator Statement
Property Statement
Concepts
Structures and Classes
Visual Basic Language Reference
Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
proceduremodifiers
Optional. Can be one of the following:
Overloads
Overrides
Overridable
NotOverridable
MustOverride
MustOverride Overrides
NotOverridable Overrides
Shared
Optional. See Shared.
Shadows
Optional. See Shadows.
name
Required. Name of the procedure. See Declared Element Names.
typeparamlist
Optional. List of type parameters for a generic procedure. See Type List.
parameterlist
Optional. List of local variable names representing the parameters of this procedure. See Parameter List.
Implements
Optional. Indicates that this procedure implements one or more Sub procedures, each one defined in an interface
implemented by this procedure's containing class or structure. See Implements Statement.
implementslist
Required if Implements is supplied. List of Sub procedures being implemented.
implementedprocedure [ , implementedprocedure ... ]
Part Description
interface Required. Name of an interface implemented by this procedure's containing class or structure.
Handles
Optional. Indicates that this procedure can handle one or more specific events. See Handles.
eventlist
Required if Handles is supplied. List of events this procedure handles.
eventspecifier [ , eventspecifier ... ]
Part Description
eventvariable Required. Object variable declared with the data type of the class or structure that raises the event.
statements
Optional. Block of statements to run within this procedure.
End Sub
Terminates the definition of this procedure.
Remarks
All executable code must be inside a procedure. Use a Sub procedure when you do not need to return a value to the calling
code. Use a Function procedure when you need to return a value.
You can use Sub only at module level. This means the declaration context for a sub procedure must be a class, structure,
module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see
Declaration Contexts and Default Access Levels.
Sub procedures default to public access. You can adjust their access levels with the access modifiers.
Rules
Implementation. If this procedure uses the Implements keyword, the containing class or structure must have an
Implements statement immediately following its Class or Structure statement. The Implements statement must
include each interface specified in implementslist. However, the name by which an interface defines the Sub (in
definedname) does not have to be the same as the name of this procedure (in name).
Behavior
Returning from a Procedure. When the Sub procedure returns to the calling code, execution continues with the
statement following the statement that called it.
The Exit Sub and Return statements cause an immediate exit from a Sub procedure. Any number of Exit Sub and
Return statements can appear anywhere in the procedure, and you can mix Exit Sub and Return statements.
The following example shows a return from a Sub procedure.
Calling a Procedure. A Sub procedure, like a Function procedure, is a separate procedure that can take parameters
and perform a series of statements. However, unlike a Function procedure, which returns a value, a Sub procedure
cannot be used in an expression.
You call a Sub procedure by using the procedure name, followed by the argument list in parentheses, in a statement. You
can omit the parentheses only if you are not supplying any arguments. However, your code is more readable if you
always include the parentheses.
You can optionally use the Call statement to call a Sub procedure. This can improve the readability of your code.
Troubleshooting
Order of Execution. Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. For that reason,
if your argument list includes expressions that call other procedures, you cannot rely on them being called in any particular
order.
Example
The following example uses the Sub statement to define the name, parameters, and code that form the body of a Sub
procedure.
VB
Sub computeArea(ByVal length As Double, ByVal width As Double)
' Declare local variable.
Dim area As Double
If length = 0 Or width = 0 Then
' If either argument = 0 then exit Sub immediately.
Exit Sub
End If
' Calculate area of rectangle.
area = length * width
' Print area to Immediate window.
Debug.WriteLine(area)
End Sub
See Also
Tasks
How to: Use a Generic Class
Troubleshooting Procedures
Reference
Implements Statement
Function Statement (Visual Basic)
Parameter List
Dim Statement (Visual Basic)
Call Statement (Visual Basic)
Of
Concepts
Parameter Arrays
Visual Basic Language Reference
SyncLock Statement
Acquires an exclusive lock for a statement block before executing the block.
SyncLock lockobject
[ block ]
End SyncLock
Parts
lockobject
Required. Expression that evaluates to an object reference.
block
Optional. Block of statements that are to execute when the lock is acquired.
End SyncLock
Terminates a SyncLock block.
Remarks
The SyncLock statement ensures that multiple threads do not execute the statement block at the same time. SyncLock
prevents each thread from entering the block until no other thread is executing it.
The most common use of SyncLock is to protect data from being updated by more than one thread simultaneously. If the
statements that manipulate the data must go to completion without interruption, put them inside a SyncLock block.
A statement block protected by an exclusive lock is sometimes called a critical section.
Rules
Branching. You cannot branch into a SyncLock block from outside the block.
Lock Object Value. The value of lockobject cannot be Nothing. You must create the lock object before you use it in a
SyncLock statement.
You cannot change the value of lockobject while executing a SyncLock block. The mechanism requires that the lock
object remain unchanged.
Behavior
Mechanism. When a thread reaches the SyncLock statement, it evaluates the lockobject expression and suspends
execution until it acquires an exclusive lock on the object returned by the expression. When another thread reaches the
SyncLock statement, it does not acquire a lock until the first thread executes the End SyncLock statement.
Protected Data. If lockobject is a Shared variable, the exclusive lock prevents a thread in any instance of the class from
executing the SyncLock block while any other thread is executing it. This protects data that is shared among all the
instances.
If lockobject is an instance variable (not Shared), the lock prevents a thread running in the current instance from
executing the SyncLock block at the same time as another thread in the same instance. This protects data maintained by
the individual instance.
Acquisition and Release. A SyncLock block behaves like a Try...Finally construction in which the Try block acquires an
exclusive lock on lockobject and the Finally block releases it. Because of this, the SyncLock block guarantees release of
the lock, no matter how you exit the block. This is true even in the case of an unhandled exception.
Framework Calls. The SyncLock block acquires and releases the exclusive lock by calling the Enter and Exit methods of
the Monitor class in the System.Threading namespace.
Programming Practices
The lockobject expression should always evaluate to an object that belongs exclusively to your class. You should declare a
Private object variable to protect data belonging to the current instance, or a Private Shared object variable to protect data
common to all instances.
You should not use the Me keyword to provide a lock object for instance data. If code external to your class has a reference to
an instance of your class, it could use that reference as a lock object for a SyncLock block completely different from yours,
protecting different data. In this way, your class and the other class could block each other from executing their unrelated
SyncLock blocks. Similarly locking on a string can be problematic since any other code in the process using the same string
will share the same lock.
You should also not use the Me.GetType method to provide a lock object for shared data. This is because GetType always
returns the same Type object for a given class name. External code could call GetType on your class and obtain the same lock
object you are using. This would result in the two classes blocking each other from their SyncLock blocks.
Example
The following example shows a class that maintains a simple list of messages. It holds the messages in an array and the last
used element of that array in a variable. The addAnotherMessage procedure increments the last element and stores the new
message. Those two operations are protected by the SyncLock and End SyncLock statements, because once the last element
has been incremented, the new message must be stored before any other thread can increment the last element again.
VB
Class simpleMessageList
Public messagesList() As String = New String(50) {}
Public messagesLast As Integer = -1
Private messagesLock As New Object
Public Sub addAnotherMessage(ByVal newMessage As String)
SyncLock messagesLock
messagesLast += 1
messagesList(messagesLast) = newMessage
End SyncLock
End Sub
End Class
If the simpleMessageList class shared one list of messages among all its instances, then the variables messagesList and
messagesLast would be declared as Shared. In this case, the variable messagesLock should also be Shared, so that there would
be a single lock object used by every instance.
See Also
Reference
System.Threading
Monitor
Concepts
Thread Synchronization
Other Resources
Multithreading in Visual Basic
Visual Basic Language Reference
Throw [ expression ]
Part
expression
Provides information about the exception to be thrown. Optional when residing in a Catch statement, otherwise required.
Remarks
The Throw statement throws an exception that you can handle with structured exception-handling code (Try...Catch...Finally)
or unstructured exception-handling code (On Error GoTo). You can use the Throw statement to trap errors within your code
because Visual Basic moves up the call stack until it finds the appropriate exception-handling code.
A Throw statement with no expression can only be used in a Catch statement, in which case the statement rethrows the
exception currently being handled by the Catch statement.
The Throw statement resets the call stack for the expression exception. If expression is not provided, the call stack is left
unchanged. You can access the call stack for the exception through the StackTrace property.
Example
The following code uses the Throw statement to throw an exception:
VB
' Throws a new exception.
Throw New System.Exception("An exception has occurred.")
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Check an Exception's Inner Exception
Reference
Try...Catch...Finally Statement (Visual Basic)
On Error Statement (Visual Basic)
Concepts
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Visual Basic Language Reference
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
Parts
tryStatements
Optional. Statement(s) where an error can occur. Can be a compound statement.
Catch
Optional. Multiple Catch blocks permitted. If an exception occurs while processing the Try block, each Catch statement is
examined in textual order to determine if it handles the exception, with exception representing the exception that has been
thrown.
exception
Optional. Any variable name. The initial value of exception is the value of the thrown error. Used with Catch to specify the
error caught. If omitted, the Catch statement catches any exception.
type
Optional. Specifies the type of class filter. If the value of exception is of the type specified by type or of a derived type, the
identifier becomes bound to the exception object.
When
Optional. A Catch statement with a When clause catches exceptions only when expression evaluates to True. A When clause
is applied only after checking the type of the exception, and expression may refer to the identifier representing the exception.
expression
Optional. Must be implicitly convertible to Boolean. Any expression that describes a generic filter. Typically used to filter by
error number. Used with When keyword to specify circumstances under which the error is caught.
catchStatements
Optional. Statement(s) to handle errors occurring in the associated Try block. Can be a compound statement.
Exit Try
Optional. Keyword that breaks out of the Try...Catch...Finally structure. Execution resumes with the code immediately
following the End Try statement. The Finally statement will still be executed. Not allowed in Finally blocks.
Finally
Optional. A Finally block is always executed when execution leaves any part of the Try statement.
finallyStatements
Optional. Statement(s) that are executed after all other error processing has occurred.
End Try
Terminates the Try...Catch...Finally structure.
Remarks
Local variables from a Try block are not available in a Catch block because they are separate blocks. If you want to use a
variable in more than one block, declare the variable outside the Try...Catch...Finally structure.
The Try block contains code where an error can occur, while the Catch block contains code to handle any error that does
occur. If an error occurs in the Try block, program control is passed to the appropriate Catch statement for disposition. The
exception argument is an instance of the Exception class or a class that derives from the Exception class. The Exception
class instance corresponds to the error that occurred in the Try block. The instance contains information about the error,
including, among other things, its number and message.
If a Catch statement does not specify an exception argument, it catches any kind of system or application exception. You
should always use this variation as the last Catch block in the Try...Catch...Finally structure, after catching all the specific
exceptions you anticipate. Control flow can never reach a Catch block that follows a Catch without an exception argument.
In partial-trust situations, such as an application hosted on a network share, Try...Catch...Finally does not catch security
exceptions that occur before the method containing the call is invoked. The following example, when placed on a server share
and run from there, produces the error "System.Security.SecurityException: Request Failed." For more information on security
exceptions, see the SecurityException class.
VB
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
Try
Process.Start("http://www.microsoft.com")
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
End Try
End Sub
In such a partial-trust situation, you need to put the Process.Start statement in a separate Sub. The initial call to the Sub will
fail, allowing Try...Catch to catch it before the Sub containing Process.Start is launched and the security exception produced.
Note
If a Try statement does not contain at least one Catch block, it must contain a Finally block.
Example
The following simplified example illustrates the structure of the Try...Catch...Finally statement.
VB
Public Sub TryExample()
Dim x As Integer = 5 ' Declare variables.
Dim y As Integer = 0
Try ' Set up structured error handling.
x = x \ y ' Cause a "Divide by Zero" error.
Catch ex As Exception When y = 0 ' Catch the error.
Beep()
MsgBox("You tried to divide by 0.") ' Show an explanatory message.
Finally
Beep() ' This line is executed no matter what.
End Try
End Sub
See Also
Reference
End Statement
Err Object (Visual Basic)
Exit Statement (Visual Basic)
On Error Statement (Visual Basic)
GoTo Statement
Exception
Visual Basic Language Reference
Parts
resourcelist
Required if you do not supply resourceexpression. List of one or more system resources that this Using block controls.
resourceexpression
Required if you do not supply resourcelist. Reference variable or expression referring to a system resource to be controlled
by this Using block.
statements
Optional. Block of statements that the Using block runs.
End Using
Required. Terminates the definition of the Using block and disposes of all the resources that it controls.
Each resource in the resourcelist part has the following syntax and parts:
resourcename As New resourcetype [ ( [ arglist ] ) ]
-or-
resourcename As resourcetype = resourceexpression
resourcelist Parts
resourcename
Required. Reference variable that refers to a system resource that the Using block controls.
New
Required if the Using statement acquires the resource. If you have already acquired the resource, use the second syntax
alternative.
resourcetype
Required. The class of the resource. The class must implement the IDisposable interface.
arglist
Optional. List of arguments you are passing to the constructor to create an instance of resourcetype. See Parameter List.
resourceexpression
Required. Variable or expression referring to a system resource satisfying the requirements of resourcetype. If you use the
second syntax alternative, you must acquire the resource before passing control to the Using statement.
Remarks
Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using
block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available
for other code to use.
Managed resources are disposed of by the .NET Framework garbage collector (GC) without any extra coding on your part. You
do not need a Using block for managed resources.
A Using block has three parts: acquisition, usage, and disposal.
Acquisition means creating a variable and initializing it to refer to the system resource. The Using statement can acquire
one or more resources, or you can acquire exactly one resource before entering the block and supply it to the Using
statement. If you supply resourceexpression, you must acquire the resource before passing control to the Using
statement.
Usage means accessing the resources and performing actions with them. The statements between Using and End Using
represent the usage of the resources.
Disposal means calling the Dispose method on the object in resourcename. This allows the object to cleanly terminate its
unmanaged resource. The End Using statement disposes of the resources under the Using block's control.
Behavior
A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block
disposes of them. Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. This
is true even in the case of an unhandled exception, except for a StackOverflowException.
The scope of every resource variable acquired by the Using statement is limited to the Using block.
If you specify more than one system resource in the Using statement, the effect is the same as if you nested Using blocks one
within another.
Structured Exception Handling Within a Using Block
If you need to handle an exception that might occur within the Using block, you can add a complete Try...Finally construction
to it. If you need to handle the case where the Using statement is not successful in acquiring a resource, you can test to see if
resourcename is Nothing.
Structured Exception Handling Instead of a Using Block
If you need finer control over the acquisition of the resources, or you need additional code in the Finally block, you can rewrite
the Using block as a Try...Finally construction. The following example shows skeleton Try and Using constructions that are
equivalent in the acquisition and disposal of resource.
Note
The code inside the Using block should not assign the object in resourcename to another variable. When you exit the Using
block, the resource is disposed, and the other variable cannot access the resource to which it points.
Example
The following example uses a Using block to acquire a new font. This guarantees that the system calls the Dispose method on
the font when your code exits the block.
VB
Public Sub setbigbold(ByVal c As Control)
Using nf As New System.Drawing.Font("Arial", 12.0F, _
System.Drawing.FontStyle.Bold)
c.Font = nf
c.Text = "This is 12-point Arial bold"
End Using
End Sub
See Also
Tasks
How to: Dispose of a System Resource
Reference
Try...Catch...Finally Statement (Visual Basic)
IDisposable
System.Drawing
Font
Visual Basic Language Reference
While condition
[ statements ]
[ Exit While ]
[ statements ]
End While
Parts
condition
Required. Boolean expression. If condition is Nothing, Visual Basic treats it as False.
statements
Optional. One or more statements following While, which run every time condition is True.
Exit While
Optional. Transfers control out of the While block.
End While
Required. Terminates the definition of the While block.
Remarks
Use a While...End While structure when you want to repeat a set of statements an indefinite number of times, as long as a
condition remains True. If you want more flexibility with where you test the condition or what result you test it for, you might
prefer the Do...Loop Statement (Visual Basic). If you want to repeat the statements a set number of times, the
For...Next Statement (Visual Basic) is usually a better choice.
If condition is True, all of the statements run until the End While statement is encountered. Control then returns to the While
statement and condition is again checked. If condition is still True, the process is repeated. If it is False, control passes to the
statement following the End While statement.
Rules
Nature of Condition. The condition usually results from a comparison of two values, but it can be any expression that
evaluates to a Boolean Data Type (Visual Basic) value (True or False). This includes values of other data types, such as
numeric types, that have been converted to Boolean.
Testing the Condition. The While statement always checks the condition before it begins the loop. Looping continues
while the condition remains True.
Number of Iterations. If condition is False when you first enter the loop, it does not run even once.
Nesting Loops. You can nest While loops by placing one loop within another. You can also nest different kinds of
control structures within one another. For more information, see Nested Control Structures.
Transferring Out of the Loop. The Exit Statement (Visual Basic) transfers control immediately to the statement
following the End While statement. You might want to exit a loop if you detect a condition that makes it unnecessary or
impossible to continue iterating, such as an erroneous value or a termination request. You can place any number of Exit
While statements anywhere in the While loop. Exit While is often used after evaluating some condition, for example in
an If...Then...Else structure.
Endless Loops. One use of Exit While is to test for a condition that could cause an endless loop, which is a loop that
could run an extremely large or even infinite number of times. If you detect such a condition, you can use Exit While to
escape the loop. For more information, see Do...Loop Statement (Visual Basic).
Example
This example uses the While...End While structure to increment a counter variable. The statements in the loop run as long as
the condition evaluates to True.
VB
Dim counter As Integer = 0
While counter < 20
counter += 1
' Insert code to use current value of counter.
End While
MsgBox("While loop ran " & CStr(counter) & " times")
See Also
Reference
Do...Loop Statement (Visual Basic)
For...Next Statement (Visual Basic)
Boolean Data Type (Visual Basic)
Exit Statement (Visual Basic)
Concepts
Loop Structures
Nested Control Structures
Visual Basic Language Reference
With object
[ statements ]
End With
Parts
object
Required. Variable or expression. Can evaluate to any data type, including elementary types.
statements
Optional. One or more statements between With and End With that run on object.
End With
Required. Terminates the definition of the With block.
Remarks
With...End With allows you to perform a series of statements on a specified object without requalifying the name of the
object. If the qualification path to the object is long, using With...End With can improve your performance. A With block also
reduces repetitive typing of the qualification path and the risk of mistyping one of its elements.
For example, to change a number of different properties on a single object, place the property assignment statements inside
the With...End With, referring to the object only once instead of for each property assignment.
Rules
Data Types. The data type of object can be any class or structure type, or even a Visual Basic elementary type such as
Integer. The .NET Framework supports all elementary types with classes or structures, which have members you can
access inside a With block.
Declaration. You must declare object before you enter the With block. You cannot declare it in the With statement.
Number of Iterations. A With block is not an iterative construction. Unless there is a loop inside the block, the
statements run only once.
Nesting Structures. You can nest With...End With structures by placing one structure within another. For an example,
see How to: Perform Multiple Actions on an Object.
However, because members of outer statements are masked inside the inner statements, you must provide a fully
qualified object reference in an inner With block to any member of an object in an outer With block.
You can also nest different kinds of control structures within one another. For more information, see
Nested Control Structures.
Transferring Out of the Structure. Visual Basic does not support the Exit Statement (Visual Basic) to transfer control
out of a With block. If you need to exit before all the statements have been executed, put a label on the End With
statement and use the GoTo Statement to branch to it. For more information, see How to: Label Statements.
You cannot transfer control either from outside a With block to inside it, or from inside it to the outside. You can call a
procedure from inside the block, but control returns to the following statement.
Accessing Other Objects. Once you have entered a With block, you cannot reassign object until you have passed the
End With statement. Therefore, you can access the methods and properties of only the specified object without
qualifying them. You can use methods and properties of other objects, but you must qualify them with their object
names.
Example
The following example uses a With block to execute a series of statements on a single object. The example assumes that object
testObject has already been created and exposes the referenced properties.
VB
With testObject
.Height = 100
.Text = "Hello, World"
.ForeColor = System.Drawing.Color.Green
.Font = New System.Drawing.Font(.Font, _
System.Drawing.FontStyle.Bold)
End With
See Also
Tasks
How to: Perform Multiple Actions on an Object
How to: Label Statements
Reference
Exit Statement (Visual Basic)
GoTo Statement
Concepts
Nested Control Structures
Visual Basic Language Reference
Constant (Const Statement (Visual Basic)) Not allowed Private (Public in Structure, not allowe Public
d in Interface)
Procedure (Function Statement (Visual Basic), Not allowed Public Not allowed
Sub Statement (Visual Basic))
External reference (Declare Statement) Not allowed Public (not allowed in Interface) Not allowed
Operator (Operator Statement) Not allowed Public (not allowed in Interface or Mod Not allowed
ule)
Default property (Default (Visual Basic)) Not allowed Public (not allowed in Module) Not allowed
Attribute List
Specifies the attributes to be applied to a declared programming element. Multiple attributes are separated by commas.
Following is the syntax for one attribute.
Parts
attributemodifier
Required for attributes applied at the beginning of a source file. Can be Assembly or Module.
attributename
Required. Name of the attribute.
attributearguments
Optional. List of positional arguments for this attribute. Multiple arguments are separated by commas.
attributeinitializer
Optional. List of variable or property initializers for this attribute. Multiple initializers are separated by commas.
Remarks
You can apply one or more attributes to nearly any programming element (types, procedures, properties, and so forth).
Attributes appear in your assembly's metadata, and they can help you annotate your code or specify how to use a particular
programming element. You can apply attributes defined by Visual Basic and the .NET Framework, and you can define your own
attributes.
For more information on when to use attributes, see Attributes in Visual Basic and Common Uses for Attributes. For
information on attribute names, see Declared Element Names.
Rules
Placement. You can apply attributes to most declared programming elements. To apply one or more attributes, you
place an attribute block at the beginning of the element declaration. Each entry in the attribute list specifies an attribute
you wish to apply, and the modifier and arguments you are using for this invocation of the attribute.
Angle Brackets. If you supply an attribute list, you must enclose it in angle brackets ("<" and ">").
Part of the Declaration. The attribute must be part of the element declaration, not a separate statement. You can use
the line-continuation sequence (" _") to extend the declaration statement onto multiple source-code lines.
Modifiers. An attribute modifier (Assembly or Module) is required on every attribute applied to a programming
element at the beginning of a source file. Attribute modifiers are not allowed on attributes applied to elements that are
not at the beginning of a source file.
Arguments. All positional arguments for an attribute must precede any variable or property initializers.
Example
The following example applies the DllImportAttribute attribute to a skeleton definition of a Function procedure.
VB
<DllImportAttribute("kernel32.dll", EntryPoint:="MoveFileW", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function moveFile(ByVal src As String, _
ByVal dst As String) As Boolean
' This function copies a file from the path src to the path dst.
' Leave this function empty. The DLLImport attribute forces calls
' to moveFile to be forwarded to MoveFileW in KERNEL32.DLL.
End Function
DllImportAttribute indicates that the attributed procedure represents an entry point in an unmanaged dynamic-link library
(DLL). The attribute supplies the DLL name as a positional argument and the other information as variable initializers.
See Also
Tasks
How to: Break and Combine Statements in Code
Reference
Assembly
Module (Visual Basic)
Concepts
Common Uses for Attributes
Application of Attributes
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
Parameter List
Specifies the parameters a procedure expects when it is called. Multiple parameters are separated by commas. Following is the
syntax for one parameter.
Parts
attributelist
Optional. List of attributes that apply to this parameter. You must enclose the Attribute List in angle brackets ("<" and ">").
Optional
Optional. Specifies that this parameter is not required when the procedure is called.
ByVal
Optional. Specifies that the procedure cannot replace or reassign the variable element underlying the corresponding
argument in the calling code.
ByRef
Optional. Specifies that the procedure can modify the underlying variable element in the calling code the same way the
calling code itself can.
ParamArray
Optional. Specifies that the last parameter in the parameter list is an optional array of elements of the specified data type.
This allows the calling code to pass an arbitrary number of arguments to the procedure.
parametername
Required. Name of the local variable representing the parameter.
parametertype
Required if Option Strict is On. Data type of the local variable representing the parameter.
defaultvalue
Required for Optional parameters. Any constant or constant expression that evaluates to the data type of the parameter. If
the type is Object, or a class, interface, array, or structure, the default value can only be Nothing.
Remarks
Parameters are surrounded by parentheses and separated by commas. A parameter can be declared with any data type. If you
do not specify parametertype, it defaults to Object.
When the calling code calls the procedure, it passes an argument to each required parameter. For more information, see
Differences Between Parameters and Arguments.
The argument the calling code passes to each parameter is a pointer to an underlying element in the calling code. If this
element is nonvariable (a constant, literal, enumeration, or expression), it is not possible for any code to change it. If it is a
variable element (a declared variable, field, property, array element, or structure element), the calling code can change it. For
more information, see Differences Between Modifiable and Nonmodifiable Arguments.
If a variable element is passed ByRef, the procedure can change it as well. For more information, see
Differences Between Passing an Argument By Value and By Reference.
Rules
Parentheses. If you specify a parameter list, you must enclose it in parentheses. If there are no parameters, you can still
use parentheses enclosing an empty list. This improves the readability of your code by clarifying that the element is a
procedure.
Optional Parameters. If you use the Optional modifier on a parameter, all subsequent parameters in the list must also
be optional and be declared using the Optional modifier.
Every optional parameter declaration must supply the defaultvalue clause.
Parameter Arrays. You must specify ByVal for a ParamArray parameter.
You cannot use both Optional and ParamArray in the same parameter list.
Passing Mechanism. The default mechanism for every argument is ByVal, which means the procedure cannot change
the underlying variable element. However, if the element is a reference type, the procedure can modify the contents or
members of the underlying object, even though it cannot replace or reassign the object itself.
Parameter Names. If the parameter's data type is an array, follow parametername immediately by parentheses. For
more information on parameter names, see Declared Element Names.
Example
The following example shows a Function procedure that defines two parameters.
VB
Public Function howMany(ByVal ch As Char, ByVal st As String) As Integer
End Function
Dim howManyA As Integer = howMany("a"c, "How many a's in this string?")
See Also
Tasks
How to: Break and Combine Statements in Code
Reference
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Declare Statement
Structure Statement
Option Strict Statement
DllImportAttribute
Concepts
Application of Attributes
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference
Type List
Specifies the type parameters for a generic programming element. Multiple parameters are separated by commas. Following is
the syntax for one type parameter.
typename [ As constraintlist ]
Parts
typename
Required. Name of the type parameter. This is a placeholder, to be replaced by a defined type supplied by the corresponding
type argument.
constraintlist
Optional. List of requirements that constrain the data type that can be supplied for typename. If you have multiple
constraints, enclose them in curly braces ({ }) and separate them with commas. You must introduce the constraint list with
the As keyword. You use As only once, at the beginning of the list.
Remarks
Every generic programming element must take at least one type parameter. A type parameter is a placeholder for a specific
type (a constructed element) that client code specifies when it creates an instance of the generic type. You can define a generic
class, structure, interface, procedure, or delegate.
For more information on when to define a generic type, see Generic Types in Visual Basic. For more information on type
parameter names, see Declared Element Names.
Rules
Parentheses. If you supply a type parameter list, you must enclose it in parentheses, and you must introduce the list
with the Of keyword. You use Of only once, at the beginning of the list.
Constraints. A list of constraints on a type parameter can include the following items in any combination:
Any number of interfaces. The supplied type must implement every interface in this list.
At most one class. The supplied type must inherit from that class.
The New (Visual Basic) keyword. The supplied type must expose a parameterless constructor that your generic
type can access. This is useful if you constrain a type parameter by one or more interfaces. A type that
implements interfaces does not necessarily expose a constructor, and depending on the access level of a
constructor, the code within the generic type might not be able to access it.
Either the Class (Visual Basic) keyword or the Structure (Visual Basic) keyword. If you include Class, the supplied
type must be a reference type. If you include Structure, the supplied type must be a value type. You cannot
include both Class and Structure in the same constraintlist.
The supplied type must satisfy every requirement you include in constraintlist.
Constraints on each type parameter are independent of constraints on other type parameters.
Behavior
Compile-Time Substitution. When you create a constructed type from a generic programming element, you supply a
defined type for each type parameter. The Visual Basic compiler substitutes that supplied type for every occurrence of
typename within the generic element.
Absence of Constraints. If you do not specify any constraints on a type parameter, your code is limited to the
operations and members supported by the Object Data Type for that type parameter.
Example
The following example shows a skeleton definition of a generic dictionary class, including a skeleton function to add a new
entry to the dictionary.
VB
Public Class dictionary(Of entryType, keyType As {IComparable, IFormattable, New})
Public Sub add(ByVal et As entryType, ByVal kt As keyType)
Dim dk As keyType
If kt.CompareTo(dk) = 0 Then
End If
End Sub
End Class
Because dictionary is generic, the code that uses it can create a variety of objects from it, each having the same functionality
but acting on a different data type. The following example shows a line of code that creates a dictionary object with String
entries and Integer keys.
VB
Dim dictInt As New dictionary(Of String, Integer)
The following example shows the equivalent skeleton definition generated by the preceding example.
VB
Public Class dictionary
Public Sub add(ByVal et As String, ByVal kt As Integer)
Dim dk As Integer
If kt.CompareTo(dk) = 0 Then
End If
End Sub
End Class
See Also
Tasks
How to: Use a Generic Class
Reference
Of
New (Visual Basic)
Class (Visual Basic)
Structure (Visual Basic)
Object Data Type
Function Statement (Visual Basic)
Structure Statement
Sub Statement (Visual Basic)
Concepts
Access Levels in Visual Basic
Visual Basic Language Reference
The compiler processes any tag that is valid XML. The following tags provide commonly used functionality in user
documentation.
<typeparam> 1 <value>
See Also
Tasks
How to: Create XML Documentation in Visual Basic
Reference
/doc
Concepts
Documenting Your Code with XML (Visual Basic)
Visual Basic Language Reference
<c>text</c>
Parameters
text
The text you would like to indicate as code.
Remarks
The <c> tag gives you a way to indicate that text within a description should be marked as code. Use <code> (Visual Basic) to
indicate multiple lines as code.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <c> tag in the summary section to indicate that Counter is code.
VB
''' <summary>
''' Resets the value the <c>Counter</c> field.
''' </summary>
Public Sub ResetCounter()
counterValue = 0
End Sub
Private counterValue As Integer = 0
''' <summary>
''' Returns the number of times Counter was called.
''' </summary>
''' <value>Number of times Counter was called.</value>
Public ReadOnly Property Counter() As Integer
Get
counterValue += 1
Return counterValue
End Get
End Property
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<code>content</code>
Parameters
content
The text to mark as code.
Remarks
Use the <code> tag to indicate multiple lines as code. Use <c> (Visual Basic) to indicate that text within a description should be
marked as code.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <code> tag to include example code for using the ID field.
VB
Public Class Employee
''' <remarks>
''' <example> This sample shows how to set the <c>ID</c> field.
''' <code>
''' Dim alice As New Employee
''' alice.ID = 1234
''' </code>
''' </example>
''' </remarks>
Public ID As Integer
End Class
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<example>description</example>
Parameters
description
A description of the code sample.
Remarks
The <example> tag lets you specify an example of how to use a method or other library member. This commonly involves using
the <code> (Visual Basic) tag.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <example> tag to include an example for using the ID field.
VB
Public Class Employee
''' <remarks>
''' <example> This sample shows how to set the <c>ID</c> field.
''' <code>
''' Dim alice As New Employee
''' alice.ID = 1234
''' </code>
''' </example>
''' </remarks>
Public ID As Integer
End Class
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<exception cref="member">description</exception>
Parameters
member
A reference to an exception that is available from the current compilation environment. The compiler checks that the given
exception exists and translates member to the canonical element name in the output XML. member must appear within
double quotation marks (" ").
description
A description.
Remarks
Use the <exception> tag to specify which exceptions can be thrown. This tag is applied to a method definition.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <exception> tag to describe an exception that the IntDivide function can throw.
VB
''' <exception cref="System.OverflowException">
''' Thrown when <paramref name="denominator"/><c> = 0</c>.
''' </exception>
Public Function IntDivide( _
ByVal numerator As Integer, _
ByVal denominator As Integer _
) As Integer
Return numerator \ denominator
End Function
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
Parameters
filename
Required. The name of the file containing the documentation. The file name can be qualified with a path. Enclose filename in
double quotation marks (" ").
tagpath
Required. The path of the tags in filename that leads to the tag name. Enclose the path in double quotation marks (" ").
name
Required. The name specifier in the tag that precedes the comments. Name will have an id.
id
Required. The ID for the tag that precedes the comments. Enclose the ID in single quotation marks (' ').
Remarks
Use the <include> tag to refer to comments in another file that describe the types and members in your source code. This is an
alternative to placing documentation comments directly in your source code file.
The <include> tag uses the W3C XML Path Language (XPath) Version 1.0 Recommendation. More information for ways to
customize your <include> use is available at http://www.w3.org/TR/xpath.
Example
This example uses the <include> tag to import member documentation comments from a file called commentFile.xml.
VB
''' <include file="commentFile.xml"
''' path="Docs/Members[@name='Open']/*" />
Public Sub Open(ByVal filename As String)
' Code goes here.
End Sub
''' <include file="commentFile.xml"
''' path="Docs/Members[@name='Close']/*" />
Public Sub Close(ByVal filename As String)
' Code goes here.
End Sub
<Docs>
<Members name="Open">
<summary>Opens a file.</summary>
<param name="filename">File name to open.</param>
</Members>
<Members name="Close">
<summary>Closes a file.</summary>
<param name="filename">File name to close.</param>
</Members>
</Docs>
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<list type="type">
<listheader>
<term>term</term>
<description>description</description>
</listheader>
<item>
<term>term</term>
<description>description</description>
</item>
</list>
Parameters
type
The type of the list. Must be a "bullet" for a bulleted list, "number" for a numbered list, or "table" for a two-column table.
term
Only used when type is "table". A term to define, which is defined in the description tag.
description
When type is "bullet" or "number", description is an item in the list When type is "table", description is the definition of term.
Remarks
The <listheader> block is used to define the heading of either a table or definition list. When defining a table, you only need to
supply an entry for term in the heading.
Each item in the list is specified with an <item> block. When creating a definition list, you will need to specify both term and
description. However, for a table, bulleted list, or numbered list, you only need to supply an entry for description.
A list or table can have as many <item> blocks as needed.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <list> tag to define a bulleted list in the remarks section.
VB
''' <remarks>Before calling the <c>Reset</c> method, be sure to:
''' <list type="bullet">
''' <item><description>Close all connections.</description></item>
''' <item><description>Save the object state.</description></item>
''' </list>
''' </remarks>
Public Sub Reset()
' Code goes here.
End Sub
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<para>content</para>
Parameters
content
The text of the paragraph.
Remarks
The <para> tag is for use inside a tag, such as <summary> (Visual Basic), <remarks> (Visual Basic), or <returns> (Visual Basic),
and lets you add structure to the text.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <para> tag to split the remarks section for the UpdateRecord method into two paragraphs.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<param name="name">description</param>
Parameters
name
The name of a method parameter. Enclose the name in double quotation marks (" ").
description
A description for the parameter.
Remarks
The <param> tag should be used in the comment for a method declaration to describe one of the parameters for the method.
The text for the <param> tag will be displayed in IntelliSense Features and in the Object Browser.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <param> tag to describe the id parameter.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<paramref name="name"/>
Parameters
name
The name of the parameter to refer to. Enclose the name in double quotation marks (" ").
Remarks
The <paramref> tag gives you a way to indicate that a word is a parameter. The XML file can be processed to format this
parameter in some distinct way.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <paramref> tag to refer to the id parameter.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<permission cref="member">description</permission>
Parameters
member
A reference to a member or field that is available to be called from the current compilation environment. The compiler
checks that the given code element exists and translates member to the canonical element name in the output XML. Enclose
member in quotation marks (" ").
description
A description of the access to the member.
Remarks
Use the <permission> tag to document the access of a member. Use the PermissionSet class to specify access to a member.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <permission> tag to describe that the FileIOPermission is required by the ReadFile method.
VB
''' <permission cref="System.Security.Permissions.FileIOPermission">
''' Needs full access to the specified file.
''' </permission>
Public Sub ReadFile(ByVal filename As String)
' Code goes here.
End Sub
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<remarks>description</remarks>
Parameters
description
A description of the member.
Remarks
Use the <remarks> tag to add information about a type, supplementing the information specified with
<summary> (Visual Basic). This information is displayed in the Object Browser.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <remarks> tag to explain what the UpdateRecord method does.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<returns>description</returns>
Parameters
description
A description of the return value.
Remarks
Use the <returns> tag in the comment for a method declaration to describe the return value.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <returns> tag to explain what the DoesRecordExist function returns.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<see cref="member"/>
Parameters
member
A reference to a member or field that is available to be called from the current compilation environment. The compiler
checks that the given code element exists and passes member to the element name in the output XML. member must appear
within double quotation marks (" ").
Remarks
Use the <see> tag to specify a link from within text. Use <seealso> (Visual Basic) to indicate text that you might want to appear
in a "See Also" section.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <see> tag in the UpdateRecord remarks section to refer to the DoesRecordExist method.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<seealso cref="member"/>
Parameters
member
A reference to a member or field that is available to be called from the current compilation environment. The compiler
checks that the given code element exists and passes member to the element name in the output XML. member must appear
within double quotation marks (" ").
Remarks
Use the <seealso> tag to specify the text that you want to appear in a See Also section. Use <see> (Visual Basic) to specify a
link from within text.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <seealso> tag in the DoesRecordExist remarks section to refer to the UpdateRecord method.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<summary>description</summary>
Parameters
description
A summary of the object.
Remarks
Use the <summary> tag to describe a type or a type member. Use <remarks> (Visual Basic) to add supplemental information to
a type description.
The text for the <summary> tag is the only source of information about the type in IntelliSense, and is also displayed in the
Object Browser.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <summary> tag to describe the ResetCounter method and Counter property.
VB
''' <summary>
''' Resets the value the <c>Counter</c> field.
''' </summary>
Public Sub ResetCounter()
counterValue = 0
End Sub
Private counterValue As Integer = 0
''' <summary>
''' Returns the number of times Counter was called.
''' </summary>
''' <value>Number of times Counter was called.</value>
Public ReadOnly Property Counter() As Integer
Get
counterValue += 1
Return counterValue
End Get
End Property
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<typeparam name="name">description</typeparam>
Parameters
name
The name of the type parameter. Enclose the name in double quotation marks (" ").
description
A description of the type parameter.
Remarks
Use the <typeparam> tag in the comment for a generic type or generic member declaration to describe one of the type
parameters.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <typeparam> tag to describe the id parameter.
VB
''' <typeparam name="T">
''' The base item type. Must implement IComparable.
''' </typeparam>
Public Class itemManager(Of T As IComparable)
' Insert code that defines class members.
End Class
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
<value>property-description</value>
Parameters
property-description
A description for the property.
Remarks
Use the <value> tag to describe a property. Note that when you add a property using the code wizard in the Visual Studio
development environment, it will add a <summary> (Visual Basic) tag for the new property. You should then manually add a
<value> tag to describe the value that the property represents.
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference
While developing in Visual Basic, you can get information from Help on a message by pressing F1. Likewise, you can press F1
on error messages shown in the Task List window.
In This Section
How to: Get Information about Visual Basic Compiler Errors
Explains the concept of compiler errors and how to get help for particular error messages.
How to: Get Information about Visual Basic Run-Time Errors
Explains the concept of run-time errors and how to get help for particular error messages.
Visual Basic Compiler Messages
Contains the Visual Basic error messages that occur at compile time.
Visual Basic Run-Time Messages
Contains the Visual Basic error messages that occur at run time
Related Sections
Exception and Error Handling in Visual Basic
Lists links to topics related to exception handling in Visual Basic.
Walkthrough: Structured Exception Handling
Illustrates how to use the Try...Catch...Finally statement to handle exceptions.
Visual Basic Language Reference
See Also
Tasks
How to: Get Information about Visual Basic Run-Time Errors
How to: Debug Code in the Editor
How to: Correct Compiler Errors with Auto Correction
Concepts
Configuring Warnings in Visual Basic
Visual Basic Language Reference
See Also
Tasks
How to: Get Information about Visual Basic Compiler Errors
How to: Correct Run-Time Errors with the Exception Assistant
Reference
Try...Catch...Finally Statement (Visual Basic)
Concepts
Structured Exception Handling Overview for Visual Basic
Visual Basic Language Concepts
6 Device unavailable
8
9 Unable to sink events of object because the object is already firing events to the maximum number of event receivers it supports
6
9 Cannot call friend function on object which is not an instance of defining class
7
9 A property or method call cannot include a reference to a private object, either as an argument or as a return value
8
4 File name or class name not found during Automation operation (Visual Basic)
3
2
4 Automation error
4
0
4 Connection to type library or object library for remote process has been lost
4
2
4 Property let procedure not defined and property get procedure did not return an object
5
1
4 The remote server machine does not exist or is unavailable (Visual Basic)
6
2
4 Printer error
8
2
The message Application-defined or object-defined error applies to an error code that Visual Basic does not recognize.
See Also
Tasks
Troubleshooting Exception Handling
Reference
On Error Statement (Visual Basic)
Err Object (Visual Basic)
Concepts
Introduction to Exception Handling
Unstructured Exception Handling Overview
Choosing When to Use Structured and Unstructured Exception Handling
Other Resources
Structured Exception Handling in Visual Basic
Visual Basic Reference: Error Messages
'>' expected
The syntax for the specified code is incorrect. This error often indicates that the closing angle bracket for an attribute is missing.
Error ID: BC30636
To correct this error
Check the syntax for the code being used.
See Also
Concepts
Declaration Statements in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Reference: Error Messages
See Also
Concepts
Keywords as Element Names in Code
Visual Basic Naming Conventions
Visual Basic Reference: Error Messages
This error can happen if two classes have the same name and are in nested namespaces with underscores in their names.
When the compiler constructs the new property names for the classes, there is still a name collision.
Error ID: BC36015
To correct this error
1. Rename the new form.
2. Rename the namespaces.
Avoid naming any class or structure with the same name as an existing one.
See Also
Reference
My.Forms Object
Form
MyGroupCollectionAttribute
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Visual Basic Reference: Error Messages
See Also
Reference
Implements Statement
Concepts
Implements Keyword and Implements Statement
Visual Basic Reference: Error Messages
3. When implementing a property, make sure that ReadOnly or WriteOnly is used in the same way as in the interface
definition.
4. When implementing a property, declare Get and Set procedures, as appropriate.
See Also
Reference
Implements Statement
Concepts
Implements Keyword and Implements Statement
Visual Basic Reference: Error Messages
See Also
Reference
Overridable
Overrides
Shadows
Visual Basic Reference: Error Messages
See Also
Concepts
Overriding Properties and Methods
Visual Basic Reference: Error Messages
See Also
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Visual Basic Reference: Error Messages
See Also
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Visual Basic Reference: Error Messages