Part I: Getting Started Chapter 1: IDE RI Chapter 3: Program and Module Structure AL Chapter 2: Controls in General TE Chapter 4: Data Types, Variables, and Constants MA Chapter 5: Operators TE D Chapter 6: Subroutines and Functions GH Chapter 7: Program Control Statements RI Chapter 8: Error Handling PY Chapter 9: Introduction to Windows Forms Controls CO Chapter 10: Forms Chapter 11: Database Controls and Objects Chapter 12: Custom Controls Chapter 13: Drag and Drop, and the Clipboard
IDE This chapter describes the Visual Studio integrated development environment (IDE). It explains the most important windows, menus, and toolbars that make up the environment, and shows how to customize them to suit your personal preferences. It also explains some of the tools that provide help while you are writing Visual Basic applications. Even if you are an experienced Visual Basic programmer, you should at least skim this material.
Part I: Getting Started To avoid confusion, you should probably not customize the IDE’s basic menus and toolbars too much. Removing the help commands from the Help menu and adding them to the Edit menu will only cause confusion later. Moving or removing commands will also make it more difficult to follow the examples in this and other books, and will make it more difficult to follow instructions given by others who might be able to help you when you have problems.
Chapter 1: IDE Although you can add any file to a project or solution, it’s not a good idea to load dozens of unrelated files. Although you may sometimes want to refer to an unrelated file while working on a project, the extra clutter brings additional chances for confusion. It will be less confusing to shrink the Visual Basic IDE to an icon and open the file using an external editor such as Word or WordPad. If you won’t use a file very often with the project, don’t add it to the project.
Part I: Getting Started If you later decide that you want to switch configurations, open the Tools menu and select Import and Export Settings to display the Import and Export Settings Wizard. Select the Reset all settings option button and click Next. In the second page, tell the wizard whether to save your current settings and click Next. On the wizard’s final page (shown in Figure 1-1), select the type of configuration you want and click Finish.
Chapter 1: IDE 1 2 3 5 4 6 7 Figure 1-2: Initially the IDE looks more or less like this. The key pieces of the IDE are labeled with numbers in Figure 1-2. The following list briefly describes each of these pieces: ❑ (1) Menus — The menus contain standard Visual Studio commands. These generally manipulate the current solution and the modules it contains, although you can customize the menus as needed.
Part I: Getting Started include Windows Forms controls and components, plus tools in the other Toolbox tabs: Crystal Reports, Data, and Components (plus the General tab is scrolled off the bottom of the Toolbox). You can add other customized tabs to the Toolbox to hold your favorite controls and components. Other project types may display other tools. For example, a Web project would display web controls and components instead of Windows Forms components.
Chapter 1: IDE Many of the menus’ most useful commands are also available in other ways. Many provide shortcut key combinations that make using them quick and easy. For example, Ctrl+N opens the New Project dialog box just as if you had selected the File ➪ New Project menu command. If you find yourself using the same command very frequently, look in the menu and learn its keyboard shortcut to save time later. Many menu commands are also available in standard toolbars.
Part I: Getting Started Figure 1-3: The File menu holds commands that deal with the solution and its files. Figure 1-4: The New Project dialog box lets you start various kinds of new projects.
Chapter 1: IDE Figure 1-5: The Open File dialog box lets you select files to view and edit. ❑ Add — This submenu lets you add new items to the current solution. This can be very useful when you are building two closely related projects. For example, if you have a Windows forms application that calls routines written in a class library, you can load both projects into the same solution and work on them together.
Part I: Getting Started Figure 1-6: The File ➪ Export Template command displays this dialog box to help you create project or items templates that you can easily use in other projects. Edit The Edit menu, shown in Figure 1-7, contains commands that deal with manipulating text and other objects. These include standard commands such as the Undo, Redo, Cut, Copy, Paste, and Delete commands that you’ve seen in other Windows applications.
Chapter 1: IDE Figure 1-7: The Edit menu holds commands that deal with manipulating text and other objects. ❑ Insert File As Text — This command lets you select a file and insert its text into the current location. ❑ Advanced — The Advanced submenu contains commands for performing more complex document formatting such as converting text to upper- or lowercase, controlling word wrap, and commenting and uncommenting code.
Part I: Getting Started View The View menu, shown in Figure 1-8, contains commands that let you hide or display different windows and toolbars in the Visual Studio IDE. Following is a description of commands associated with the View menu: ❑ Code — The Code command opens the selected file in a code editor window. For example, to edit a form’s code, you can click on the form in the Solution Explorer and then select View ➪ Code.
Chapter 1: IDE ❑ Tab Order — If the currently visible document is a form that contains controls, the Tab Order command displays the tab order on top of each control. You can click the controls in the order you want them to have to set their tab order’s quickly and easily. ❑ Toolbars — The Toolbars submenu lets you toggle the currently defined toolbars to hide or display them. This submenu lists the standard toolbars in addition to any custom toolbars you have created.
Part I: Getting Started Project The Project menu shown in Figure 1-10 contains commands that let you add and remove items to and from the project. Which commands are available depends on the currently selected item. Following is a description of commands associated with the Project menu: ❑ New items — The first several commands let you add new items to the project. These commands are fairly self-explanatory. For example, the Add Class command adds a new class module to the project.
Chapter 1: IDE Figure 1-11: The Project menu’s Add New Item command lets you add a wide variety of items to the project. ❑ Show All Files — The Show All Files command makes Solution Explorer list files that are normally hidden. These include resource files corresponding to forms, hidden partial classes such as designer-generated form code, resource files, and files in the obj and bin directories that are automatically created by Visual Studio when it compiles your program.
Part I: Getting Started Figure 1-12: Use the Add Reference dialog box to add references to libraries. Figure 1-13: Use the Add Web Reference dialog to add references to web services. In Figure 1-14, the Toolbox, Error List, Task List, and other secondary windows have been hidden to make more room for the large Properties page. You can see these other windows’ icons lurking along the left and bottom edges of the figure.
Chapter 1: IDE Figure 1-14: Property pages let you set a project’s properties. Click the tabs on the left to view and modify different types of application settings. You can leave many of the property values alone and many are set in other ways. For example, by default, the Assembly name and Root namespace values shown in Figure 1-14 are set to the name of the project when you first create it. There are three properties on the Compile tab shown in Figure 1-15 that deserve special mention.
Part I: Getting Started Figure 1-15: The Compile tab contains important properties for controlling code generation. The second compiler option is Option Strict. When this option is turned off, Visual Studio allows your code to implicitly convert from one data type to another, even if the types are not always compatible. For example, Visual Basic will allow the following code to try to copy the string s into the integer i. If the value in the string happens to be a number, as in the first case, this works.
Chapter 1: IDE accident. This also helps you use the correct data types and avoid unnecessary conversions that may make your program slower. To avoid confusion and long debugging sessions, you should always set Option Explicit On and Option Strict On. You can turn them on for a project using the project’s Property pages. To make them on by default for new projects, open the Tools menu and select Options.
Part I: Getting Started ❑ Rebuild WindowsApplication1 — This command recompiles the currently selected project from scratch. The Build WindowsApplication1 command compiles only the files that you have modified since they were last built. This command rebuilds every file. ❑ Clean WindowsApplication1 — This command removes temporary and intermediate files that were created while building the application, leaving only the source files and the final result .exe and .dll files.
Chapter 1: IDE Figure 1-18: The Publish Wizard helps you deploy an application. Figure 1-19: The Run Code Analysis command displays potential problems in an application.
Part I: Getting Started Debug The Debug menu, shown in Figure 1-20, contains commands that help you debug a program. These commands help you run the program in the debugger, move through the code, set and clear breakpoints, and generally follow the code’s execution to see what it’s doing and hopefully what it’s doing wrong. Effectively using these debugging techniques can make finding problems in the code much easier, so you should spend some time learning how to use these tools.
Chapter 1: IDE ❑ Continue — This command resumes program execution. The program runs until it finishes, it reaches another breakpoint, or you stop it. ❑ Break All — This command stops execution of all programs running within the debugger. This may include more than one program if you are debugging more than one application at the same time. This can be useful, for example, if two programs work closely together.
Part I: Getting Started When you right-click on a property’s value and select Edit Value, you can change it within the dialog box. If you click the Add Watch button, the debugger adds the expression to the Watch window shown in Figure 1-22. You can also highlight a variable’s name in the code and drag and drop it into a Watch window to create a watch very quickly. Right-click a watch in this window and select Delete Watch to remove it.
Chapter 1: IDE ❑ Toggle Breakpoint — This command toggles whether the current code line contains a breakpoint. When execution reaches a line with an active breakpoint, execution pauses so you can examine the code and program variables. You can also toggle a line’s breakpoint by clicking on the margin to the left of the line in the code editor.
Part I: Getting Started ❑ Immediate — This command displays the Immediate window, where you can type and execute ad hoc Visual Basic statements. The section “The Command and Immediate Windows” later in this chapter describes this window in a bit more detail. ❑ Locals — This command displays the Locals window shown in Figure 1-25. The Locals window displays the values of variables defined in the local context. To change a value, click it and enter the new value.
Chapter 1: IDE ❑ Output — This command displays the Output window. This window displays compilation results and output produced by Debug and Trace statements. ❑ Autos — This command displays the Autos window shown in Figure 1-27. This window displays the values of local and global variables used in the current line of code and in the three lines before and after it. ❑ Call Stack — This command displays the Call Stack window shown in Figure 1-28.
Part I: Getting Started Figure 1-29: The Threads window displays information about the program’s threads of execution. ❑ Watch — The Watch submenu contains the commands Watch 1, Watch 2, Watch 3, and Watch 4. These commands display four different watch windows. When you create a watch using the Debug menu’s QuickWatch command described earlier, the new watch is placed in the Watch 1 window (shown in Figure 1-22).
Chapter 1: IDE ❑ Script Explorer — This command displays the Script Explorer, which can help you debug script code written in VBScript or JScript. ❑ Processes — This window lists processes that are attached to the Visual Studio session. This includes any programs launched by Visual Studio and processes that you attached to using the Debug menu’s Attach to Process command. The Breakpoints Window A breakpoint is a line of code that you have flagged to stop execution.
Part I: Getting Started Right-click a breakpoint and select Hit Count to display the Breakpoint Hit Count dialog box shown in Figure 1-32. Each time the code reaches a breakpoint, it increments the breakpoint’s hit count. You can use this dialog box to make the breakpoint’s activation depend on the hit count’s value.
Chapter 1: IDE The Command and Immediate Windows The Command and Immediate windows enable you to execute commands while the program is stopped in the debugger. One of the more useful commands in each of these windows is the Debug.Print statement. For example, the command Debug.Print x displays the value of the variable x. You can use a question mark as an abbreviation for Debug.Print. The following text shows how the command might appear in the Command window.
Part I: Getting Started You can execute much more complex statements in the Command and Immediate windows. For example, suppose that your program uses the following statement to open a file for reading. Dim fs As FileStream = File.OpenRead( _ “C:\Program Files\Customer Orders\Summary” & _ datetime.Now().ToString(“yymmdd”) & “.dat”) Suppose that the program is failing because some other part of the program is deleting the file.
Chapter 1: IDE Figure 1-34: The Data menu holds commands that deal with datasets. ❑ Make Same Size — This submenu contains commands that change the size of the controls you have selected. It contains the commands Width, Height, Both, and Size to Grid. The Size to Grid command adjusts the selected controls’ widths so that they are a multiple of the alignment grid size. The other commands give the selected controls the same width, height, or both.
Part I: Getting Started Figure 1-35: The Format menu contains commands for formatting and arranging controls on a form. ❑ Lock Controls — This command locks all of the controls on the form so that they cannot be moved or resized by clicking and dragging. You can still move and resize the controls by changing their Location and Size properties in the Properties window. Invoking this command again unlocks the controls.
Chapter 1: IDE Figure 1-36: The Tools menu contains miscellaneous commands and commands that modify the IDE. ❑ Connect to Device — This command lets you connect to a physical device or emulator such as Pocket PC or Smartphone devices or emulators. You can use the devices and emulators to test software you are writing for devices other than the Windows platform where you are building the application.
Part I: Getting Started ❑ Add-in Manager — This command displays the Add-in Manager, which lists the add-in projects registered on the computer. You can use the Add-in Manager to enable or disable these add-ins. ❑ Macros — The Macros submenu contains commands that help you create, edit, and execute macros. See the section “Macros” later in this chapter for details. ❑ Upgrade Visual Basic 6 Code — This command displays the dialog box shown in Figure 1-37.
Chapter 1: IDE ❑ Device Emulation Manager — This command displays the Device Emulation Manager, which lets you connect, reset, shut down, and otherwise manipulate device emulators. ❑ Import/Export Settings — This command displays a dialog box that you can use to save, restore, or reset your Visual Studio IDE settings. Use this dialog box to configure your development environments for general development, team test, Visual Basic, C#, C++, J#, or Web development.
Part I: Getting Started Some examples of macros that I’ve used in the past include code that: arranges controls in unusual ways, such as spacing picture boxes around the edge of a circle; that generates a long series of statements that does the same thing to a collection of text values (for example, makes Select Case statements for a series of text values); sets up a new dialog box by creating the OK and Cancel buttons, positioning them, setting their DialogResult properties, and setting the form’s AcceptBu
Chapter 1: IDE Sometimes when you perform a series of programming tasks many times, there are better ways to approach the problem than writing a macro. For example, you may be able to make your program repeat the steps inside a loop. Or you may be able to extract the common code into a subroutine and then call it repeatedly rather than repeating the code many times. In these cases, your application doesn’t need to contain a long sequence of repetitive code that may be hard to debug and maintain.
Part I: Getting Started Figure 1-41: The Customize dialog box’s Commands tab lets you add commands to toolbars and menus. To create a new menu, select the New Menu item in the list on the left. Then drag and drop the New Menu entry from the right list onto the IDE’s menu area. To make a command that executes a macro you have created, select the Macros category in the list on the left. Find the macro you want to use in the list on the right, and drag it onto a toolbar or menu.
Chapter 1: IDE image from the clipboard. For example, you can open a bitmap using Microsoft Paint, press Ctrl+A to select the whole image, and press Ctrl+C to copy it to the clipboard. Then you can use the Paste Button Image command to paste the image into a button. Note that the buttons are 16 by 16 pixels. If the image you copy is larger, Visual Studio shrinks it to fit. Select the Reset Button Image command to restore the button to its default image. For a command tied to a macro, this erases the image.
Part I: Getting Started Figure 1-43: You can use the Visual Studio simple button editor to change a command’s button. The pop-up menu’s Default Style command makes the command use a style that depends on whether it is in a menu or toolbar. In a menu, the command displays a button and text. In a toolbar, the command displays only a button. Ironically, a new button’s default style is not Default Style. When you create a new toolbar or menu command, the button initially displays only text.
Chapter 1: IDE Figure 1-44: The Options dialog’s Keyboard section lets you view and modify keyboard shortcuts. Options The Tools menu’s Options command displays the dialog box shown in Figure 1-45. This dialog box contains a huge number of pages of options that configure the Visual Studio IDE. The Customize dialog box’s Keyboard button described in the previous section uses the same dialog box with the Keyboard item selected in the list on the left.
Part I: Getting Started The following list describes the Options dialog box’s most important categories: ❑ Environment — Contains general IDE settings such as whether the IDE uses a Multiple Document Interface (MDI) or Single Document Interface (SDI), the number of items shown in the MRU lists, and how often the IDE saves AutoRecover information. The Fonts and Colors subsection lets you determine the colors used by the editors for different types of text.
Chapter 1: IDE Figure 1-46: The Test menu displays commands that control Visual Studio’s testing tools. The following list briefly describes the Test menu’s commands: ❑ New Test — Displays the dialog box shown in Figure 1-47 to let you create various kinds of tests for the application. ❑ Load Metadata File — Lets you load a test metadata file. These files contain XML data that describes test lists, each of which can contain tests. This command lets you load test lists into different projects.
Part I: Getting Started Figure 1-47: The Add New Test dialog box lets you define new tests for the application. ❑ Administer Test Controllers — Lets you manage test controllers. Test controllers manage test agents and gather test results. Test agents run the tests. ❑ Select Active Test Run Configuration — Lets you select the active test run configuration.
Chapter 1: IDE Figure 1-48: The Window menu displays commands that control the Visual Studio windows. ❑ Floating, Dockable, Tabbed Document — Secondary windows such as the Toolbox, Solution Explorer, and Properties windows can be displayed as dockable, as floating, or as tabbed documents. A dockable window can be attached to the edges of the IDE or docked with other secondary windows. A floating window stays in its own independent window even if you drag it to a position where it would normally dock.
Part I: Getting Started ❑ New Vertical Tab Group — Splits the main document window vertically so that you can view two different documents at the same time. ❑ Close All Documents — Closes all documents. ❑ Reset Window Layout — Resets the window layout to a default configuration. ❑ Form1.vb — The bottom part of the Window menu lists the open documents. In Figure 1-48, it lists Form1.vb in the code editor and Form1.vb [Design] in the Form Designer (Design mode).
Chapter 1: IDE Help The Help menu shown in Figure 1-50 displays the usual assortment of help commands. You should be familiar with most of these from previous experience. One new item in the Help menu is the How Do I command. This command opens the help system and displays a page full of links to common programming topics. These topics lead to a hierarchical series of categorized tutorials on various programming topics.
Part I: Getting Started right edge). If you drop a toolbar away from the IDE’s edges, it becomes a floating window not docked to the IDE. You can use the menu commands described earlier in this chapter to determine which toolbars are visible, to determine what they contain, and to make custom toolbars of your own. Many menu commands are also available in standard toolbars. For example, the Debug toolbar contains many of the same commands that are in the Debug menu.
Chapter 1: IDE Figure 1-51: Use the IDE’s docking icons to help you dock windows. The windows in the Microsoft Document Explorer used by the MSDN Library and other external help files provide the same arranging and docking tools for managing its subwindows such as Index, Contents, Help Favorites, Index Results, and Search Results. Toolbox The Toolbox window displays a series of sections containing tools for the currently active document.
Part I: Getting Started You can customize the Toolbox by right-clicking a tab and selecting one of the commands in the context menu. The following list briefly describes these commands: ❑ List View — Toggles the current tab to display tools either as a list of names (as in the Data section in Figure 1-52) or a series of icons (as in the All Windows Forms section in Figure 1-52).
Chapter 1: IDE ❑ Rename Tab — Lets you rename a tab. ❑ Move Up, Move Down — Moves the clicked tab up or down in the Toolbox. You can also click and drag the tabs to new positions. If you right-click a tool in the Toolbox, the context menu contains these commands plus Cut, Copy, Paste, and Rename Item. Figure 1-53: Use the Choose Toolbox Items dialog box to select the tools in the Toolbox.
Part I: Getting Started Figure 1-54: The Visual Basic code editor provides many features, including line numbers and icons that indicate breakpoints and bookmarks. Margin Icons The gray margin to the left of the line numbers contains icons giving information about the corresponding lines of code. The following table describes the icons on lines 4 through 13.
Chapter 1: IDE These icons can combine to indicate more than one condition. For example, line 12 shows a blue and white rectangle to indicate a bookmark, a hollow red diamond to indicate a disabled breakpoint that performs an action, and a plus sign to indicate that the breakpoint has a condition or hit count test. Note that the editor marks some of these lines in other ways than just an icon. It highlights the currently executing line with a yellow background.
Part I: Getting Started For example, you can place several related subroutines in a region so you can collapse and expand the routines as a group. Figure 1-55 shows more examples of outlining. Line 36 begins a region named Randomization Functions that contains three collapsed subroutines. Notice that the corresponding End Region statement includes a comment giving the region’s name. This is not required but it makes the code easier to understand when you are looking at the end of a region.
Chapter 1: IDE Tooltips If you hover the mouse over a variable at design time, the editor displays a tooltip describing the variable. For example, if you hovered over an integer variable named num_actions, the tooltip would display “Dim num_actions As Integer.” If you hover over a subroutine or function call, the tooltip displays information about that method.
Part I: Getting Started If a variable has properties that are references to other objects, you can hover over their plus signs to expand those objects. You can continue following the plus signs to drill into the variable’s object hierarchy as deeply as you like. IntelliSense If you start typing a line of code, the editor tries to anticipate what you will type. For example, if you typed Me. then the editor would know that you are about to use one of the current object’s properties or methods.
Chapter 1: IDE While the IntelliSense window is visible, you can use the up and down arrows to scroll through the list. While IntelliSense is displaying the item that you want to use, you can press the Tab key to accept that item. Press the Escape key to close the IntelliSense window and type the rest manually. After you finish typing a method and its opening parenthesis, IntelliSense displays information about the method’s parameters.
Part I: Getting Started Code Coloring and Highlighting The code editor displays different types of code items in different colors. You can change the colors used for different items by selecting the Tools menu’s Options command, and opening the Environment ➪ Fonts and Colors option page. To avoid confusion, however, you should probably leave the colors alone unless you have a good reason to change them.
Chapter 1: IDE Figure 1-59: If the code editor can figure out what’s wrong, it displays a suggestion indicator. Code Snippets A code snippet is a piece of code that you might find useful in many applications. It is stored in a snippet library so that you can quickly insert it into a new application. Visual Studio comes with hundreds of snippets for performing standard tasks. Before you start working on a complicated piece of code, you should take a look at the snippets that are already available to you.
Part I: Getting Started Figure 1-60: The error suggestion dialog box proposes likely solutions to an error. Using Snippets To insert a snippet, right-click where you want to insert the code and select Insert Snippet to make the editor display a list of snippet categories. Double-click a category to find the kinds of snippets that you want. If you select a snippet, a tooltip pops up to describe it.
Chapter 1: IDE Figure 1-61: When you select a code snippet, a pop-up describes it. Creating Snippets To create a new snippet, you need to build an XML file containing the property tags to define the snippet and any replacements that the user should make. The following code shows the Create a public property snippet used in the previous section. The outer CodeSnippets and CodeSnippet tags are standard and you should not change them. Use the Title tag in the Header section to describe the snippet.
Part I: Getting Started Figure 1-62: Values that you should replace in a snippet are highlighted. DataType The property’s data type. Integer Description The property’s description.
Chapter 1: IDE 0 PropertyName The property’s name.
Part I: Getting Started The Code Editor at Runtime The code editor behaves slightly differently at runtime and design time. Many of its design time features still work. Breakpoints, bookmarks, IntelliSense, and snippets still work. At runtime, the editor adds new tools for controlling the program’s execution. Right-click a value and select Add Watch or QuickWatch to examine and monitor the value.
Chapter 1: IDE After you have used the IDE for a while and are comfortable with it, customize it to match your preferences. Build custom toolbars and menus to make using your favorite tools easier. When you have the tools that you use most at your fingertips, you will see just how productive Visual Studio can be. After you have become familiar with the IDE, you can start building applications.