Chapter 1. Introducing Visual Basic 2005
When Microsoft released its new version of Visual Basic in 2002, many developers willingly upgraded to take advantage of the new web functionality, security, and performance provided by the .NET platform on which it was built. But in doing so, many also felt they were leaving behind the features that had made Visual Basic 6.0 such a popular tool for the rapid development of Windows applications in the first place.
The release of Visual Basic 2005 (VB 2005) is in many ways a return to Visual Basic’s roots as the Rapid Application Development (RAD) tool of choice. Many of the most popular features of earlier versions are back, such as Edit and Continue, along with dozens of new controls, better IntelliSense, an improved debugger, and a host of other tools that speed up programming, debugging, testing, and deployment.
Besides the many tools added to its interactive development environment (IDE), Visual Basic 2005 provides more support than ever for developing the next generation of network-enabled Windows clients and web applications, while a new set of functionality unique to VB 2005—the My
namespace—gives you the means by which to perform many common tasks without having to work your way through the complex types of the .NET class libraries.
The best way to learn about Visual Studio 2005 is by using the tool to build an application. In the following sections, you’ll assemble a straightforward Windows client that enables users to connect to a database and browse or update the information they find there. You’ll work with the authors table of the pub’s database that ships with SQL Server 2005. You’ll also see how you can extend the application using some of the features new to VB 2005, such as project templates and application configuration tools. Figure 1-1 shows how the main window of the the completed application will look when you’ve finished your work.
Tip
Although this book uses Microsoft Visual Studio 2005 as the tool to build the sample applications, you can also use Microsoft Visual Basic 2005 Express Edition.
Create the Application and Its Main Window
Let’s start by using Visual Studio 2005 to create a Windows application, one that you can program with VB 2005.
First, you need to fire up Visual Studio 2005 and open a new project by selecting File → New Project… on the Visual Studio 2005 menu. Visual Studio displays the New Project dialog shown in Figure 1-2.
In the Project types window of the New Project dialog, select Visual Basic and then select the Windows Application template in the Visual Studio installed templates dialog window. Keep the default project Name, WindowsApplication1, provided by Visual Studio. Click OK.
Visual Studio 2005 will present you with its familiar Windows development environment, shown in Figure 1-3, including a designer surface for Form1, which will become the startup window of your application.
Add a Menu and Toolbar
Let’s now add a menu and toolbar to the form. In VB 2005, you can create professional looking Windows applications, complete with menus and toolbars that look like those used with Microsoft Office applications.
In the Menus & Toolbars tab in Toolbox, shown in Figure 1-4, locate and then drag and drop the
ToolStripContainer
control onto the form. TheToolStripContainer
control allows other controls (such as theToolStrip
control) to anchor in the four positions available (left, right, top, and bottom).In the
ToolStripContainer
Tasks menu, click on the “Dock Fill in Form” link (see Figure 1-5) to dock theToolStripContainer
control onto the form. This will cause theToolStripContainer
control to fill up the entire form and automatically resize itself when the form is resized.Now you’ll add the application menu. Double-click on the
MenuStrip
control in the Toolbox to add it to the form. TheMenuStrip
control displays a standard list of drop-down menus at the top of a window. In theMenuStrip
Tasks menu, click on the Insert Standard Items link to add a list of commonly used menu items to the control (see Figure 1-6).Your form should now look like the one shown in Figure 1-7.
Now you’ll add a toolbar to Form1. Select the
MenuStrip
control that you have just added by single-clicking on it. In the Toolbox, double click on theToolStrip
control (or drag and drop it) to add it to the form. This will add theToolStrip
control to the top of theToolStripContainer
control, thereby making it moveable. You use theToolStrip
control to display buttons for tasks users will commonly want to perform. Initially, the toolbar is blank. To add common toolbar items, click on the Insert Standard Items link in theToolStrip
Tasks menus. Your form should now look like Figure 1-8.To test the application, press F5. You will now be able to drag the
ToolStrip
control and anchor it in one of the four positions (see Figure 1-9).
Connect to a Database and Browse Records
One great time-saving feature in VB 2005 is its new support for automatic data binding. The automatic–data binding feature allows you to connect to a data source and then drag and drop the connection onto a Windows Forms application. A set of controls bound to the data source will then be automatically added to the form, and you can perform a variety of operations on the data source, such as navigating through records, searching for a specific record, and more, without having to write any code.
To see how automatic data binding works, you will now connect to a database and then drag and drop one of its tables onto your form so that you can view and work with its records. You will use SQL Server 2005 Express and the pubs database and then view and edit the records in the authors table.
Select Data → Show Data Sources to display the Data Sources window, as shown in Figure 1-10. The Data Sources window allows you to connect to your data sources (such as databases, web services, and business objects) and view their content. Click on the Add New Data Source… link to add a new data source to your project (see Figure 1-10).
When the Data Source Configuration Wizard appears, click Next.
The Choose a Data Source dialog, which appears next, lets you choose between a database, a web service, or some other object as the source of your data. You’ll be using a database, so click the Database icon and then click Next.
Now you need to select a data connection to use to connect to your database. In the “Choose your data connection” dialog, click New Connection….
The Add Connection dialog will be shown (see Figure 1-11).
Tip
For this step, I am assuming you have SQL Server 2005 Express installed on your computer. You can download SQL Server 2005 Express from: http://www.microsoft.com/sql/express/default.mspx.
As SQL Server 2005 Express does not come with any sample databases, you need to install the sample database yourself. See the sidebar “SQL Server 2005 Express and the pubs and Northwind Databases” for more information.
Enter the details of your database (see Figure 1-11). Type
.\SQLEXPRESS
for Server name if your database is installed locally on your machine. Select the database to use (in this example, select the sample pubs database in SQL Server 2005 Express). Click OK and Next in the next window.Visual Studio 2005 now has the information it needs to create the connection string that will let your application access the pubs database. The “Save the connection string to the application configuration file” step gives you the useful option of naming and saving the connection string in the application configuration file, as shown in Figure 1-12. Having the information in a configuration file lets you change database details without recompiling the application, even after it has been deployed. Leave the checkbox checked, give the connection string the name
pubsConnectionString
, and click Next to display the next part of the Data Source Configuration Wizard dialog.With a connection string in place, you’re now in a position to select the table(s) you want to work with. The “Choose your database objects” step shown in Figure 1-13 displays the tables (and fields) of the pubs database. Your application will give users access to author information stored in the pubs database, so check the authors table to select all fields and then click Finish to move to the next step, which displays a completed Data Sources window for your application. You can return to the Data Sources window whenever you need to make changes by clicking on the Data Sources tab next to the Solution Explorer or by going to the Visual Studio menu and selecting Data → Show Data Sources.
One last step is required to make the authors table accessible to your users: you need to bind each field to a control that can be displayed in the application window. In the Data Sources window, you’ll see that the authors table is displayed as a tree, as shown in Figure 1-14, and that each field has been bound to a specific type of control. For example, the au_lname field is bound to a text box (represented by the icon containing the letters “abl”). You can change the binding by clicking on the field name and then choosing another binding. For now, we’ll make only one change. Click on the drop-down menu for the au_id field and then choose the
Label
control (as represented by the icon containing the letter A, as shown in Figure 1-14).Also, you should change the authors table binding to Details (using the drop-down menu for the authors field shown in Figure 1-15) so that you can view the authors table one record at a time. The reason for doing this will become evident to you in the next step when we add the ability for users to navigate through the table.
Now you’re ready the drag and drop the authors item in the Data Sources window onto the default Windows Form and watch Visual Studio 2005 perform some real magic. For starters, Visual Studio automatically populates Form1 with the controls shown in Figure 1-16. Visual Studio 2005 also adds a new
BindingNavigator
control to the top of the form. The newBindingNavigator
control lets users navigate through all the records in the table as displayed in the form.By default, the
BindingNavigator
control is docked (fixed) to the top of the form and is not moveable. Set theDock
property toNone
and rearrange the controls as shown in Figure 1-17.You can now test the application by pressing F5. Form1, the main window of your application, will display, complete with menu, toolbar, and navigation control, as shown in Figure 1-18. You should be able to navigate the records in the authors table as well as move the various toolbars around. Try scrolling through the table by clicking the arrows on the
BindingNavigator
control.You should also be able to edit individual records by modifying the values in the text box bound to each field. Try it. To save a modified record to the database, you need to click on the Save icon, which is represented by the diskette icon in the
BindingNavigator
control.Visual Studio 2005 automatically adds the relevant code to the code behind of the form to handle the retrieving and saving of data. To see the code added by Visual Studio 2005, double-click on the diskette icon to reveal the code behind. You will see the code shown in Example 1-1.
Example 1-1. Save menu item code behind added by Visual Studio 2005Private Sub bindingNavigatorSaveItem_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles bindingNavigatorSaveItem.Click If Me.Validate Then Me.AuthorsBindingSource.EndEdit() Me.AuthorsTableAdapter.Update(Me.PubsDataSet.authors) Else System.Windows.Forms.MessageBox.Show( _ Me, "Validation errors occurred.", "Save", _ System.Windows.Forms.MessageBoxButtons.OK, _ System.Windows.Forms.MessageBoxIcon.Warning) End If End Sub
Create an Exit Dialog Box
For most Windows applications, it is customary to ask users if they really want to quit an application when they either click the Close window button or select Exit on the File menu. In this section, you’ll use Visual Studio 2005 and VB 2005 to add a dialog box that asks users to confirm that they really want to quit the application when they select either action.
First, let’s create the dialog box by adding a new Dialog to the project. You add a new Dialog to your project by right-clicking on the project name in Solution Explorer, which is
WindowsApplication1
, and then selecting Add → New Item…. In the Add New Item dialog, select Dialog and use the default name of Dialog1.vb as shown in Figure 1-19.Notice that the Dialog window already comes with two buttons: OK (
OK_Button
) and Cancel (Cancel_Button
).Populate the dialog with the
Label
control shown in Figure 1-20 by dragging and dropping it from the Toolbox. Also, resize the dialog window.Set the properties of the various controls to the values shown in Table 1-1. To set the properties of a control, right-click the control and select Properties to display its Property window. Look for each Property you wish to set by scrolling through the Properties window and entering the appropriate value.
Table 1-1. Properties of the various controls
Handle Exit and Close Events
Now it’s time to write some code to link the Exit dialog with the events triggered by users when they attempt to exit or close the application.
First, you’ll add code to deal with the Exit menu item when a user selects it. To get started, expand the File menu in Form1 and doubleclick on the Exit menu item (see Figure 1-21) to open the code-behind page shown in Figure 1-22.
The code-behind page contains all of the code that you write for the application. So far in this chapter, all of the work has been done by Visual Studio, but the code it has generated to support your work with the designer and wizards is hidden and out of sight for now. You’ll see how to view this code in Chapter 2.
When you double-click on the Exit item of the application menu on Form1, Visual Studio deduces that you wish to write code to specify how the exit event will be handled, just as it does in VB 6. Note that the code behind page in this example is named Form1.vb. As you can see in Figure 1-22, Visual Studio has already generated the code to create the event handler. All you need to do is specify what specific actions are to be taken when the event handler is called by placing your cursor on the line below the handler declaration and entering your own code.
Now, code the exit event of the
ToolStrip
control by entering the code shown in bold in Example 1-2 on the code-behind page.Example 1-2. Exit menu item event handlerPrivate Sub exitToolStripMenuItem_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles exitToolStripMenuItem.Click
Dim result As DialogResult = Dialog1.ShowDialog() If result = Windows.Forms.DialogResult.OK Then End End If
End SubWhen users select the Exit item on the File menu, an exit event fires and the code in Example 1-2 displays Dialog1, which forces users to confirm whether or not they really want to exit the application. If a user selects OK, then the application exits; otherwise, no action is taken and the dialog window closes.
Much of the code in Example 1-2 will seem familiar to VB 6 users.
Dim
statements are still used to declare variables, theIf…Then
statement is unchanged, and theSub…End Sub
block is still used to define subroutines. What’s new is the way in which the code makes use of classes, methods, and properties found in the .NET Framework, most visibly in the use of dot (.) syntax to reference them. You’ll learn more about VB 2005 data types and language syntax in Chapter 2. Later in Chapter 3, you’ll see how to use the new support for object-oriented programming and the .NET Framework in VB 2005 to greatly increase your productivity.Now you need to add code to handle the case when the user closes the application window (Form1) by clicking on the Close button at top the right of the application windowt. This is handled by coding the
FormClosing
event of Form1, as shown in Example 1-3. Again, when the user clicks the Close button, you’ll display Dialog1. If the user selects the OK button, end the application. If the user selects the Cancel button, cancel the close operation by setting theCancel
property of theSystem.Windows.Forms.FormClosingEventArgs
argument toTrue
. You can get Visual Studio 2005 to generate the code stub for theFormClosing
event by selecting the Form1 Events item in the left drop-down list (see Figure 1-23) and then selectingFormClosing
in the second drop-down list. Enter the code shown in bold in Example 1-3.Example 1-3. FormClosing event handlerPrivate Sub Form1_FormClosing( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms.FormClosingEventArgs) _ Handles Me.FormClosing
Dim result As DialogResult = Dialog1.ShowDialog() If result = Windows.Forms.DialogResult.OK Then End Else e.Cancel = True End If
End Sub
Run and Debug the Application
With the code you have added in the last section, it is now time to test the application. This is a good chance for you to see some of the new enhancements in the new Visual Studio 2005 debugger. For this example, you will set a breakpoint so that you can examine the values of variables at a particular point in the code.
Now set a breakpoint in the application by clicking on the gray bar on the left of the code edit window (see Figure 1-24) and then running the application by pressing F5. You will set the breakpoint so that the program halts when you click on the Close box, allowing you to examine the value of
DialogResult
returned by the Exit dialog box (Dialog1
).When the form is loaded, close the form to display the dialog box. Click OK, and the application will stop at the breakpoint you have set. To step through the code one line at a time, press F11 (see Figure 1-25).
Inspect an Object at Runtime
The debugger in Visual Studio 2005 now supports a new feature known as DataTips. Using DataTips, you can examine the values in a complex data type while you are debugging the application, otherwise known as debug time. This is a marked improvement over Visual Studio .NET 2003, where only simple data types can be examined by placing the cursor over a variable name.
Figure 1-26 shows the DataTips display for the FormClosingEventArgs
object. To see this result, simply position your cursor over the name of the variable or object that you are interested in while the program is stopped at a breakpoint. Not only can you view the values of variables and objects, you can also edit and change their values during debug time.
Add an About Box
VB 2005 now comes with several new templates that make developing a Windows application easy. Among the new templates are:
- Explorer Form
Allows you to build applications similar to Windows Explorer, with a tree-like display on the left pane and a detailed view on the right pane.
- About Box
Displays an About window listing detailed information (such as version number, copyright, credits, etc.) about the current application.
- Login Form
Creates a standard login window to simplify the task of user authentication.
- Splash Screen
Displays a welcome screen when your application is launched.
In this section, you will add an About box to your application using the About Box template. The About box for an application is displayed when a user selects Help → About… and contains useful information about the application, including its manufacturer and version number. Much of the information in the About box is available from the application and its configuration files.
First, you need to create an About box form. Right-click on the project name (
WindowsApplication1
) in Solution Explorer and select Add New Item…. Select the About Box template and accept the default name of AboutBox1.vb provided by Visual Studio 2005. Click Add (see Figure 1-27).The AboutBox1.vb form will be added to your project, and Visual Studio 2005 will display a designer for the feature as shown in Figure 1-28.
Let’s personalize the form by adding an image of the cover for this book to replace the default pretzel-like image. Click the
LogoPictureBox
control and then, in the Property window for the control, click the “…” button of its Image property. This will display the Select Resource dialog window. Click the Import… button of the dialog to select your own image for the About box (C:\vbjumpstartpg.gif). Click OK (see Figure 1-29).Tip
You can download the vbjumpstartpg.gif image from: http://www.oreilly.com/catalog/vbjumpstart/.
Set the
SizeMode
property of theLogoPictureBox
control toCenterImage
.To configure the information about your application so that it can be displayed by the About box, right-click on the project name in Solution Explorer and then select Properties. In the Application tab, click on the Assembly Information… button (see Figure 1-30).
Set the information as shown in Figure 1-31.
The AboutBox1 window should now look like the one shown in Figure 1-32.
To link Form1 with the AboutBox1 window, expand the Help menu and double-click on the About… menu item (see Figure 1-33) to open the code-behind page for Form1 and generate a code stub for the About box selection event handler.
Now add the line of code shown in bold to the code stub generated by Visual Studio, as shown in Example 1-4). You use the
ShowDialog
method of the dialog window to get the object display itself.Finally, it’s time to take your work for a trial run. Press F5 to run the application. Click Help → About… and you will see the About box shown in Figure 1-34.
Configure the Application
In the application that you have built, you can move and anchor the ToolStrip
control as you wish while you are using the application. However, you may have noticed that its position is lost each time you exit the application. This is because you need to manually save its positions each time you exit the application, or else the information will be lost. Fortunately, this can be done easily with the new Application Settings feature in VB 2005. In this section, you’ll see how.
You’ll begin by adding code to save the location of the
ToolStrip
control. Select theToolStrip
control and, in its Properties window, select thePropertyBinding
property (under the “(ApplicationSettings
)” property; see Figure 1-35). Click the “…” button.Locate the Location property (this property determines where the control should be placed) and click the drop-down listbox. Click on the New… link at the bottom and create a new application setting called
ToolStripLocation
(see Figure 1-36). Be sure to set the scope toUser
. Click OK. Be sure to set the Location property to the newly created application setting.You have now created an application setting that binds the position of the
ToolStrip
control to theToolStripLocation
application setting. When the form is loaded, theToolStrip
control will get its Location property from the application settings, which is saved in the app.config file.Now, perform the same steps 1 and 2 for the
MenuStrip
control,MenuStrip1
. Name its application settingMenuLocation
.You will want to save the current locations of all two controls whenever Form1 is closed, so add the bold code to the
FormClosing
event andExit
menu item event as shown in Example 1-5.Example 1-5. Saving control location data when a user exits or closes Form1Private Sub Form1_FormClosing(ByVal sender As Object, _ ByVal e As System.Windows.Forms.FormClosingEventArgs) _ Handles Me.FormClosing
Dim result As DialogResult = Dialog1.ShowDialog() If result = Windows.Forms.DialogResult.OK Then My.Settings.MenuLocation = MenuStrip1.Location My.Settings.ToolStripLocation = ToolStrip1.Location My.Settings.Save() End Else e.Cancel = True End If
End Sub Private Sub exitToolStripMenuItem_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles exitToolStripMenuItem.ClickDim result As DialogResult = Dialog1.ShowDialog() If result = Windows.Forms.DialogResult.OK Then My.Settings.MenuLocation = MenuStrip1.Location My.Settings.ToolStripLocation = ToolStrip1.Location My.Settings.Save() End End If
End Sub
Tip
Note that in this example, only the ToolStrip
control is moveable. You can make the MenuStrip
control moveable by changing its
GripStyle
property from Hidden
to Visible
.
In Example 1-5, when a user closes the application either by closing the window or clicking on the Exit menu item, the application saves the position of the MenuStrip
and ToolStrip
controls using the application settings that you have created. You can access the application settings programmatically by using the My.Settings
object (they automatically appear under the My.Settings
object after you have created them). Once the locations of these two controls are assigned to the application settings, you use the Save
method of the My.Setting
object to persist this information to the
app.config file.
Summary
In this chapter, you built a Windows application using VB 2005 and Visual Studio 2005. Though the application is simple, its assembly illustrates several key enhancements to the VB 2005 language and the Visual Studio 2005 development tool. To recap, here are the major features you explored:
New controls with Smart Tasks menus
New Windows application templates
Debugging and restored support for edit-and-continue
Improved IntelliSense and improved Code Editor
Data Source Configuration Wizard
Application Settings
In next chapter, you will learn more about the language syntax of the new VB 2005.
Get Visual Basic 2005 Jumpstart now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.