Hosted by RachaelArnold <www.rachaelarnold.com>

Visual Basic 2005 Express - Default Installation Code Snippets

This document lists the embedded name and description of every code snippet included in a basic installation of Visual Basic 2005 Express. The snippets are arranged alphabetially by VBE categorization.

Table of Contents

  1. Application
  2. Collections and Arrays
  3. Common Code Patterns
    1. Conditionals and Loops
    2. Exception Handling
    3. Properties and Procedures
    4. Types
  4. Connectivity
  5. Database
  6. DataTypes
  7. FileSystem
  8. Math
  9. WindowsForms
    1. Clipboard
    2. Controls
      1. Button
      2. Calendar
      3. ComboBox
      4. DatagridView
      5. ListBox
      6. ListView
      7. Menu
      8. ProgressBar
      9. RadioButton
      10. RichTextBox
      11. Textbox
      12. TreeView
    3. Drawing
    4. Fonts
    5. Forms
    6. Sound
  10. XML

Application

Activate a Running Application by Name

Activates a running application using the name of the application.

Activate a Running Application by Process ID

Activates a running application using the process ID of the application.

Capture Output from a Console Application

Saves the output from a command console application to a string.

Change the Foreground and Background Colors in a Console Window

Changes the background and text color of the console window.

Check for Current Version using ClickOnce

Checks for current version using ClickOnce.

Check for Update to ClickOnce Application

Checks whether updates to the application are available for download.

Clear the Console Window

Clears the console window.

Delete File from Isolated Storage

Deletes file from isolated storage.

Determine the Amount of Isolated Storage Available.

Determines the Amount of Isolated Storage Available.

Determine the Scope of Isolated Storage

Determines the scope of the isolated storage.

Download Files Synchronously with ClickOnce

Downloads files synchronously using ClickOnce.

Find the Names of Resources in an Assembly

Returns a list of all the resources in an assembly.

Load a Cursor File from an Assembly

Sets the cursor of a Windows form from a cursor file that is an embedded resource of the application.

Load an Assembly at Run Time

Loads an assembly at run time.

Make an Asynchronous Method Call

Makes an asynchronous method call using the BackgroundWorker component.

Read and Write from the Console Window

Writes a prompt and then reads in the user request. It is run from a console application.

Read Command Line Arguments

Iterates through the command line arguments.

Read Text from Isolated Storage

Reads the text from a file in isolated storage.

Retrieve an Image that Is an Application Resource

Assigns an image resource in the My Application designer to the PictureBox1's Image property.

Retrieve a Text File from an Assembly's Resources

Retrieves the text from a file that is an embedded resource of an assembly.

Save Text in Isolated Storage

Writes a string to the assembly or user-isolated storage.

Send Keystrokes to an Application

Sends keystrokes to an application.

Stop an Application

Closes all the running instances of Notepad.

Update Application Asynchronously using ClickOnce

Updates ClickOnce application asynchronously.

Update Application Synchronously using ClickOnce

Update a ClickOnce application Synchronous.

Write a Message to the Application Log

Writes a message to the application log.

Write to a Text file

Writes a message to the application event log.

Collections and Arrays

Convert an ArrayList to a Strongly Typed Array

Converts an ArrayList to a strongly typed array using ToArray(Type)

Create a list with items of a single type.

Creates a collection to hold a specific type of items.

Create a keyed collection with one item type.

Creates a dictionary to hold specific types of items indexed by key.

Create a sorted dictionary.

Creates a sorted dictionary to hold a specific type of items.

Define a type comparer to be used in sorting routines.

Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.

Index into a strongly typed dictionary using a key.

Indexes into strongly typed dictionary by using a key.

Initialize a One-Dimensional Array

Initializes a one-dimensional array.

Iterate through a collection.

Iterates through specific item types in a collection.

Iterate through a dictionary.

Iterates through all the items in a dictionary.

Iterate through a sorted dictionary by key.

Iterates through all the items in a dictionary based on the sorted list of keys.

Locate an Element in an Array

Finds the index of a given element in an array.

Sort An Array

Declares an array of String objects, populates it, and then sorts it alphabetically.

Common Code Patterns

Conditionals and Loops

Build Only Selected Portions of the Source Code by Using #If

Uses the #If compiler directive to control which block of code is compiled into the assembly.

Do...Loop Until Statement

Loops until a condition is True.

Do...Loop While Statement

Loops while a condition is True.

Do Until...Loop Statement

Loops until a condition is True.

Do While...Loop Statement

Loops while a condition is True.

For Each...Next Statement

Loops through a collection of items.

For...Next Statement

Loops through a sequence of numbers.

If...Else...End If Statement

Inserts an If...Else...End If statement.

If...ElseIf...Else...End If Statement

Inserts an If...ElseIf...Else...End If statement.

If..End If Statement

Inserts an If..End If statement.

Select Case Statement

Inserts a Select Case statement.

While...End While Statement

Inserts a While...End While statement.

Exception Handling

Define An Exception Class

Provides a basic implementation for a new exception class.

Throw an Exception

Throws an Exception.

Try...Catch...End Try Statement

Inserts a Try...Catch...End Try statement.

Try...Catch...Finally...End Try Statement

Inserts a Try...Catch...Finally...End Try statement.

Try...Finally...End Try Statement

Inserts a Try...Finally...End Try statement.

Using Statement

Inserts a Using statement.

Properties and Procedures

Define an Addition Operator (+)

Defines the addition (+) operator on a class.

Define a Function to Call a Windows API

Defines a function to call a Windows API.

Define Comparison Operators (> and <)

Defines the comparison operators (> and <).

Define a CType Operator

Defines the CType Operators on a class.

Declare an Event

Declares an event.

Define a Default Property

Defines a default property or index property.

Define a Sub that is Private

Uses the Sub keyword to define a private method that does not return a value.

Define a Property

Defines a Property with a backing field.

Define a Sub that is Public

Uses the Sub keyword to define a method that does not return a value.

Define Equality Operators (= and <>)

Defines the equality Operators (= and <>).

Define a Function with Generic Parameters

Defines a Function that uses Generic parameters.

Define a Function with a Parameter Array

Defines a Function that takes a variable number of parameters.

Define a Sub that is Overridable

Defines an Overridable Sub.

Define a Function

Uses the Function keyword to define a procedure that returns a value.

Define a Sub

Uses the Sub keyword to define a procedure that does not return a value.

Define a ReadOnly Property

Defines a ReadOnly Property with a backing field.

Define a Sub that Overrides Dispose

Overrides the Dispose Function according to the Dispose Finalize pattern.

Define a Sub with a ByRef parameter

Defines a Sub with an argument whose value can be changed by the code in the method.

Define a WriteOnly Property

Defines a WriteOnly Property with a backing field.

Types

Define an Enumeration

Defines an enumeration.

Define an Enumeration with Custom Values

Defines an enumeration with specified integer values.

Define a New Generic Type

Defines a Generic Type.

Define an Interface

Defines an interface.

Define a Structure

Defines a structure.

Find the Name of an Enumeration Value

Gets the string name of an enumeration value.

Define a Class that Implements IDisposable

Implements the Dispose Finalize pattern.

Connectivity

Convert a Relative Uri to an Absolute Uri

Converts a relative Uri to an absolute Uri

Determine if the Network is Available

Determines whether the network connection is available on the local computer.

Download a File using Http

Downloads a file using http.

Enumerate Serial Ports

Shows how to enumerate serial ports using the My object.

Ping Another Computer

Determines whether the specified Web site responds.

Read Data from a Serial Port

Reads Data from a Serial Port

Create an E-Mail Message

Uses the MailMessage class to send an e-mail message.

Upload a File Using My.Computer.Network

Uploads a local file to the Internet.

Use a SerialPort to Dial a Phone Number

Uses a SerialPort to dial a phone number.

Database

Add a new row to a typed DataTable

Adds a new row to a typed DataTable

Call the ExecuteNonQuery Method of a SqlCommand

Calls ExecuteNonQuery on an existing command. Wraps the execution in a try/finally block to return the connection object to it's previous state

Call the ExecuteReader Method of a SqlCommand

Fetches data from a database using the SqlCommand.ExecuteReader method of an existing data command.

Call the ExecuteScalar Method of a SqlCommand

Executes a SQL statement that returns a single value using the SqlCommand.ExecuteScalar method of an existing data command.

Converts BindingSource.Current to a specific row in a DataTable

Gets the current row within a binding source and converts it to the specific row. Recomended method for capturing the current, rather then using BindingSource.Position which may return a different row based on the sorting of the DataView

Create a DataRelation

Creates a data relation between two data tables in a dataset.

Create an Expression Column

Creates a DataColumn object and sets the DataColumn.Expression property to calculate the order total.

Create a Parameterized SELECT Command

Calls the ExecuteReader method of a data command to execute a Select statement.

Create a Parameterized Stored Procedure

Constructs a command object for executing a stored procedure with parameters

Create a local SQLConnection to SQL Express

Creates a SQL Connection providing replacements for the typical connection name/value pairs for a SQL Express Connection using User Instance=True

Create a Server based SQLConnection to SQL Server

Creates a SQL Connection providing replacements for the typical connection name/value pairs

Extend a TableAdapter w/Partial Classes

Extends a TableAdapter using partial classes. Includes the namespace required to reference existing TableAdapters

Implement Data Try/Catch Blocks

Implements a Try/Catch block that handles Exception, DataException, and all the exceptions that derive from DataException.

Read Access Data into a Dataset

Loads the data from one table in an Access database into a DataSet object.

Return Output Parameter for a TableAdapter Query

TableAdapter methods that "Retun No Value" use ExecuteNonQuery which returns the rows affected. This Snippet returns the value from one of the command parameters on a TableAdapter.

DataTypes

Convert an Array of Bytes into a String

Convert an Array of Bytes into a String

Convert a Number to a Hexadecimal String

Returns the hexadecimal representation of an integer.

Convert a Number to a Octal String

Returns the octal string representation of an integer.

Convert a String to a Byte Array

Converts a string to a byte array.

Convert between Hiragana and Katakana Characters (Japanese Only)

Converts between Hiragana and Katakana characters in a String.

Convert between Simplified Chinese and Traditional Chinese Characters

Converts between Simplified Chinese and Traditional Chinese characters in a String.

Convert between Wide and Narrow Characters

Converts between Wide and Narrow characters in Strings.

Determine the Span between Two Dates

Calculates the difference in days between two dates and also constructs a TimeSpan value for that difference.

Determine the Span between Two Times

Calculates the difference in seconds between two times in the same day, and also constructs a TimeSpan value for that difference.

Generate Multiline String Literals

Constructs a string literal that is three lines long.

Parse an E-mail Address

Returns the user name and provider name from an e-mail address.

Remove Parts of a String

Removes all occurrences of one string from another string.

FileSystem

Compare Two Files

Compares two files.

Copy a Directory

Copies a directory and all its files and subdirectories.

Copy a File

Copies the file Source.txt to a second file, Copy.txt.

Create a File

Creates a new file.

Create a Folder

Creates two new folders on a computer.

Create a Temporary File Name

Creates a name for a temporary file.

Delete a File

Deletes a file after confirming deletion with the user.

Determine if a File Exists

Sets a Boolean variable indicating whether a specified file exists.

Determine if a Folder Exists

Sets a Boolean variable indicating whether a specified folder exists.

Determine the Size of a File

Obtains the size of a file and assigns it to a variable

Enumerate the Drives on a Computer

Enumerates the drives on a computer.

Find Amount of Disk Space Available

Obtains the amount of disk space available.

Get Information About a File

Obtains an object containing information about a file.

Move Files

Moves a file to a new directory.

Read a Delimited Text File

Returns the values in each column and row from a text file with comma-delimited data. Other delimiters may be used.

Read a Binary File

Reads data from a binary file.

Read a file in the My Documents folder

Reads the contents of a text file in the My Documents folder into a single string.

Read Text from a File

Reads the contents of a text file into a string.

Rename a Directory

Renames a directory.

Rename a File

Renames a file.

Retrieve the Drives on the Local Computer

Retrieves the drive names on the local computer.

Search a Directory for Files Recursively

Searches a directory for files recursively.

Search Files for an Expression

Searches files in a directory for an expression.

Write Text to a File

Writes a line of text to a text file, replacing any text if the file exists.

Write to a Binary File

Writes bytes to a binary file.

Math

Calculate a Monthly Payment on a Loan

Calculates the monthly payment on a loan.

Calculate the Cosine of a specified Angle

Converts an angle from degrees to radians and then calculates cosine of the angle

Calculate the Sum-of-Years Depreciation

Returns a Double specifying the sum-of-years digits depreciation of an asset for a specified period.

Calculate the Sine of a specified Angle

Converts an angle from degrees to radians and then calculates sine of the angle

Calculate the Tangent of a specified Angle

Converts an angle from degrees to radians and then calculates the tangent of the angle

Get a Random Number using the Random class

Generates a random integer between an upper bound and a lower bound.

WindowsForms

Clipboard

Copy a Class Instance to the Clipboard

Copies an instance of a serializable class to the Clipboard.

Copy an Image to the Clipboard

Copies an Image to the Clipboard.

Copy a String to the Clipboard

Copies a String to the Clipboard.

Get an Image from the Clipboard

Gets an Image from the Clipboard and stores it in an Image object.

Get a String from the Clipboard

Gets a String from the Clipboard and stores it in a String object

Controls

Add a ToolTip to a Windows Forms Control

Adds a ToolTip to a Windows Forms Control.

Button

Resize a Button Dynamically by Measuring its Text

Resizes a button by measuring its text and then resetting its Width.

Resize a Button Dynamically by using AutoSize

Uses AutoSize to dynamically resize a button to the length of its text.

Calendar

Select a Range of Dates in a Windows Forms MonthCalendar

Selects a range of dates in a MonthCalendar control.

ComboBox

Populate a ComboBox from an ArrayList

Uses an ArrayList object as the data source for a ComboBox control.

Populate a ComboBox from the Column of a Database Table

Fills a ComboBox with data from a DataTable object.

Provide Automatic Text Completion for a ComboBox

Provides automatic text completion for a combobox.

DatagridView

Lock the Column Widths of a DataGridView

Locks the column widths of a DataGridView.

ListBox

Clear Items from a Bound ListBox Control

Clears items from a bound ListBox control.

Load a Column from a Database Table into a ListBox Control

Fills a ListBox with data from a DataTable object.

Locate an Item in a Windows Forms ListBox Control

Locates the first incidence of a string in a ListBox control.

Select an Item in a Windows Forms ListBox Control

Selects an item in a ListBox control, programmatically.

ListView

Determine the Selected Item in a ListView

Determines the selected item in a ListView and assigns it to a variable.

Menu

Add a Check Mark to a ToolStripMenuItem

Adds a check mark to a ToolStripMenuItem.

Add a Context Menu to a Windows Form

Adds a context menu to a windows form.

Add a Shortcut Key to a ToolStripMenuItem

Add a shortcut to a ToolStripMenuItem.

Add Menu Items to Windows Forms

Adds menu items to an existing menu

Delete a ToolStripMenuItem from a MenuStrip

Deletes a ToolStripMenuItem from an existing MenuStrip.

ProgressBar

Use a ProgressBar to Track an Iteration

Increments a ProgressBar by a fixed amount, upon each iteration.

RadioButton

Create a RadioButton Group from a String Array

Creates a Group of RadioButtons from an Array of Strings.

RichTextBox

Format Characters in Bold in a RichTextBox Control

Adds the text "This text is in bold." to an existing RichTextBox control.

Load an RTF File into a RichTextBox Control

Loads a file in RTF format into a RichTextBox control.

Position the Cursor in a RichTextBox

Positions the cursor in a RichTextBox.

Save the Contents of a RichTextBox to a RTF File

Saves the content of the RichText box to a RTF file.

Textbox

Enter Multiline String into Multiline TextBox

Enters a multiline string into a multiline textbox.

TreeView

Determine the Selected Node in a TreeView

Determines the selected node in a TreeView control and assigns it to a variable.

Drawing

Create a Bitmap at Run Time

Creates and fills a Bitmap object and displays it in an existing Windows Forms PictureBox control.

Create a Custom Brush

Creates a TextureBrush object with an image file.

Create a Pen

Creates a Pen object.

Create a Solid Brush

Creates a SolidBrush object.

Create a Triangle Shape using a GraphicsPath Object

Draws a triangle by connecting a series of points.

Display an Animated GIF

Displays an animated GIF.

Draw a Filled Ellipse on a Windows Form

Draws a filled ellipse on a form.

Draw a Filled Rectangle on a Windows Form

Draws a filled rectangle on a form.

Draw a Line on a Windows Form

Draws a line on a form.

Draw a Pie Chart

Draws a pie chart.

Draw a Rubber Band Rectangle

Draws a rubber band rectangle on the form.

Draw a Shape with Gradient Fill

Draws a shape with gradient fill.

Draw Outlined Ellipse

Draws outlined ellipses on a form.

Draw Outlined Rectangle

Draws outlined rectangle on a form.

Draw Text on a Windows Form

Draws text on a form.

Draw Vertical Text on a Windows Form

Draws text on a form in a vertical orientation.

Fonts

Create a Font

Creates a font by using three overloads of the Font constructor.

Forms

Add a Windows Forms Control at Run Time

Creates a new instance of a Windows forms TextBox control at run time.

Arrange MDI Child Forms

Arranges the child forms in a cascading layout.

Convert Mouse Coordinates to Screen Coordinates

Converts mouse coordinates from a mouse event into screen coordinates.

Create MDI Child Forms

Creates and displays a new MDI child form.

Create Transparent Windows Forms

Sets the opacity of a form to make it transparent.

Determine the Active MDI Child and Control

Retrieves the active MDI child form and the active control on the child form.

Determine Which Control on a Windows Form is Selected

Finds the selected control on a form.

Determine Which Modifier Key Was Pressed

Monitors for modifier keys such as the SHIFT, ALT, and CTRL keys.

Display a Windows Form

Displays a windows form.

Eliminate the TitleBar from a Form

Eliminates the TitleBar from a Form

Keep a Windows Form on Top

Shows how the TopMost property controls whether a form is a top-most form. A top-most form will float above other, non–top-most forms even when it is not active.

Move a Window by Dragging the Client Area of the Form

Moves a form by dragging any part of it with the mouse. This feature is particularly useful when the form has no title bar.

Play a Beep From a Windows Form

Plays a beep.

Resize Windows Forms

Resizes a form.

Restrict a Control's Acceptable Keystrokes

Overrides the default ProcessCmdKey function of a Windows Forms Control and restricts user input to numeric and navigation keys.

Retrieve Information from the Parent MDI Form of a Dialog Box

Retrieves information from the parent MDI form.

Retrieve the Result for Dialog Boxes

Determines how a dialog box was closed.

Set the Screen Location of Windows Forms

Sets the location, in pixels, of the the top-left corner of the form.

Sound

Loop a Sound Playing on a Windows Form

Plays a looping sound in the background.

Play a Sound

Plays a sound from a file.

Stop Playing Sounds in the Background

Stops a sound playing in the background.

XML

Add an Element to a XML Document

Adds a new element to an XML document instance.

Enumerate Attributes of an XML Node

Enumerates the attributes of an XmlNode.

Find a Node in XML Data Using the Element Name

Locates an element in an XML file by Element name.

Infer and create a Schema from an XML file.

Infers a Schema from an existing XML file and saves it as a seperate schema file.

Iterate named nodes in XML document

Iterates the elements in an XML document by element name.

Navigate with XPathNavigator

Iterates through the nodes of an XML document using the XPathNavigator.

Read Class Data from an XML File

Reads class data that was previously written to an XML file using the XmlSerializer class.

Read XML from a File Using the XmlTextReader

Uses the XMLTextReader class to extract the contents from an XML file.

Read XML from a String

Reads XML data from a string.

Read XML from a URL

Read XML data from a location defined as an URL.

Select Nodes with XPathNavigator

Creates an iterator to walkthrough selected nodes.

Transform XML into HTML using a XSL Stylesheet

Transforms XML into HTML using a XSL stylesheet.

Transform XML into HTML using XSLT

Transforms XML into HTML using XSLT.

Write Class Data to an XML File

Writes the data from a class to an XML file using the XmlSerializer class.