Free Essay

Visual Basic Preview

In:

Submitted By coolkatare
Words 5044
Pages 21
Visual Basic 2010 Essentials

Visual Basic 2010 Essentials Visual Basic 2010 Essentials – First Edition © 2010 Payload Media. This eBook is provided for personal use only. Unauthorized use, reproduction and/or distribution strictly prohibited. All rights reserved. The content of this book is provided for informational purposes only. Neither the publisher nor the author offers any warranties or representation, express or implied, with regard to the accuracy of information contained in this book, nor do they accept any liability for any loss or damage arising from any errors or omissions.

2

Visual Basic 2010 Essentials

Table of Contents
Chapter 1. Chapter 2. 2.1 2.2 2.3 2.4 About Visual Basic Essentials .................................................................................. 11 Downloading and Installing Visual Studio............................................................... 12

Getting Visual Studio ...................................................................................................... 12 Downloading a Visual Studio Trial .................................................................................. 12 Installing Visual Studio ................................................................................................... 13 Starting Visual Studio for the First Time ........................................................................ 14 Creating a New Visual Basic Project ....................................................................... 16

Chapter 3. 3.1

Creating a Project in Visual Studio ................................................................................. 16 A Simple Visual Basic Example ................................................................................ 18

Chapter 4. 4.1 4.2 4.3 4.4 4.5

Creating a New Project................................................................................................... 18 Adding Controls to the Form .......................................................................................... 18 Setting Control Properties .............................................................................................. 20 Creating an Event Handler ............................................................................................. 22 Building and Running a Visual Basic Application ........................................................... 23 Visual Basic and Forms ............................................................................................ 25

Chapter 5. 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9

Creating a New Form...................................................................................................... 25 Changing the Form Name .............................................................................................. 25 Changing the Form Title ................................................................................................. 25 Changing the Form Background Color ........................................................................... 26 Changing the Form Background Image .......................................................................... 27 Configuring the Minimize, Maximize and Close Buttons ............................................... 28 Setting Minimum and Maximum Form Sizes ................................................................. 29 Specifying the Position of a Form on the Display .......................................................... 29 Changing the Form Border ............................................................................................. 29

5.10 Stopping a Form from Appearing the Windows Taskbar ............................................... 30 5.11 Creating a Transparent Form ......................................................................................... 30 Chapter 6. Designing Forms in Visual Studio ............................................................................ 31 3

Visual Basic 2010 Essentials 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 Visual Basic Forms and Controls .................................................................................... 31 Double Clicking the Control in the Toolbox ................................................................... 32 Dragging a Dropping Controls onto the Form ................................................................ 33 Drawing a Control on the Form...................................................................................... 33 Positioning and Sizing Controls Using the Grid .............................................................. 33 Positioning Controls Using Snap Lines ........................................................................... 34 Selecting Multiple Controls ............................................................................................ 35 Aligning and Sizing Groups of Controls .......................................................................... 36 Setting Properties on a Group of Controls ..................................................................... 36

6.10 Anchoring and Autosizing Form Controls ...................................................................... 37 6.11 Setting Tab Order in a Form ........................................................................................... 37 Chapter 7. 7.1 7.2 7.3 Understanding Visual Basic Events ......................................................................... 39

Event Triggers ................................................................................................................. 39 Wiring Up Events in Visual Studio .................................................................................. 40 Setting Up a Visual Basic Timer Event ............................................................................ 43 Hiding and Showing Forms in Visual Basic .............................................................. 46

Chapter 8. 8.1 8.2 8.3 8.4 8.5 8.6

Creating a Visual Basic Application Containing Multiple Forms .................................... 46 Understanding Modal and Non-modal Forms ............................................................... 48 Writing Visual Basic Code to Display a Non-Modal Form .............................................. 49 Writing Visual Basic Code to Display a Modal Form ...................................................... 49 Hiding Forms in Visual Basic ........................................................................................... 50 Closing Forms in Visual Basic.......................................................................................... 50 Creating a Visual Basic MDI Form ........................................................................... 52

Chapter 9. 9.1 9.2 9.3

What is an MDI? ............................................................................................................. 52 Creating an MDI Parent and Child Forms in Visual Studio ............................................. 53 Writing the Visual Basic Code to Add the Children to the MDI Parent.......................... 54

Chapter 10. Creating Top-Level Menus in Visual Basic .............................................................. 56 10.1 Creating a Top-Level Menu ............................................................................................ 56 4

Visual Basic 2010 Essentials 10.2 Adding Standard Menu Items ........................................................................................ 57 10.3 Manually Adding Menu Items using the Form Builder .................................................. 58 10.4 Editing, Deleting and Moving Menu Items .................................................................... 61 10.5 Assigning Keyboard Shortcuts to Menu Items ............................................................... 61 10.6 Programming Menu Items in Visual Basic...................................................................... 62 Chapter 11. Creating Context Menus in Visual Basic ................................................................. 64 11.1 Adding Context Menus to a Visual Basic Form .............................................................. 64 11.2 Associating a Component with a Context Menu............................................................ 65 11.3 Programming Visual Basic Context Menu Options ........................................................ 66 11.4 Compiling and Running the Application......................................................................... 66 Chapter 12. Building a Visual Basic Toolbar ............................................................................... 68 12.1 Creating a Toolbar .......................................................................................................... 68 12.2 Adding Tooltip Text to Toolbar Controls ........................................................................ 69 12.3 Programming Toolbar Controls ...................................................................................... 69 12.4 Changing the Toolbar Position ....................................................................................... 71 Chapter 13. Building a Visual Basic Status Bar ........................................................................... 72 13.1 Adding a Status Bar to a Visual Basic Application .......................................................... 72 13.2 Adding Items to a Status Bar .......................................................................................... 73 Chapter 14. Visual Basic Modules and Procedures .................................................................... 74 14.1 Visual Basic Code Modules ............................................................................................. 74 14.2 Visual Basic Code Procedures ........................................................................................ 76 14.3 Defining Visual Basic Subroutines .................................................................................. 77 14.4 Passing Parameters to Functions and Subroutines ........................................................ 78 14.5 Defining Visual Basic Functions ...................................................................................... 80 Chapter 15. Understanding Visual Basic Variable and Constant Types ..................................... 82 15.1 Boolean Variable ............................................................................................................ 82 15.2 Char Variable .................................................................................................................. 82 15.3 Byte Variable .................................................................................................................. 82 5

Visual Basic 2010 Essentials 15.4 Date Variable .................................................................................................................. 82 15.5 Decimal Variable ............................................................................................................ 83 15.6 Double Variable .............................................................................................................. 83 15.7 Integer Variable .............................................................................................................. 83 15.8 Object Variable ............................................................................................................... 83 15.9 Long Variable .................................................................................................................. 83 15.10 15.11 Short Variable ............................................................................................................. 83 String Variable ............................................................................................................ 83

Chapter 16. Declaring Visual Basic Variables and Constants ..................................................... 85 16.1 Declaring Visual Basic Variables ..................................................................................... 85 16.2 Initializing Visual Basic Variables .................................................................................... 86 16.3 Assigning New Values to Visual Basic Variables............................................................. 86 16.4 Referencing Variable Values .......................................................................................... 87 16.5 Understanding Variable and Constant Scope ................................................................ 87 16.5.1 16.5.2 16.5.3 16.5.4 Block Level Scope .................................................................................................... 87 Procedure Level Scope ............................................................................................ 87 Module Level Scope ................................................................................................ 88 Global Scope ........................................................................................................... 88

16.6 Static Variables in Visual Basic ....................................................................................... 88 16.7 Declaring and Referencing Visual Basic Constants ........................................................ 89 Chapter 17. Visual Basic Arithmetic............................................................................................ 90 17.1 Understanding Expressions ............................................................................................ 90 17.2 Visual Basic Operator Precedence ................................................................................. 91 17.3 Visual Basic Addition ...................................................................................................... 91 17.4 Visual Basic Subtraction and Negation .......................................................................... 92 17.5 Visual Basic Multiplication ............................................................................................. 92 17.6 Visual Basic Division ....................................................................................................... 92 17.7 Visual Basic Exponentiation ........................................................................................... 93 6

Visual Basic 2010 Essentials 17.8 Visual Basic Modulus Arithmetic .................................................................................... 93 Chapter 18. Visual Basic Comparison and Logic ......................................................................... 94 18.1 Visual Comparison Operators ........................................................................................ 94 18.2 Visual Basic Logical Operators........................................................................................ 94 Chapter 19. Visual Basic Flow Control ........................................................................................ 97 19.1 Using If ... Then to Make Decisions ................................................................................ 97 19.2 Using If ... Then .. Else to Make Decisions ...................................................................... 97 19.3 Using If ... Then .. ElseIf to Make Decisions.................................................................... 98 19.4 Evaluating Multiple Possibilities using Select Case ........................................................ 99 19.5 Using the Visual Basic GoTo Statement ....................................................................... 101 Chapter 20. Visual Basic For Loops ........................................................................................... 102 20.1 Creating a Visual Basic For Loop................................................................................... 102 20.2 Incrementing a For Loop by a Value Greater Than 1 ................................................... 103 20.3 Early Exit of a For Loop ................................................................................................. 103 20.4 Continuing a For Loop .................................................................................................. 103 Chapter 21. Visual Basic Do ... Loops ........................................................................................ 105 21.1 Creating a Visual Basic Do ... Loop ............................................................................... 105 21.2 Visual Basic Do While Loops ......................................................................................... 105 21.3 Visual Basic Do Until Loops .......................................................................................... 106 21.4 Summary ...................................................................................................................... 107 Chapter 22. Visual Basic Arrays ................................................................................................ 108 22.1 What is a Visual Basic Array ......................................................................................... 108 22.2 How to Declare a Visual Basic Array ............................................................................ 108 22.3 Initializing a Visual Basic Array ..................................................................................... 109 22.4 Assigning Values to Individual Array Elements ............................................................ 109 22.5 Accessing Array Element Values .................................................................................. 110 22.6 Finding the Size of an Array.......................................................................................... 110 22.7 Changing the Size of a Visual Basic Array ..................................................................... 111 7

Visual Basic 2010 Essentials 22.8 Clearing a Element Ranges from a Visual Basic Array .................................................. 112 22.9 Sorting a Visual Basic Array .......................................................................................... 112 22.10 Searching for Array Elements ................................................................................... 112

Chapter 23. Visual Basic Multidimensional Arrays ................................................................... 114 23.1 Creating a Visual Basic Multidimensional Array .......................................................... 114 23.2 Assigning Values to Multidimensional Array Elements ............................................... 114 23.3 Accessing Elements of a Multidimensional Array ........................................................ 115 23.4 Summary ...................................................................................................................... 115 Chapter 24. Working with Dates and Times in Visual Basic ..................................................... 116 24.1 Creating and Initializing a Visual Basic Date................................................................. 116 24.2 Accessing the Date and Time in a Date Variable ......................................................... 116 24.3 Formatting Dates and Times ........................................................................................ 117 24.4 Adjusting a Date or Time .............................................................................................. 118 24.5 Retrieving Parts of a Date or Time ............................................................................... 119 24.6 Finding the Interval Between Two Dates or Times ...................................................... 119 24.7 Accessing the System Date and Time from Visual Basic .............................................. 120 24.8 Checking if a Value is a Valid Date ............................................................................... 120 Chapter 25. Working with Strings in Visual Basic ..................................................................... 121 25.1 Joining Strings in Visual Basic ....................................................................................... 121 25.2 Finding the Length of a String ...................................................................................... 122 25.3 Extracting Text from the Beginning of String ............................................................... 122 25.4 Extracting Text from the End of a String ...................................................................... 123 25.5 Extracting Text from Anywhere in a String .................................................................. 123 25.6 Searching for a Substring ............................................................................................. 123 25.7 Trimming Leading and Trailing Spaces from a String ................................................... 124 25.8 Replacing Text in String ................................................................................................ 125 Chapter 26. Object Oriented Programming with Visual Basic.................................................. 126 26.1 What is an Object? ....................................................................................................... 126 8

Visual Basic 2010 Essentials 26.2 What is a Class? ............................................................................................................ 126 26.3 Defining a Visual Basic Class ......................................................................................... 126 26.4 Creating Visual Basic Class Properties .......................................................................... 127 26.5 Defining Class Methods ................................................................................................ 127 26.6 Instantiating an Object from a Visual Basic Class ........................................................ 129 26.7 Accessing Object Properties and Methods .................................................................. 130 Chapter 27. Accessing Databases Using Visual Basic ............................................................... 131 27.1 Installing the NorthWind Sample ................................................................................. 131 27.2 Connected to a Database ............................................................................................. 132 27.3 Selecting the Data Source ............................................................................................ 133 27.4 Linking Data Sources to an Application ........................................................................ 134 27.5 Adding SQL Statements to a Visual Basic Application.................................................. 137 Chapter 28. Visual Basic and the DataGridView Control .......................................................... 139 28.1 Selecting the Data Source ............................................................................................ 140 28.2 Adding a DataGridView Control ................................................................................... 141 28.3 Customizing the DataGridView Control ....................................................................... 142 Chapter 29. Working with Files in Visual Basic ......................................................................... 144 29.1 Opening a Text File in Visual Basic ............................................................................... 144 29.1.1 29.1.2 29.1.3 FileMode Options.................................................................................................. 144 FileAccess Options ................................................................................................ 144 FileShare Options .................................................................................................. 144

29.2 Writing to a File with Visual Basic ................................................................................ 145 29.3 Reading From a File in Visual Basic .............................................................................. 146 29.4 Detecting a Change to a File......................................................................................... 147 Chapter 30. Working with Directories in Visual Basic .............................................................. 148 30.1 Creating and Removing a Directory In Visual Basic ..................................................... 148 30.2 Obtaining a Directory Information and Contents Listings in Visual Basic .................... 149 30.3 Extracting Parts of a Path Name in Visual Basic ........................................................... 149 9

Visual Basic 2010 Essentials 30.4 Copying Directories in Visual Basic .............................................................................. 150 30.5 Renaming a Directory in Visual Basic ........................................................................... 150 Chapter 31. Drawing Graphics in Visual Basic .......................................................................... 151 31.1 Drawing Filled Shapes in Visual Basic ........................................................................... 151 31.2 Drawing in Visual Basic Using a Pen ............................................................................. 153 31.3 Drawing Shapes in Visual Basic .................................................................................... 154 31.3.1 31.3.2 Drawing a Ellipse ................................................................................................... 154 Drawing a Rectangle ............................................................................................. 154

31.4 Drawing Text in Visual Basic ......................................................................................... 155 31.5 Clearing a Drawing Area ............................................................................................... 155 31.6 Summary ...................................................................................................................... 156

10

Visual Basic 2010 Essentials

Chapter 1.

About Visual Basic Essentials

Visual Basic Essentials is intended to be of use to both novices looking to learn Visual Basic, and to those proficient in other languages that plan to cross-train. The Visual Basic language, combined with the Visual Studio, provides a uniquely powerful, yet easy to learn development environment allowing even the absolute beginner to rapidly create and deploy Windows applications. Visual Basic Essentials begins with instruction on designing Windows forms in Visual Studio including tasks such as designing menu systems and toolbars and wiring up event procedures. The book then introduces the basic concepts of the Visual Basic language covering concepts such as Visual Basic variable types, looping, flow control, functions and subroutines. Once the basics are covered, topics such as single and mutli-dimensional arrays, string handling, file I/O and date and time manipulation are explained. Finally, more advanced topics such as Visual Basic object oriented programming, database access and graphics drawing are detailed. Throughout the book, liberal use is made of code excerpts providing practical examples of theory in action. It is intended that having read this online book, the programmer will be confidently developing Windows applications using Visual Basic and Visual Studio.

11

Visual Basic 2010 Essentials

Chapter 2.

Downloading and Installing Visual Studio

Everything you need to build Visual Basic applications is included with Microsoft Visual Studio. At the time of publication of this book the latest release of Visual Studio is Visual Studio 2010. The first step in learning Visual Basic is, therefore, to obtain a copy of Visual Studio. 2.1

Getting Visual Studio

There are a number of options in terms of getting a copy of Visual Studio. If you work for a company which has Visual Studio licenses available then the first step is to talk to your IT department to see if they can provide you with a license, or purchase one for you. If you do not have access to a purchased Visual Studio license, or lack the funds to buy a copy, the best option, and actually the ideal option for those learning Visual Basic, is to download a trial version from Microsoft's web site. This will give you a 30 day trial period to use all the features of Visual Studio with the option to extend the trial to 90 days. Given that this book will teach you everything you need to know to program in Visual Basic the 90 day trial period will give you plenty of time to learn Visual Basic with time to spare to decide if you want purchase a fully licensed copy of Visual Studio. In this chapter of Visual Basic Essentials we will assume that you are downloading and installing the trial version of Visual Studio 2010. 2.2

Downloading a Visual Studio Trial

To work through the examples in this book, Visual Studio 2010 Professional Edition is recommended. Trial copies of Microsoft Visual Studio Professional Edition are available from the Visual Studio page of the Microsoft web site. From this page, you can choose to download a trial copy of Visual Studio 2010 using the web installer or as an ISO image. The ISO image is approximately 2.5GB in size. Whilst the web installer itself will download relatively quickly, the installer will subsequently download the remainder of the Visual Studio files and packages so a high speed internet connection is highly recommended regardless of the installation method chosen. That said, the web installer provides the ability to download only the features needed to develop Visual Basic applications, so will download and install faster than the ISO image. The ISO image will either need to be burned to a DVD after it has downloaded, or be mounted as a virtual CD using a tool such as Virtual Clone Drive, or the ISO image may be unpacked using WinZip. 12

Visual Basic 2010 Essentials In the remainder of this chapter it will be assumed that the installation is being performed using the web installer. 2.3

Installing Visual Studio

Once the web installer has downloaded, navigate to the location it has been saved to and double click on the executable to launch it. Once a number of files have been installed and the license terms accepted, a screen will appear providing the option to select the features to be installed:

Visual Studio supports a number of different programming languages in addition to Visual Basic (such as C#, F# and C++). If you only plan to use Visual Basic then choose the custom installation option and uncheck the boxes for the other languages. This will both speed up the installation process and reduce the amount of space required to install Visual Studio. If you need to work with the other supported programming languages at a later date you can install additional language support. Once the desired features have been selected, the installer will download and install the corresponding packages. The download and installation process is reported in real-time as illustrated in the following figure:

13

Visual Basic 2010 Essentials

2.4

Starting Visual Studio for the First Time

Once the Visual Studio installation is complete you are ready to start it up. Find Visual Studio in the Windows Start menu and select it. The first time Visual Studio is run it will ask you which programming language you would like to use as the default:

14

Visual Basic 2010 Essentials

Select Visual Basic Development Settings from the list and click on the Start Visual Studio button. After loading some user settings, the main Visual Studio 2010 window should appear and you are now ready to start learning Visual Basic.

15

Visual Basic 2010 Essentials

Chapter 3.

Creating a New Visual Basic Project

Visual Studio uses the concept of projects to contain the files and resources required to build an application using Visual Basic. Typically there will be one Visual Studio project per individual application you develop. In this chapter we will look at creating a new Visual Studio project. 3.1

Creating a Project in Visual Studio

Now that Visual Studio is installed it is time to create a new project. If it is not already running, begin by starting Visual Studio from the Windows Start menu. When the main Visual Studio Window appears click on the File menu and select the New Project option. Visual Studio will subsequently display the "New Project" dialog illustrated in the following figure:

The New Project dialog provides a number of options with regard to the type of project being created and the version of the .NET Framework to use as the foundation for that project. In this example we are going to build a Windows Application using .NET Framework 4. A Windows Application is a graphical application (in other words an application that appears in a window and contains buttons, text fields and all the other graphical items we expect to see when we run Microsoft Windows applications). Select the Windows Application icon from the New Project dialog and give your new project a name by typing it into the Name: field (for example you might want to name your project "VBexample"). Click on the OK button to create the project. Once the project is created Visual

16

Visual Basic 2010 Essentials Studio will display the new project, which at this point consists of a single form, ready for us to start adding visual components:

If the main window does not appear as illustrated above, select the Window -> Reset Window Layout menu option to reset the window to the default settings. Since it is easy to lose windows and tabs in Visual Studio during the learning phase this is a useful feature to keep in mind as you work through the remaining chapters of this book. Now that we have created a new project in Visual Studio it is time to move on to the next chapter and create a simple Visual Basic application. Before doing so, however, select the File -> Close Project menu item and click on the Discard button in the resulting dialog to remove our test project from your system.

17

Visual Basic 2010 Essentials

Chapter 4.

A Simple Visual Basic Example

It is often helpful when learning a new programming language to start out with a very simple example. In this chapter we will create a small sample Visual Basic application. The purpose of this example is to provide an early confidence boost for those completely new to Visual Basic by showing just how easy it is to create an application and verifying that the Visual Studio 2010 environment is correctly installed and configured. 4.1

Creating a New Project

The first step is to create a new project to contain our example Visual Basic Application. Start Visual Studio and select File -> New project. From the new project dialog select Windows Application and name the project myVBapp and click on Ok to create the new project. Once the new project is created, Visual Studio will display a blank form ready for us to design the user interface of the application. 4.2

Adding Controls to the Form

For the purposes of our example Visual Basic application we are going to add two controls to our form; a push button and a label. To achieve this we first need to access the Visual Studio Toolbox. Along the left hand side of the Visual Studio main window you should see a tab labeled Toolbox. Click on this tab to display the Toolbox. It should appear as follows:

18

Visual Basic 2010 Essentials

This Toolbox contains all the controls that may be used to build a Graphical User Interface for a Windows application. The toolbox will auto-hide by default, that is it will disappear when the mouse pointer is moved away from it. To make it permanently visible click on the push pin icon at the top of the toolbox window. Once it is pinned in place, it will no longer auto-hide. It is also possible to detach the toolbox so that it will float and can be positioned anywhere on the desktop. To do so, simply click on the toolbox title area and drag it to the desired screen location. To re-dock the panel to its original location, click on the small down arrow located in the title bar and select the Dock option from the resulting menu. 19

Visual Basic 2010 Essentials Controls are added to the Form by clicking on the required control in the Toolbox and dragging it to the desired location on the Form. To add a label to the form, click on the Label control in the Toolbox, drag it to the center of the Form and release the mouse button. The new label will then appear in the Form at the point you dropped it. Next we need to add a button. Grab a Button from the Toolbox and drag and drop it on the Form. Use the mouse to move the controls around the Form until you have a layout you are happy with, for example:

4.3

Setting Control Properties

Now that we have added the controls to our Form we need to change some of the characteristics of these controls. This is done by changing the Properties of the controls. Properties are a group of settings that allow the appearance and behavior of controls to be changed. For example, there is a property for changing the text displayed on a label, the color of a button, the font of the text on a button and so on. Properties of a control are changed using the Visual Studio Properties panel which is, by default, displayed in the bottom right hand corner of the main dialog:

20

Visual Basic 2010 Essentials

The property panel is context sensitive. In other words, the properties displayed at any one time are related to the currently selected control in the Form. If you click on the Label and then the Button in your Form you will see the properties panel change to reflect the current selection. To begin with, we will change the text of the Label control. Select the Label control in the form and then scroll down the list of properties until you find Text. This is the property which defines the text to be displayed on the currently selected Label control. Change this from the current value ('Label1') to read My First VB Application. Notice that as soon as you change this property the Label in the Form changes to reflect the new property setting. Select the Button control in the Form and change the Text Property for this control to read Close. Re-position the controls in the Form if necessary. You should now have a Form which looks something like the following:

21

Visual Basic 2010 Essentials

4.4

Creating an Event Handler

The next step is to make the Close button do something when it is pressed. Before we do that, however, we need to give the button a more meaningful name. Visual Studio has given the button a default name of Button1. While this is fine for a small design, it will quickly become difficult to work with such names in larger applications containing many buttons. With the Button selected in the Form, scroll up to the top of the properties list and change (Name) from Button1 to closeButton. Having changed the name we can now add an event to the button. Double click on the Button in the Form to display the event code for the closeButton control. Visual Studio will display the following code:
Private Sub closeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeButton.Click End Sub

This is a Visual Basic subroutine where code is placed to define what happens when a Click event is detected on the button (i.e. the user clicks on the button in the user interface of our application). In this example we want the application to close when the closeButton is pressed. To achieve this we add a single line of Visual Basic code to the closeButton_Click() sub-routine as follows so that the code calls the Close() method to exit the application:
Private Sub closeButton_Click(ByVal sender As System.Object, ByVal e As

22

Visual Basic 2010 Essentials

System.EventArgs) Handles closeButton.Click Close() End Sub

To return to the form design screen, simply click on the Form1.vb [Design] tab. 4.5

Building and Running a Visual Basic Application

Now that we have completed the design and implementation of a simple Visual Basic application we can compile and run it. To build the application, select Build myVBapp from the Visual Studio Build menu. Assuming there are no problems the application should compile without any errors (the message Build succeeded should appear in the status bar at the bottom of the Visual Studio screen). Once built, the application can be run by selecting Start Debugging from the Debug menu. An even quicker way of building and running the application is to simply press F5. This will compile and run the application without having to use any menu options. As you develop Visual Basic applications in Visual Studio you will find yourself using the F5 shortcut more than any other key on your keyboard. After a few seconds the application should appear just as you designed it in the Visual Studio designer:

Try out the Click event on the closeButton control by clicking on the Close button to close the application. Congratulations - you have designed, built and run your first Visual Basic application. 23

Visual Basic 2010 Essentials Before proceeding, select the File -> Close Project menu option and select Save from the resulting dialog to save your project.

24

Visual Basic 2010 Essentials

Chapter 5.

Visual Basic and Forms

The Windows Form is a vital component in the development of any Windows-based application. Forms essentially provide the windows that make up a Windows application. In fact, the terms window and form are often used interchangeably. Forms allow the Visual Basic developer to create windows and layout controls (such as buttons, labels etc) in those forms to provide the application's user interface. In the Designing Forms in Visual Basic we will look at how to layout controls inside a form. Before we reach that stage, however, there are a surprising number of ways in which the form itself can be modified and configured. We will cover these options in detail in this chapter. 5.1

Creating a New Form

Throughout this chapter we will work with a form in a new project. Begin by starting Visual Studio and creating a new Windows Application project (see Creating a New Visual Basic Project for details of how to do this) and name the new project VBforms. Once the new project is created you will see a Form in Visual Studio ready for you to begin work. 5.2

Changing the Form Name

All objects in a Visual Basic application need a name so that they can be referenced in the code. When a new object is added to an application in Visual Studio it is assigned a default name which usually consists of the object type and a number. For example the first form object in an application is named Form1, the second Form2, and so on. To change the name of a Form to something more meaningful, simply click in any area of the Form in Visual Studio and change the (Name) value in the Properties panel. 5.3

Changing the Form Title

Each form represents an application window. The text displayed in the title bar for each window should be changed to display something meaningful. This should either be the name of application, or a description of the form's function (for example Order Entry or Sales Report). The value of the text to be displayed in the window title is defined by the form's Text property. To change the title of the form, therefore, select the Text value in the Properties panel and change it to a new value (for example, 'My Form Example'):

25

Visual Basic 2010 Essentials

5.4

Changing the Form Background Color

The background of any form may be changed either by specifying a new color, or by using a background image. The background color is controlled by the BackColor property of the form. By default this property is set to Control. This specifies that the form should use a system defined default color. This color varies between different Windows versions, and changes when the user changes the overall theme of their Windows desktop environment. To change the background color, select the form in Visual Studio and locate the BackColor property in the Properties panel. There are a number of ways to specify a color.


Color by name - Simply type in a color name into the BackColor value field (for example Red, Yellow, Cyan etc). Color by RGB value - Colors may be specified by entering the hexadecimal RGB values (for example #FFFFFF for white, #000000 for black and so on). RGB values may also be specified using decimal values (for example 255,255,255 for white, 0,0,0 for black etc). 26

Similar Documents

Free Essay

Sales and Inventory System

...Rica A. Hernandez BSCS 2101 Start Microsoft Visual Basic 6.0 (VB6) The New Project dialog box will appear. If it doesn't go up to the menu bar and select File -> New Project In the New Project dialog select Standard EXE, and click the Open Button. This will bring up your new Project 1 application with Form1 visible. Already Visual Basic has done a lot for us. As you can see this tutorial isn't very long but already you have a full working application. You can see your new program in action by going up to the menu bar and selecting Run -> Start (Or simply press the F5 key). You should see the Form1 window appear: This is a fully functional application. You can move it around, minimize and maximize it, and close it down. For you to do this same thing in C++ - the original language most of Windows was written in you would have written hundreds of lines of code. You area already getting to see some of the extreme power VB gives you. Now lets continue with the tutorial.  Lets make this program say hello! On the left side of the screen you can see the toolbox (if this doesn't show up go to the top menu bar and select View -> Toolbox). In this toolbox you will see a picture of a button. Double click the button icon and it will create a Command1 CommandButton in the center of your form.    If you run the program now (Press F5) you will see your window now has a button labeled Command1 in the center of it, but if you click the button it doesn't do anything...

Words: 628 - Pages: 3

Free Essay

Management Information System

...酒店管理系统是较为典型的管理信息系统,系统的开发主要包括前端的程序开发和后台数据库的建立和维护。数据库要求具有一致性、完整性、数据安全性好的特点,而前端的程序要求功能完备,使用便捷。 本系统使用MICROSOFT公司的Visual Basic 6.0和ACCESS 2000作为程序开发工具和数据库开发工具。主要包括预订管理,接待管理,收银管理,系统管理,客房管理等功能模块。设计首先在短时间内建立起系统应用的原型, 然后对原型系统进行需求分析, 并不断修正和改进, 直到最终形成用户满意的可行性系统。系统的难点在于数据库的设计和模块之间的动态连接。因为时间和能力的原因,目前本系统的设计为单机版,在论文的第6章有关于网络版的部分构思。 关键字:管理信息系统 BASIC 6.0 ACCESS 2000 窗体 ABSTRACT The system of hotel management is a typical application of management information system(MIS),which mainly includes building up data-base of back-end and developing the application interface of front-end. The former should make the application powerful and easily used. The later required consistency and integrality and well security of data. This system uses Visual Basic 6.0 and the ACCESS 2000 presented by Microsoft Company. Including the pre-arranged management primarily, reception management, system management, guest room management etc. function mold piece. It can give you a short-cut to build up a prototype of system application. The prototype could be modified and developed till users are satisfied with it. The design of this system is a single machine version, there are a outline concerning network in the section six. Key words: Management information system(MIS) VISUAL BASIC 6.0 ACCESS 2000 FORM 目 录 前言 ...

Words: 2237 - Pages: 9

Free Essay

Chapter of My...

...computer. The program is also robust; phpMyAdmin has enough functionality that you can probably create and run a Web site without knowing any SQL. Being free and open-source never hurt anybody, either. For these reasons, most hosting sites include phpMyAdmin in their control panel as the default MySQL administration tool. phpMyAdmin has some nice extras, such as importing and exporting Excel, OpenDocument, and XML files, and a tool that generates a PDF image of your database schema. Visual Basic  According to Laud (2012) Visual Basic is a programming language and integrated development environment (IDE). It derives from the much older BASIC programming language, and so is considered a useful and relatively easy programming language for the beginner to learn. Visual Basic (VB) is now integrated into many different software applications and also web applications. Visual Basic was developed to be easy to learn, with a quick learning curve and a diverse scope of possibilities. Using the Visual Basic software, you can either hard-code or use the developer software to assist you throughout. It's also used to create ActiveX controls (for web usage and other controls), .dll file extensions or executables for standalone operation. LAN (Local Area Network) According to Rouse (2006) a local area network (LAN) is a group of computers and associated...

Words: 1499 - Pages: 6

Premium Essay

Pt1420

...Lab 4.1 – Pseudocode and Modules (“UTP Installed”) Critical ReviewA Module is a group of statements that exists within a program for the purpose of performing a specific task.Modules are commonly called procedures, subroutines, subprogram, methods, and functions.The code for a module is known as a module definition. To execute the module, you write a statement that calls it.The format for a module definition is as follows:Module name()StatementStatementEtc.End ModuleCalling a module is normally done from the Main() module such as:Call name()Generally, local variables should be used and arguments should be passed by reference when the value of the variable is changed in the module and needs to be retained. For example:Module main()Real Integer numberCall inputData(number)Call printData(number)End Module// Accepts number as a reference so that changed value// will be retainedModule inputData(Real Ref number)number = 20End Module// number does not need to be sent as reference because// number is not going to be modifiedModule printData(Real number)Display “The number is “, numberEnd Module | This lab requires you to think about the steps that take place in a program by writing pseudocode. Read the following program prior to completing the lab. Data Communications Corp wants a small program that will calculate the cost of UTP it installs for their clients. Write a program that will ask the user to input the name of the client, the number of feet of cable installed. The program...

Words: 1808 - Pages: 8

Free Essay

Vp Short Report

...‘Visual Basic’ Developer: Microsoft Appeared in: 1991; 24 years ago OS: Microsoft Windows and Ms - DOS HISTORY: Alan Cooper, the 'father' of Visual Basic, shows a drag-and-drop shell prototype called Tripod to Bill Gates. Microsoft negotiates to buy the concept, now code-named Ruby. The Tool includes a widget control box, the ability to add widgets dynamically, and a small language engine. Visual Basic is Microsoft's high-level object-oriented rapid application development environment for the Windows platform. The first versions of Visual Basic were intended to target Windows 3.0 (a version for DOS existed as well), however it was not until version 3.0 for Windows 3.1 that this programming language gained large-scale acceptance in the shareware and corporate programming community. VB 1.0 was introduced in 1991. The approach for connecting the programming language to the graphical user interface is derived from a system called Tripod (sometimes also known as Ruby), originally developed by Alan Cooper, which was further developed by Cooper and his associates under contract to Microsoft. Visual Basic is a third-generation event-driven programming language and integrated development environment (IDE) from Microsoft for its COM programming model first released in 1991. Microsoft intended Visual Basic to be relatively easy to learn and use. Visual Basic was derived from BASIC and...

Words: 1610 - Pages: 7

Premium Essay

The History of Visual Basic

...The History of Visual Basic dates back to 1991 when VB 1.0 was introduced. The core of Visual Basic was constructed on the older BASIC language, which was the prevalent programming language throughout the 1980s. It's a computer programming system established and owned by Microsoft. Visual Basic was originally produced to make it easier to write programs for the Windows computer operating system. The basis of Visual Basic is an earlier programming language called BASIC that was invented by Dartmouth College professors John Kemeny and Thomas Kurtz. Visual Basic is often denoted by using just its initials; VB. Visual Basic is easily the most extensively used computer programming system in the history of software. Microsoft Visual Basic is the most common language and development environment for developers coding to the Windows operating system platform. From modest beginnings it has grown to be part of personal computing itself, and with the latest incarnation, Visual Basic .NET in Beta it looks as if it may be in use for another decade or longer. Visual Basic 1.0 for Windows was released in May 1991 at a trade show in Atlanta, Georgia. Visual Basic 2.0 was released in November 1992. The programming environment was easier to use, and its speed was improved. Visual Basic 3.0 was released in 1993 and came in Standard and Professional versions. Visual Basic 4.0 was released in August 1995. It was the first version that could produce 32-bit as well as 16-bit Windows programs. It...

Words: 409 - Pages: 2

Free Essay

Art History

...OMIS 462 Spring 2013 Visual Basic Assignment 4 Due: April 25rd 100 points Title: University Book Store Learning Objectives After completing this project, you will be able to: 1. Create a database in VB, use the data in an application, and create queries. 2. Build an application using multiple forms, and pass data between forms. Description Build a simple University Bookstore system. This system will have a one-table Inventory database for books. For this system, each book will have only one author. Here are the main things you must do in your application: 1. Using the Golf Tutorial as a guide, create a database containing an Inventory table. The inventory table should have the following attributes: BookID, Title, Author (just last name), ISBN and edition. Enter data for at least 5 books. Include two books written by Dickens, and at least three others of your choice. 2. Create a query to allow the user to enter the author name to find all books by that author. 3. The first form should allow the user to search for the author by name (the query created above), displaying all the details except BookID. Once the user finds the desired book, the user should be able to click a button to put the selected book on a book order on a new form. Also add a Quit button. 4. On the order form, display the values shown. Have a button to Place the Order. Clicking this button should display a “Thank you for your order” message...

Words: 403 - Pages: 2

Free Essay

Vb, Net

...HND Division Head Office - IDM Nations Campus HND in Computing & Systems Development Unit 42 - Programming in .NET (June 2013) Set By : Mr. Sanaka Suranga Perera Student Name: Student Number: Edexcel Registration No: Date Released: 02/04/2013 Branch Name : Due Date: 31/05/2013 Submitted Date: Here by I confirm that this is my own work and that I have not plagiarized any part of it. I have also noted the assessment criteria of the assignment. Student Signature : Outcomes/Grade Descriptors Achieved (Please Tick) |Outcomes/ Grade |P42.1 |P42.2 |P42.3 |P42.4 | |Descriptors | | | | | | |1.1 |1.2 | |P42.1.1discuss the principles, |Include features ,principals of .NET framework(Task 1-a) | | |characteristics and features of | | | |programming using a .NET framework | | | |P42.1.2 critically compare different types|Differentiate the .NET versions (Task 1 -b) | ...

Words: 1224 - Pages: 5

Free Essay

Pt1420

...address, city, state, zip Display “Enter your telephone number” Input Telephone number Display “Enter college major” Input college major Input Information Console.Write("Enter your full name: ") name = Console.ReadLine() Console.Write("Enter your address, city, state, and zip: ") addressCityStateZip = Console.ReadLine() Console.Write("Enter your Telephone Number: ") telephoneNumber = Console.ReadLine() Console.Write("Enter your College Degree: ") collegeDegree = Console.ReadLine() Visual Basic Code: Sub Main() 'Declarations for variables Dim name As String Dim addressCityStateZip As String Dim telephoneNumber As String Dim collegeDegree As String 4) Total Purchase A customer in a store is purchasing five items. Design a program that asks for the price of each item, and then displays the subtotal of the sale, the amount of sales tax, and the total. Assume the sales tax is 6%. Visual Basic Code: Console.Title = "Total Purchase" Console.WriteLine("Input the amount of each item purchased") Console.WriteLine("Item 1") Dim Num1 As Double Num1 = Console.ReadLine() Console.WriteLine("Item 2") Dim Num2 As Double Num2 = Console.ReadLine() Console.WriteLine("Item 3") Dim Num3 As Double Num3 = Console.ReadLine() Console.WriteLine("Item 4")...

Words: 290 - Pages: 2

Free Essay

Werwqewq

...employer. Some of your colleagues would have also tried to get certified, but could not get certified. So, this achievement of yours deserves a back-patting. You always wanted to get certified, so after you receive your certification letter and other stuff, a sense of personal satisfaction, gratification, and relief is felt. Those were some of the benefits that you could receive after getting CCNA certified. Top 10 best free web design software 1. Coffeecup html editor 2. Notepad++ 3. Pagebreeze 4. Firebug 5. Bluefish editor 6. Brackets 7. kompoZer 8. openBexi 9. GIMP 10. Bluegriffon The CoffeeCup Free HTML Editor is a full-featured web design system. With built-in S-Drive sync and real-time preview that updates HTML5 and CSS3 as you code, your site will be ready for the web before you know it. Plus, its wizards for tables, frames, fonts, and more prove that it's a great tool for anyone who wants to design their own website. The Free HTML Editor is a trimmed-down version of the...

Words: 541 - Pages: 3

Free Essay

Asp.Net Application for Book Doisplay

...value; } } public Book1(string p1,string p2,string p3,double p4) { // TODO: Complete member initialization this.isbn = p1; this.title = p2; this.author = p3; this.buyprice = p4; } } public partial class display : System.Web.UI.Page { private ArrayList books; String txt; String bookname; String bookauthor; double price; protected void Page_Load(object sender, EventArgs e) { books = new ArrayList(); BookDetails(); } private void BookDetails() { Book1 b1 = new Book1("978-1449311520", "adoop: The Definitive Guide", "Tom White", 15.99); Book1 b2 = new Book1("978-0735667044", "Microsoft Visual Basic 2013 Step by Step", "Michael Halvoson", 9.50); Book1 b3 = new Book1("978-0993088100", "Fifty Quick Ideas to Improve Your User Stories", "David Evens/Gojko Adzick", 33.00); Book1 b4 = new Book1("978-1428336117", "The Medical Manager Student Edition", "David Fitzpatrick", 99.00); Book1 b5 = new Book1("978-0769302652", "Introduction to Language Development", "Scott McLaughlin", 55.00);...

Words: 773 - Pages: 4

Premium Essay

Unit 3

...Lab 3: Input, Processing, and Output This lab accompanies Chapter 2 (pp. 56-68) of Starting Out with Programming Logic & Design. Chris Garcia Name: ___________________________ Lab 3.1 – Pseudocode This lab requires you to think about the steps that take place in a program by writing pseudocode. Read the following program prior to completing the lab. Write a program that will take in basic information from a student, including their name and how many credits they have taken in Network Systems Administration program. The program will then calculate how many credits are needed to graduate. Display should include the student name and the number of credits left to graduate. This should be based off a 90 credit program, where some courses are half credits. Step 1: This program is most easily solved using just a few variables. Identify potential problems with the following variables declared in the pseudocode. Assume that the college has the ability to offer half credits. (Reference: Variable Names, page 39-40). |Variable Name |Problem (Yes or No) |If Yes, what’s wrong? | |Declare Real creditsTaken |n | | |Declare Int creditsLeft |y | | |Declare Real studentName ...

Words: 1394 - Pages: 6

Premium Essay

Resume

...Engineer | SOFTWARE PROFICIENCY |Web Technologies  |HTML, XML | |Script |PERL Scripting,Java Scripts | |RDBMS/DBMS |Oracle 9i | |IDE’s |Eclipse, NetBeans | |Languages |C++, SQL, PL\SQL, Visual Basic and JAVA | |Operating System |Windows XP, Windows 95/98, & UNIX | |PLM/PPM Packages |Windchill/Planisware 5 | PROJECTS UNDERTAKEN |Project Name |Support and Enhancement of the Product Planisware 5(PPM) | |Period |01-July-10 to | |Location...

Words: 431 - Pages: 2

Free Essay

Cis115

...Week 7 iLab—Sales Tax TCO 3: Given a simple problem, design and desk-check a solution algorithm requiring a modular design that is expressed in terms of pseudocode or program notes, input-process-output (IPO) analysis, and flow chart. * TCO 7: Given a program with logic errors that is intended as a solution to a simple problem, employ debugging diagnostics to remove and correct the errors. TCO 8: Given a more complex problem, develop a complete solution that includes a comprehensive statement of the problem, complete program design, and program documentation. Scenario Your algorithm will write two functions called ComputeTotal( ) and ComputeTax( ). ComputeTotal( ) will receive the quantity of items purchased, and the unit price of each item. It will return the total sales (quantity times price). ComputeTax( ) will receive total sales as a number and the state as a string and return the amount of tax depending on the state. NJ requires 7% tax, FL requires 6% tax, and NY has 4% tax. The main program will ask for the name of the customer and read the name in a variable called name. It will also ask for one of the three states listed above. It will ask for the number of items sold and the unit price of the item. Main will then call ComputeTotal( ), passing the quantity and unit price. Main will then call ComputeTax( ), passing the state and the amount of sales and receive back the tax. Finally Main( ) will print out the total sales, the tax amount, and the total...

Words: 784 - Pages: 4

Free Essay

Sfsfsfsfsfsfsfsfs

...Азбука Visual Basic Как вам, быть может, известно, программирование интерфейса в среде Windows некоторое время назад являлось весьма сложной задачей: надо было написать кучу строк кода (например, на С++), чтобы через час-другой трудов увидеть свое творение на экране, так что программы для Windows писали долго и не поодиночке. Visual Basic же позволяет это делать, как уверяют разработчики и энтузиасты, с отличной производительностью и непревзойденной легкостью. В абсолютно вольном переводе название Visual Basic можно трактовать как "наглядная простота". Любой школьник теперь знает, что Basic относится к простейшим языкам для написания компьютерных программ. По обычным человеческим меркам он довольно древний, поскольку был создан аж в 1964 г. Его разработчики - Томас Курт и Джон Кемени - уже тогда хотели сделать его языком для начинающих, облегчающим написание несложных программ. И вот почти 30 лет спустя, в начале 90-х гг., их последователи из Microsoft сумели этой простоте придать легкий оттенок гениальности. Новая разновидность языка под названием Visual Basic позволяла начинающему программисту решать не только простейшие задачи, но и весьма сложные, которые ранее можно было осуществить только на серьезных и сложных языках типа C++. По сути дела, это была революция в способе создания приложений под Windows (рис. 1). Рис. 1. Эта трехмерная сцена использует возможности Direct3D. А написана она на Visual Basic. Действительно, в основу программного пакета было положено передовое...

Words: 3449 - Pages: 14