Skip to content

Assignment 1 Planning Document Visual Basic

1-introduction.htm; updated July 6, 2011

Introduction to Visual Basic

Coverage:

This chapter covers object-oriented terminology and concepts, the basic files comprising a VB project, elements of the Visual Studio integrated development environment, VB Help, and the first hands-on project introducing VB objects, properties, and methods.

Outline:

Introduction

Objective

Commercial GUI Design/Development Approach

Microsoft Visual Studio and Visual Basic (.NET Version)

Programming Languages

Visual Studio Components

Object-Oriented Programming Terminology

Getting Started with Visual Studio

Before Using Visual Basic

Launching Visual Basic

The Integrated Development Environment

The Toolbox

Set Up Your Work Environment

Resetting the Default IDE Layout

Building the Ch01VBUniversity Application

Plan the Project

Setup the Project and Form

Naming Rules and Conventions

Build a Form Like This One

Saving and Running a Project

Name and Text Properties

Locking Controls

Program Coding

Accessing an Event Procedure

The Remark Statement

Switching Between the View Designer and View Code Windows

Accessing Intellisense

The Assignment Statement

The Clear Method

The Close Method

Printing a Form

Finish Coding the Application

Managing Projects

Copying Your Project to a Flash Drive

Opening an Existing Project

Program Errors

A Clean Compile

Design Time, Run Time, Break Time

VB Help

MSDN

Solution to In-Class Exercise

INTRODUCTION

Objective

Course objective – learn to design and develop Windows-based business applications using Visual Basic.NET programs that meet commercial programming standards.

·        Program design and coding is satisfactory.

·        Work is equivalent to that expected from someone already working in the information technology field as a professional programmer.

·        Grade you according to commercial standards.

VB supports programming projects that run in both:

·        Microsoft Windows and,

·        Web (Internet) environments.

This course focuses on the Windows operating system(s).

Commercial GUI Design/Development Approach

Modern programs run in a graphical user interface (GUI) environment.You can open up any desktop program or web browser and examine the GUI.This interface includes:

·        Buttons (some with Icons and Graphical Images) and Menus on which you point and click.

·        TextBox controls in which you type information.

·        Graphical images to guide a system user in using the program.

·        Other components.

·        A GUI for a version of Microsoft Word is shown in this figure.

Microsoft Visual Studio and Visual Basic (.NET Version)

Programming Languages

Microsoft's Visual Studio (also called Visual Studio.NET) includes several different programming languages:

·        Visual Basic,

·        Visual C# (C sharp),

·        Visual C++ (cee-plus-plus),

·        Visual F# (F sharp),

·        JScript and

·        Web Development (called ASP.NET).

·        It also includes the .NET 4 Framework upon which these languages operate.

All of these languages compile.

·        This means they are translated from human readable-form to machine readable-form to the same Microsoft Intermediate Language (MSIL).

·        MSIL run within the Common Language Runtime (CLR) – a component of the .NET Framework.

Visual Basic (also termed Visual Basic.NET or VB) is a major revision of earlier Microsoft VB products.

·        This latest version is Version 10 of VB.

·        This is an upgrade of earlier.NET versions.

·        The current and earlier versions are not completely compatible—a program coded with an earlier version that is upgraded to the current version cannot be opened again with the earlier version software.

·        Version 6 and earlier are not .NET-compatible – programs created with these versions are completely incompatible with .NET applications.

VB is available in several editions including the free Express Edition that you can download from Microsoft.Other editions (Professional, Premium, and Ultimate) are used within industry.

·        Our classroom has the Visual Studio 2010 Ultimate Edition installed.

·        You can also use the Express Edition (2010) (free download) or,

·        The Professional Edition (2010) (free download for students).

·        You must use one of these 2010 editions (also called Version 10) for this class.

Visual Studio Components

When Visual Studio is installed on a computer, there are two mandatory components to the installation and an optional third component.

·        .NET Framework Class Library.This is a library of predefined class objects.It enables you to quickly build a computer application through the use of predefined objects such as forms, text boxes, labels, buttons, drop-down list controls, and others (mandatory).

·        Common Language Runtime (CLR).This component manages the execution of a programming project written in any of the languages that are included within Visual Studio including Visual Basic as a language (mandatory).This component is installed as part of the .NET Framework.

·        MSDN (Help).This is the help component and provides access to a help reference library.This is covered in detail at the end of this set of notes.It is an optional, but highly recommended component.

Object-Oriented Programming Terminology

VB is an object-oriented programming language.

·        Means you work with objects in building an application.

·        Examples:Form objects, Button objects, TextBox objects, Label objects, ListBox objects, PictureBox objects, and more.

VB is also termed an event-driven programming language because you will write program code that responds to events that are controlled by the system user.Example events include:

·        Clicking a button or menu.

·        Opening or Closing a form.

·        Moving the mouse over the top of an object such as a text box.

·        Moving from one text box to another.

In order to work with VB, you need to understand "object" terminology as defined in Table 1.

Table 1

Terminology

Definition

Object

A thing – like a noun in English.Examples include forms and controls you place on forms such as buttons, text boxes, and icons.

Property

Objects have properties – like adjectives in English.Properties describe object behaviors.Examples of properties include Text, Name, BackColor, Font, and Size.

Refer to a property by the notation ObjectName.PropertyName (use the .dot notation) – example: TotalDueTextBox.Text or AccountLabel.ForeColor.

Method

Like a verb in English – these are the actions that objects exhibit.Examples include methods to Show and Hide forms and methods to Print and Close forms.

Refer to a method with the notation ObjectName.MethodName – example Me.Close will close the current form.

Event

Events are actions usually triggered by the system user such as clicking a button; however, events can also be triggered by the actions of objects.For example, closing a form can trigger an event.

Class

This is a really abstract term – it is a sort of template for an object.For example, all forms belong to the Form class of object.All buttons belong to the Button class of object.Classes include definitions for object properties, methods, and associated events.Each class is assigned an identifying namespace within the .NET Framework Class Library.

Each new object you create is defined based on its class – the new object is called a class instance.

Getting Started with Visual Studio

You will use the VB component of Visual Studio to create and test projects.

·        The programming applications you will design and develop are called solutions in VB.

·        A solution can actually contain more than one project, but in this course we will focus on just creating a single project in a solution.

·        Each solution is stored in a folder identified by the solution name.

·        This is covered in more detail later in this set of notes.

Before Using Visual Basic

When you first startup a computer in our classroom and computer laboratories, you may need to reset the Propertiesof MyDocuments.

·        Required because the operating system setup on these classroom/lab computers is produced from a “ghost image” created by the system administrator.

·        At the desktop, right-click on the MyDocuments icon.

·        Select the Properties menu option as shown in this figure.

·        Click the Restore Defaults button and then OK as shown in the below figure – this sets the ownership to you as the logged in user of the computer.

·        Do this each time you plan to use VB in the classroom or computer lab – this is NOT necessary when using VB on your home computer.

Launching Visual Basic

Start VB – Click the Windows Start button and locate Microsoft Visual Studio 2010 – launch the program by clicking.The option will look something like this.

The first screen to display may require you to choose your Default Environment Settings.

·        If this screen displays, click the Visual Basic Development Settings option in the list box and then click the Start Visual Studio button

The Visual Studio Start Page is shown in the figure below.The start page is slightly different for Visual Studio 2010 (Professional or Ultimate Edition) and Visual Basic 2010 Express Edition.

·        This is the Start Page for Visual Basic 2010 Express Edition.

·        This is the Start Page for Visual Studio 2010 (Ultimate Edition).

Click the New Project link shown in the figure above to create a new project.This opens the New Project dialog box shown below.

·        Your first project will be a Visual Basic Project using a Windows Forms Application template as shown in the figures above.

·        The default name is WindowsApplication1 -- not a very useful name.Change the project name to:Ch01VBUniversity.

·        Click the OK button – it takes several seconds to create the project files from the template.

The Integrated Development Environment

Familiarize yourself with the Integrated Development Environment (IDE).

·        Across the top are menus with different options used in the designing of an application.

·        Toolbars with shortcut icons are shown below the menus.

·        Form Designer (also termed the Document Window).

o   Displays open documents such as the Form1 shown in the figure below.

o   Tabs along the top are used to allow you to switch rapidly between open documents.

o   Every project starts with a default form named Form1 – the form you modify to build your business application.

o   The form can be resized by using the sizing handles.

o   The form can be renamed (you’ll do this later in an exercise).

·        Solution Explorer Window – displays filenames for files that comprise a project.The solution name is also shown here (Ch01VBUniversity).

·        Properties Window – displays properties of the currently selected object – in the figure the properties displayed are those of the Form object.

·        ToolBox Window – this is shown along the left edge of the figure in collapsed display.

The Toolbox

The Toolbox:

·        Contains controls that are used to build forms.

·        Can be expanded or collapsed with the Pin/Unpin icon.

·        Parts of the Toolbox can be expanded/collapsed with the white and black pointer icons to the left of the groupings.

·        Used to add controls (tools) to a form by either double-clicking or dragging/dropping (your option on which to use).

Set Up Your Work Environment

The IDE shows the default work environment in terms of the windows that are displayed.Experiment with pinning and unpinning these windows by using the AutoHide pushpin icon for each window.

·        Toolbox

·        Solution Explorer

·        Properties

You can also close/open these windows with the View menu.

Resetting the Default IDE Layout

Sometimes you startup VB and the IDE layout is not what you expect.

·        Windows you want such as Solution Explorer, Toolbox, or Properties may be closed.

·        The quick way to reset the layout is through the Window menu, Reset Window Layout submenu option as shown in this figure.

Building the Ch01VBUniversity Application -- Project Specifications

Plan the Project

Your textbook teaches you to plan the design of the user interface by sketching (pencil & paper) a layout for the Form that represents the business application – the Department of Computer Management and Information Systems does not teach this approach in CMIS 142 because no one in a commercial programming setting uses an approach like this.

Instead, we teach project planning in CMIS 270 – you will learn about project analysis and design including how to write specifications for building forms-based business applications.In CMIS 142 you are given project specifications to guide you in building assigned project applications.

Setup the Project and Form

There are several actions you need to take for every project.

·        Change the form's FileName property.

o   Click the FileName in the SolutionExplorer window – change the FileName property in the Properties window.

o   A FileName should always end in the .vb file name extension.

·        Changing the form's FileName also changes the Name property of the form – select the Form and examine the Name property (the easiest way to select the form is to single-click the title bar).

·        Change the Title Bar value of a form by typing a new value into the Text property for the form.

o   Select the Form.

o   Click the Alphabetic icon shown in the figure below to list the properties alphabetically.

o   Type the new value VB University – Student Information in the Text property of the Properties window.

·        Size the form as needed by clicking the white squares around the form and dragging/dropping.

·        Set the form's StartPosition property to CenterScreen.This will cause the project when it runs to display in the center of the computer monitor screen.

·        Set the form's Font property – usually you'll leave this at about an 8.25 point font, but in class I use a 10 point bold font so everyone in the back of the room can see the overhead display.

Naming Rules and Conventions

Now you are ready to build a form – you will be placing controls on a form and you need to know the naming rules and conventions that you will follow this term in naming controls.

Visual Basic automatically assigns a value to the Name property of each control, for example, Label1, Label2, Label3, or TextBox1, TextBox2, TextBox3, or Button1, Button2, Button3.However, it is difficult to remember the difference between Label1 and Label2 so:

·        if you are going to later refer to the controls, it is best to rename them to a more meaningful name,

·        if you are not going to refer to the controls later, then just use the assigned default name such as Label1.

When you name an object such as a Label or TextBox or Button, you must follow these rules:

·        An object name can begin with an alphabetic letter or the special “underscore” character.

·        An object name can include letters, digits, and underscores.

·        An object name CANNOT include a space or a punctuation mark.

·        An object name CANNOT be a VB reserved word such as Button, Close, or TextBox.

·        An object name can contain a VB reserved word – object names such as PrintButton, CloseButton, NameTextBox, and MajorTextBox are legal names.

Several naming conventions exist within industry – the common ones are the Hungarian naming convention and the Pascal naming Convention.

Naming conventions are simply guidelines to help other programmers read your code more easily.We will use the Pascal naming convention.The rules are:

·        Begin an object name with an uppercase alphabetic character.

·        Capitalize each word that is part of an object name.

·        Select object names that are meaningful.

·        Append the full name of the control class to the end of the name.

·        Avoid abbreviations unless they are standard abbreviations such as SSN (social security number).

·        Examples of valid names:MajorTextBox, ResetButton, MessageLabel, TotalDueTextBox, and CloseButton.

This table gives examples of both the Camel Casing and Hungarian naming conventions.

Camel Casing and Hungarian Naming Conventions

Control Type and Camel Casing Naming Suffix

Example Camel Casing

Control Names

Hungarian

Naming

Prefix

Example Hungarian

Control Names

TextBox

NameTextBox, MajorTextBox

txt

txtName, txtMajor

Button

ShippingButton, ExitButton, ResetButton

btn

btnShipping, btnExit, btnReset

Label

NameLabel, OutputLabel

lbl

lblName, lblOutput

Note:Label controls are often not renamed – they are not referred to later in writing computer code so the default assigned name is unchanged.

Build a Form Like This One

1.   Open the Toolbox – select the CommonControls node.

2.   Place a Label control on the form by either double-clicking the Label tool or by drag/dropping a label to the form.

o   Notice that when you select the Toolbox's label control, the mouse pointer on the form becomes a crosshair showing you where the upper left corner of the label will be displayed.

o   Drag the new label to where you want it in the upper left corner of the form.

o   Change the label's Text property to Student Name:

o   The label also has a Name property – the first label is named Label1.This is a satisfactory name and you will not refer to the label when you later write programming code so leave it named Label1.

3.   Add a second label control on the form.Set the Text property to Academic Major: – this label is named Label2.

4.   Add two text box controls as shown.

o   Name the first text box control NameTextBox.

o   Name the second text box control MajorTextBox.

o   These TextBox controls will only display output so set the properties ReadOnly = True and TabStop = False.

5.   Add six button controls as shown.

o   Name the button controls Display1Button, Display2Button, Display3Button, ResetButton, PrintButton, and ExitButton.

o  

Statements in Visual Basic

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.

This topic describes each category. Also, this topic describes how to combine multiple statements on a single line and how to continue a statement over multiple lines.

Declaration Statements

You use declaration statements to name and define procedures, variables, properties, arrays, and constants. When you declare a programming element, you can also define its data type, access level, and scope. For more information, see Declared Element Characteristics.

The following example contains three declarations.

The first declaration is the statement. Together with its matching statement, it declares a procedure named . It also specifies that is , which means that any code that can refer to it can call it.

The second declaration is the statement, which declares the constant , specifying the data type and a value of 33.

The third declaration is the statement, which declares the variable . The data type is a specific object, namely an object created from the 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.

You can assign an initial value to a variable as part of its declaration, as the following example illustrates.

If a variable is an object variable, you can explicitly create an instance of its class when you declare it by using the New Operator keyword, as the following example illustrates.

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.

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 control structure to run different blocks of code based on the value of a variable. Within each block of code, a loop runs a specified number of times.

The statement in the preceding example checks the value of the parameter . If the value is , it calls the method of . If the value is , it calls the method of . The control structure ends with .

The loop within each block calls the appropriate method a number of times equal to the value of the parameter.

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.

In the preceding example, the assignment statement stores the literal value 42 in the variable .

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

The preceding example adds the value held in variable to the value held in variable , and then adds the value returned by the call to function . The total value of this expression is then stored in variable .

Data Types in Assignment Statements

In addition to numeric values, the assignment operator can also assign values, as the following example illustrates.

You can also assign values, using either a literal or a expression, as the following example illustrates.

Similarly, you can assign appropriate values to programming elements of the , , or 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.

The preceding example adds 1 to the value of , and then stores that new value in . It is a shorthand equivalent of the following statement:

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.

Type Conversions in Assignment Statements

The value you assign to a variable, property, or array element must be of a data type appropriate to that destination element. In general, you should try to generate a value of the same data type as that of the destination element. However, some types can be converted to other types during assignment.

For information on converting between data types, see Type Conversions in Visual Basic. In brief, Visual Basic automatically converts a value of a given type to any other type to which it widens. A widening conversion is one in that always succeeds at run time and does not lose any data. For example, Visual Basic converts an value to when appropriate, because widens to . For more information, see Widening and Narrowing Conversions.

Narrowing conversions (those that are not widening) carry a risk of failure at run time, or of data loss. You can perform a narrowing conversion explicitly by using a type conversion function, or you can direct the compiler to perform all conversions implicitly by setting . For more information, see Implicit and Explicit Conversions.

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.

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 executable statement is continued over two lines.

Implicit Line Continuation

In many cases, you can continue a statement on the next consecutive line without using the underscore character (_). The following table lists the syntax elements that implicitly continue the statement on the next line of code.

Syntax elementExample
After a comma ().
After an open parenthesis () or before a closing parenthesis ().
After an open curly brace () or before a closing curly brace ().

For more information, see Object Initializers: Named and Anonymous Types or Collection Initializers.
After an open embedded expression () or before the close of an embedded expression () within an XML literal.

For more information, see Embedded Expressions in XML.
After the concatenation operator ().

For more information, see Operators Listed by Functionality.
After assignment operators (, , , , , , , , , , ).

For more information, see Operators Listed by Functionality.
After binary operators (, , , , , , , , , , , , , , , , , , ) within an expression.

For more information, see Operators Listed by Functionality.
After the and operators.

For more information, see Operators Listed by Functionality.
After a member qualifier character () and before the member name. However, you must include a line-continuation character (_) following a member qualifier character when you are using the statement or supplying values in the initialization list for a type. Consider breaking the line after the assignment operator (for example, ) when you are using statements or object initialization lists.


For more information, see With...End With Statement or Object Initializers: Named and Anonymous Types.
After an XML axis property qualifier ( or or ). However, you must include a line-continuation character (_) when you specify a member qualifier when you are using the keyword.

For more information, see XML Axis Properties.
After a less-than sign (<) or before a greater-than sign () when you specify an attribute. Also after a greater-than sign () when you specify an attribute. However, you must include a line-continuation character (_) when you specify assembly-level or module-level attributes.

For more information, see Attributes overview.
Before and after query operators (, , , , , , , , , , , , , , , , , , and ). You cannot break a line between the keywords of query operators that are made up of multiple keywords (, , , and ).

For more information, see Queries.
After the keyword in a statement.

For more information, see For Each...Next Statement.
After the keyword in a collection initializer.

For more information, see Collection Initializers.

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 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 after the statement, followed by the comment. Comments can also go on their own separate line. The following example demonstrates these possibilities.

Checking Compilation Errors

If, after you type a line of code, the line is displayed with a wavy blue underline (an error message may appear as well), there is a syntax error in the statement. You must find out what is wrong with the statement (by looking in the task list, or hovering over the error with the mouse pointer and reading the error message) and correct it. Until you have fixed all syntax errors in your code, your program will fail to compile correctly.

Related Sections