Back to description
The chapters in the first part of this book describe the Visual Studio integrated development environment... more
The chapters in the first part of this book describe the Visual Studio integrated development environment (IDE). They explain the most important windows, menus, and toolbars that make up the environment, and show how to customize them to suit your needs. They explain some of the tools that provide help while you are writing Visual Basic applications and how to use the IDE to debug programs.
Even if you are an experienced Visual Basic programmer, you should at least skim this material. The IDE is extremely complex and provides hundreds (if not thousands) of commands, menus, toolbars, windows, context menus, and other tools for editing, running, and debugging Visual Basic projects. Even if you have used the IDE for a long time, there are sure to be some features that you have overlooked.
Note
When I teach Visual Basic, for example, I cover the IDE’s keyboard shortcuts (such as Alt+Space to open IntelliSense, and Ctrl+C, Ctrl+X, and Ctrl+V to copy, cut, and paste) early in the class. The students don’t really write enough code to take full advantage of these tools for several weeks, however, so we revisit the topic later.
These chapters describe some of the most important of those features, and you may discover something useful that you’ve never noticed before.
Even after you’ve read these chapters, you should periodically spend some time wandering through the IDE to see what you’ve missed. Every month or so, spend a few minutes exploring little-used menus and right-clicking things to see what their context menus contain. As you become a more proficient Visual Basic programmer, you will find uses for tools that you may have previously dismissed or not understood before.
It’s also useful to save links to tips you discover online. You can make a Visual Basic Tips folder in your browser’s favorites list to make finding tips easier.
This chapter explains how to get started using the IDE. It tells how to configure the IDE for different kinds of development. It explains Visual Basic projects and solutions, and shows how to create, run, and save new projects. This chapter is mostly an introduction to the chapters that follow. The other chapters in this part of the book provide much more detail about particular tasks such as using the IDE’s menus, customizing menus and toolbars, and using the Windows Form Designer to build forms.
... less
The Visual Studio IDE is incredibly powerful and provides hundreds of tools for building and modifying projects. The price... more
The Visual Studio IDE is incredibly powerful and provides hundreds of tools for building and modifying projects. The price you pay for all of these powerful tools is extra complexity. Because there are so many tools available, it can take some digging to find the tool you want, even if you know exactly what you need.
This chapter describes the menus, toolbars, and windows that contain the tools provided by the IDE. It explains some of the most useful tools provided by the IDE and tells where to find them, provided you haven’t moved them while customizing the IDE.
This chapter also tells how you can customize the menus and toolbars to give you easy access to the commands that you use most frequently and how to hide those that you don’t need.
The Visual Studio IDE is packed with thousands of tools that are available through toolbar and menu commands. There are so... more
The Visual Studio IDE is packed with thousands of tools that are available through toolbar and menu commands. There are so many tools available that the IDE would be practically useless if every tool were displayed at the same time. In the interests of usability, the IDE displays only the tools that the Microsoft Visual Studio developers thought would be most useful when you were performing a particular task.
Unfortunately, the Microsoft developers didn’t know exactly what you would be doing while developing applications, so they made their best guesses about which tools you would need. Under some circumstances, you may find that a completely different set of tools would be more useful. In those cases, you may want to customize the IDE.
This chapter explains how you can customize the IDE. It explains how to make new toolbars and menus, add commands to them, and determine the commands’ appearances. It also tells how you can define keyboard shortcuts to make the commands you use most often really easy to access.
The Windows Form Designer allows you to design forms for typical Windows applications. It lets you add, size, and move controls... more
The Windows Form Designer allows you to design forms for typical Windows applications. It lets you add, size, and move controls on a form. Together with the Properties window, it also lets you change a control’s properties to determine its appearance and behavior.
This chapter provides an introduction to the Windows Form Designer. It explains how to add controls to a form, move and size controls, set control properties, and add code to respond to control events. It also describes tips and tricks that make working with controls easier.
The WPF (Windows Presentation Foundation) Designer allows you to build WPF windows interactively much as the Windows Form... more
The WPF (Windows Presentation Foundation) Designer allows you to build WPF windows interactively much as the Windows Form Designer lets you build Windows Forms. It provides a WYSIWYG (what you see is what you get) surface where you can add controls to a window. If you select one or more controls on the designer’s surface, the Properties window displays the objects’ properties and lets you edit many of them.
In addition to the WYSIWYG design surface, the designer provides an XAML (Extensible Application Markup Language) code editor. Here you can view and edit the XAML code that defines the user interface. This lets you edit properties and arrange controls in ways that are impossible using the WYSIWYG designer.
This chapter provides an introduction to the WPF Designer. It explains how to add controls to a window, move and size controls, set control properties, and add code to respond to control events.
The Visual Studio IDE includes editors for many different kinds of documents, including several different kinds of code.... more
The Visual Studio IDE includes editors for many different kinds of documents, including several different kinds of code. For example, it has Hypertext Markup Language (HTML), Extensible Markup Language (XML), Extensible Application Markup Language (XAML), and Visual Basic editors. These editors share some common features, such as displaying comments and keywords in different colors.
As a Visual Basic developer, you will use the Visual Basic code editor frequently, so you should spend a few minutes learning about its specialized features. The most obvious feature of the code editor is that it lets you type code into a module, but the code editor is far more than a simple text editor such as Notepad. It provides many features to make writing correct Visual Basic code easier. This chapter describes some of the most important of these features.
The Visual Basic code editor provides many features that are not provided by other Visual Studio editors. For example, the HTML, XML, and XAML editors do not provide breakpoints or features that let you step through executing code. Even the C# code editor is missing some of the features in the Visual Basic editor, such as immediately updated error indicators as you type.
The Visual Basic Code Editor described in Chapter 6, “Visual Basic Code Editor,” provides tools that make writing Visual... more
The Visual Basic Code Editor described in Chapter 6, “Visual Basic Code Editor,” provides tools that make writing Visual Basic applications relatively easy. Features such as error indicators, tooltips, and IntelliSense help you write code that obeys the rules of Visual Basic syntax.
No code editor or any other tool can guarantee that the code you write actually does what you want it to do. Debugging is the process of modifying the code to make it run and produce correct results.
Testing tools such as NUnit (www.nunit.org) can do a lot to ensure that your code runs correctly, but they only work if the code you write does the right things. If you need a billing system but write an inventory application, no tool will save you.
www.nunit.org
Depending on the application’s complexity, debugging can be extremely difficult. Although Visual Studio cannot do your debugging for you, it does include features that make debugging easier. It allows you to stop execution while the program is running so you can examine and modify variables, explore data structures, and step through the code to follow its execution path.
This chapter explains Visual Basic’s most important debugging tools. It describes the tools available in the Debug menu and the other IDE windows that are most useful for debugging.
Controls are an extremely important part of any interactive application. They give information to the user... more
Controls are an extremely important part of any interactive application. They give information to the user (Label, ToolTip, TreeView, PictureBox) and organize the information so that it’s easier to understand (GroupBox, Panel, TabControl). They enable the user to enter data (TextBox, RichTextBox, ComboBox, MonthCalendar), select options (RadioButton, CheckBox, ListBox), control the application (Button, MenuStrip, ContextMenuStrip), and interact with objects outside of the application (OpenFileDialog, SaveFileDialog, PrintDocument, PrintPreviewDialog). Some controls also provide support for other controls (ImageList, ToolTip, ContextMenuStrip, ErrorProvider).
Label
ToolTip
TreeView
PictureBox
GroupBox
Panel
TabControl
TextBox
RichTextBox
ComboBox
MonthCalendar
RadioButton
CheckBox
ListBox
Button
MenuStrip
ContextMenuStrip
OpenFileDialog
SaveFileDialog
PrintDocument
PrintPreviewDialog
ImageList
ErrorProvider
This chapter provides only a very brief description of the standard Windows Forms controls and some tips that can help you decide which control to use for different purposes. Appendix G covers the controls in much greater detail, describing each control’s most useful properties, methods, and events.
A control is a programming object that has a graphical component. A control sits on a form and interacts with the user, providing... more
A control is a programming object that has a graphical component. A control sits on a form and interacts with the user, providing information and possibly allowing the user to manipulate it. Text boxes, labels, buttons, scroll bars, drop-down lists, menu items, toolstrips, and just about everything else that you can see and interact with in a Windows application is a control.
A component is similar to a control, except it is not visible at runtime. When you add a component to a form at design time, it appears in the component tray below the bottom of the form. You can select the component and use the Properties window to view and change its properties. At runtime, the component is invisible to the user, although it may display a visible object such as a menu, dialog box, or status icon.
This chapter explains controls and components in general terms. It describes different kinds of controls and components. It explains how your program can use them at design time and runtime to give the user information and to allow the user to control your application. It also explains in general terms how a control’s properties, methods, and events work, and it lists some of the most useful properties, methods, and events provided by the Control class. Other controls that are derived from this class inherit the use of those properties, methods, and events unless they are explicitly overridden.
Control
Appendix G, “Windows Forms Controls and Components,” describes some of the most commonly used controls in greater detail.
The Visual Basic Windows... more
The Visual Basic Windows Form class is a descendant of the Control class. The inheritance trail is Control > ScrollableControl > ContainerControl > Form. That means a form is a type of control. Except where overridden, it inherits the properties, methods, and events defined by the Control class. In many ways, a form is just another kind of control (like a TextBox or ComboBox).
Form
Control >
ScrollableControl >
ContainerControl
At the same time, Forms have their own special features that set them apart from other kinds of controls. You usually place controls inside a form, but you rarely place a form inside another form. Forms also play a very central role in most Visual Basic applications. They are the largest graphical unit with which the user interacts directly. The user can minimize, restore, maximize, and close forms. They package the content provided by the other controls so that the user can manage them in a meaningful way.
Forms
This chapter describes some of the special features of Windows Forms not provided by other objects. It focuses on different ways that typical applications use forms. For example, it explains how to build multiple-document interface (MDI) applications, custom dialogs, and splash screens.
An MDI application displays more than one document at a time in separate windows within a larger MDI parent form. MDI applications usually provide tools for managing the child forms they contain. These let the user minimize child forms, arrange the icons for the minimized forms, tile the parent form’s area with the child forms, and so on. Visual Studio can display many windows (form designers, code editors, bitmap editors, and so forth) all within its main form, so it is an MDI application.
A single-document interface (SDI) application displays only one document in each form. For example, Microsoft Paint can manage only one picture at a time, so it is an SDI application. Some SDI applications can display more than one document at a time, but each has its own separate form.
The chapter covers the Form object’s properties, methods, and events only in passing. For a detailed description of specific Form properties, methods, and events, see Appendix J.
One of the largest new additions in Visual Basic 2008 is Windows Presentation Foundation (WPF). WPF provides a whole new... more
One of the largest new additions in Visual Basic 2008 is Windows Presentation Foundation (WPF). WPF provides a whole new method for building user interfaces. It provides tools for separating the user interface from the code behind the interface so that the two pieces can potentially be built by separate user interface designers and Visual Basic developers. It includes a new Extensible Application Markup Language (XAML, pronounced “zammel”) that lets you build a user interface by using declarative statements rather than executable code. XAML lets you determine the size, position, and other properties of the WPF controls on a form. It lets you define styles that can be shared among many controls, and it lets you define transformations and animations that affect the controls.
Actually, WPF was introduced in the .NET Framework version 3.0. You can use WPF and several of the other new technologies with Visual Basic 2005, however this is the first version of Visual Basic that includes WPF, and it has better support integrated for WPF than Visual Basic 2005 has.
As is the case in Windows Forms applications, controls play a central role in WPF (Windows Presentation Foundation) applications. They give information to the user (Label, StatusBar TreeView, ListView, Image) and organize the information so that it’s easy to understand (Border, StackPanel, DockPanel, TabControl). They enable the user to enter data (TextBox, TextBlock, ComboBox, PasswordBox), select options (RadioButton, CheckBox, ListBox), and control the application (Button, Menu, Slider).
StatusBar
ListView
Image
Border
StackPanel
DockPanel
TextBlock
PasswordBox
Menu
Slider
To make an application as effective as possible, you should match controls with your application’s needs. Though it is often possible to use many controls to perform a particular task, some controls usually work better than others. For example, you could display status information by changing a button’s caption, but that’s not really what buttons do best. A label in a status bar is usually a better way to give the user status information because the user will expect and understand it. Users generally don’t expect to see status information in a button with changing text.
This chapter briefly describes the most common WPF controls so you can understand which controls work best for different purposes. To help you find the controls you need, the sections later in this chapter group controls by their general function. For example, if you need to display status to the user, look in the section “Providing Feedback.”
I provide only brief descriptions of the WPF controls in this chapter, and some tips that can help you decide which control to use for different purposes. The following chapter, “Using WPF Controls,” covers the controls in much greater detail, describing each control’s most useful properties, methods, and events.
The code behind WPF controls is the same as the code behind Windows Forms controls. That means that everything the earlier... more
The code behind WPF controls is the same as the code behind Windows Forms controls. That means that everything the earlier chapters have explained about applications, forms, controls, Visual Basic code, error handling, drawing, printing, reports, and so forth, still work almost exactly as before.
Chapter 11, “Selecting WPF Controls,” briefly describes the most common WPF controls, grouped by category to help you pick the control that best suits a particular task. This chapter provides more detail about WPF. It explains some of the more important concepts that underlie WPF. It also gives more detail about how particular controls work and tells how you can use them in your applications.
WPF is a huge topic. It basically reproduces all of the functionality of Windows Forms programming, and then some. This chapter cannot hope to cover all of the concepts, tools, and techniques used by WPF. Instead, it introduces some of the more important concepts and explains how to build basic WPF forms.
The example programs for this chapter, which are available on the book’s web site, demonstrate many of the topics described in this chapter.
In Windows Forms applications,... more
In Windows Forms applications, Form objects play a special role. They represent the top-level user interface components in which all other controls reside. A typical Windows Forms application starts by displaying a Form object. That Form may provide buttons, menus, and other controls that open other Form objects, but all of the controls are contained in Form objects.
In WPF applications, you can display controls on a Window, an object that is basically the WPF version of a Form. Alternatively you can display controls in a Page. A Page is a lot like a Window without decorations such as borders, title bar, and system menus (maximize, minimize, restore, close, and so forth). A Page must be hosted inside another object that provides these decorations. Usually, a Page is displayed in a web browser, but the WPF Frame control can act as a browser and display Page objects.
Window
Page
Frame
This chapter explains how you can use these top-level objects, Window and Page, in your WPF applications. It explains how a program can display and manage multiple Window and Page objects, and provides some examples showing simple navigation schemes.
A Visual Basic solution contains one or more related projects. A project contains files related to some topic. Usually, a... more
A Visual Basic solution contains one or more related projects. A project contains files related to some topic. Usually, a project produces some kind compiled output (such as an executable program, class library, control library, and so forth). The project includes all the files related to the output, including source code files, resource files, documentation files, and whatever other kinds of files you decide to add to it.
This chapter describes the basic structure of a Visual Basic project. It explains the functions of some of the most common files and tells how you can use them to manage your applications.
This chapter also explains the basic structure of source code files. It explains regions, namespaces, and modules. It also describes some simple typographic features provided by Visual Basic such as comments, line continuation, and line labels. These features do not execute programming commands themselves, but they are an important part of how you can structure your code.
Variables are among the most fundamental building blocks of a program. A variable is a program object that stores a value... more
Variables are among the most fundamental building blocks of a program. A variable is a program object that stores a value. The value can be a number, letter, string, date, structure containing other values, or an object representing both data and related actions.
When a variable contains a value, the program can manipulate it. It can perform arithmetic operations on numbers, string operations on strings (concatenation, calculating substrings, finding a target within a string), date operations (find the difference between two dates, add a time period to a date), and so forth.
Four factors determine a variable’s exact behavior:
Data type determines the kind of the data (integer, character, string, and so forth).
Scope defines the code that can access the variable. For example, if you declare a variable inside a For loop, only other code inside the For loop can use the variable. If you declare a variable at the top of a subroutine, all the code in the subroutine can use the variable.
For
Accessibility determines what code in other modules can access the variable. If you declare a variable at the module level (outside of any subroutine in the module) and you use the Private keyword, only the code in the module can use the variable. If you use the Public keyword, code in other modules can use the variable as well.
Private
Public
Lifetime determines how long the variable’s value is valid. A variable inside a subroutine that is declared with a normal Dim statement is created when the subroutine begins and is destroyed when it exits. If the subroutine runs again, it creates a new copy of the variable and its value is reset. If the variable is declared with the Static keyword, however, the same instance of the variable is used whenever the subroutine runs. That means the variable’s value is preserved between calls to the subroutine.
Dim
Static
For example, a variable declared within a subroutine has scope equal to the subroutine. Code outside of the subroutine cannot access the variable. If a variable is declared on a module level outside any subroutine, it has module scope. If it is declared with the Private keyword, it is accessible only to code within the module. If it is declared with the Public keyword, then it is also accessible to code outside of the module.
Visibility is a concept that combines scope, accessibility, and lifetime. It determines whether a certain piece of code can use a variable. If the variable is accessible to the code, the code is within the variable’s scope, and the variable is within its lifetime (has been created and not yet destroyed), the variable is visible to the code.
This chapter explains the syntax for declaring variables in Visual Basic. It explains how you can use different declarations to determine a variable’s data type, scope, accessibility, and lifetime. It discusses some of the issues you should consider when selecting a type of declaration. This chapter also describes some newer variable concepts such as anonymous and nullable types, which can complicate variable declarations.
Constants, parameters, and property procedures all have concepts of scope and data type that are similar to those of variables, so they are also describe here.
The chapter finishes with a brief explanation of naming conventions. Which naming rules you adopt isn’t as important as the fact that you adopt some. This chapter discusses where you can find the conventions used by Microsoft Consulting Services. From those, you can build your own coding conventions.
An operator is a basic code element that performs some operation on one or more values to create a result. The values the... more
An operator is a basic code element that performs some operation on one or more values to create a result. The values the operator acts upon are called operands. For example, in the following statement, the operator is + (addition), the operands are B and C, and the result is assigned to the variable A:
+
B
C
A
A = B + C
The Visual Basic operators fall into five categories: arithmetic, concatenation, comparison, logical, and bitwise. This chapter first explains these categories and the operators they contain, and then discusses other operator issues such as precedence, assignment operators, and operator overloading. Also included are discussions of some specialized issues that arise when you work with strings and dates.
Subroutines and functions enable you to break an otherwise unwieldy chunk of code into manageable pieces. They enable you... more
Subroutines and functions enable you to break an otherwise unwieldy chunk of code into manageable pieces. They enable you to extract code that you may need to use under more than one circumstance and place it in one location where you can call it as needed. This not only reduces repetition within your code; it also enables you to maintain and update the code in a single location.
A subroutine performs a task for the code that invokes it. A function performs a task and then returns some value. The value may be the result of a calculation, or a status code indicating whether the function succeeded or failed.
Together, subroutines and functions are sometimes called routines or procedures. They are also sometimes called methods, particularly when they are subroutines or functions belonging to a class. Subroutines are also occasionally called sub procedures.
This chapter describes subroutines and functions. It explains the syntax for declaring and using each in a Visual Basic application. It also provides some tips for making routines more maintainable.
Program control statements tell an application which other statements to execute under a particular set of circumstances.... more
Program control statements tell an application which other statements to execute under a particular set of circumstances. They control the path that execution takes through the code. They include commands that tell the program to execute some statements but not others and to execute certain statements repeatedly.
The two main categories of control statements are decision (or conditional) statements and looping statements. The following sections describe in detail the decision and looping statements provided by Visual Basic .NET.
Although it is theoretically possible to write a program that perfectly predicts every possible situation that it might encounter... more
Although it is theoretically possible to write a program that perfectly predicts every possible situation that it might encounter, in practice that’s very difficult for nontrivial programs. For large applications, it is very difficult to plan for every eventuality. Errors in the program’s design and implementation can introduce bugs that give unexpected results. Users and corrupted databases may give the application values that it doesn’t know how to manage.
Similarly, changing requirements over time may introduce data that the application was never intended to handle. The Y2K bug is a good example. When engineers wrote accounting, auto registration, financial, inventory, and other systems in the 1960s and 1970s, they didn’t think their programs would still be running in the year 2000. At the time, disk storage and memory were relatively expensive, so they stored years as 2-byte values (for example, 89 meant 1989). When the year 2000 rolled around, the applications couldn’t tell whether the value 01 meant the year 1901 or 2001. In one humorous case, an auto registration system started issuing horseless carriage license plates to new cars because it thought cars built in 00 must be antiques.
The Y2K problem wasn’t really a bug. It was a case of software used with data that wasn’t part of its original design.
This chapter explains different kinds of exceptional conditions that can arise in an application. These range from unplanned data (as in the Y2K problem) to bugs where the code is just plain wrong. With some advanced planning, you can build a robust application that can keep running gracefully, even when the unexpected happens.
The Windows Forms controls described in Chapter 8, “Selecting Windows Forms Controls,” allow the application and the user... more
The Windows Forms controls described in Chapter 8, “Selecting Windows Forms Controls,” allow the application and the user to communicate. They let the application display data to the user, and they let the user control the application.
Visual Basic’s database controls play roughly the same role between the application and a database. They move data from the database to the application, and they allow the application to send data back to the database.
Database programming is an enormous topic, and many books have been written that focus exclusively on database programming. This is such a huge field that no general Visual Basic book can adequately cover it in any real depth. However, database programming is also a very important topic, and every Visual Basic programmer should know at least something about using databases in applications.
This chapter explains how to build data sources and use drag-and-drop tasks to create simple table- and record-oriented displays. It also explains the most useful controls and objects that Visual Basic provides for working with databases. Although this is far from the end of the story, it will help you get started building basic database applications.
Note that the example programs described in this chapter refer to database locations as they are set up on my test computer. If you download them from the book’s web site (www.vb-helper.com/vb_prog_ref.htm), you will have to modify many of them to work with the database locations on your computer.
www.vb-helper.com/vb_prog_ref.htm
LINQ (Language Integrated Query) is a new data selection mechanism designed to give programs the ability to select data in... more
LINQ (Language Integrated Query) is a new data selection mechanism designed to give programs the ability to select data in the same way from any data source. Ideally the program would be able to use exactly the same method to fetch data whether it’s stored in arrays, lists, relational databases, XML data, Excel worksheets, or some other data store. Currently the LINQ API supports data stored in relational databases, objects within the program stored in arrays or lists, and XML data.
LINQ is a complex topic. LINQ provides dozens of extension methods that apply to all sorts of objects that hold data such as arrays, dictionaries, and lists. Visual Basic provides a LINQ query syntax that converts SQL-like queries into calls to LINQ functions.
LINQ tools are divided into the three categories summarized in the following list:
LINQ to Objects refers to LINQ functions that interact with Visual Basic objects such as arrays, dictionaries, and lists. Most of this chapter presents examples using these kinds of objects to demonstrate LINQ concepts.
LINQ to XML refers to LINQ features that read and write XML data. Using LINQ, you can easily move data between XML hierarchies and other Visual Basic objects.
LINQ to ADO.NET refers to LINQ features that let you write LINQ-style queries to extract data from relational databases.
The first section, “Introduction to LINQ,” provides an intuitive introduction to LINQ. Many of the details about LINQ functions are so complex and technical that they can be hard to understand, but the basic ideas are really quite simple. The introduction gives examples that demonstrate the essential concepts to try to give you an understanding of the basics.
The section, “Basic LINQ Query Syntax,” describes the most useful LINQ query commands. These let you perform complex queries that select, filter, and arrange data taken from program objects. The next section, “Advanced LINQ Query Syntax,” describes additional LINQ query commands.
The next section, “LINQ Functions,” describes functions that are provided by LINQ but that are not supported by Visual Basic’s LINQ query syntax. To use these functions, you must apply them to the arrays, dictionaries, lists, and other objects that they extend.
The next section, “LINQ Extension Methods,” explains how LINQ extends objects such as arrays, dictionaries, and lists. It describes method-based queries and explains how you can write your own extensions to increase the power of method-based queries.
Finally, after describing the tools provided by LINQ, the remainder of the chapter describes the three main categories of LINQ usage: LINQ to Objects, LINQ to XML, and LINQ to ADO.NET.
LINQ to Objects is a bit easier to cover effectively than LINQ to XML and LINQ to ADO.NET because it doesn’t require that you have any special knowledge beyond Visual Basic itself. To understand LINQ to XML properly, you need to understand XML, which is a complex topic in its own right. Similarly to get the most out of LINQ to ADO.NET, you need to understand relational databases such as SQL Server, a huge topic about which many books have been written.
Because LINQ to Objects is easiest to cover, this chapter focuses mostly on it, and most of the examples throughout the chapter deal with LINQ to Objects. The final sections of the chapter do provide some information about LINQ or XML and LINQ to ADO.NET, however, to give you an idea of what is possible in those arenas.
The book’s web site contains 20 example programs that demonstrate the techniques described in this chapter. Go to the book’s web site to download those examples.
LINQ is one of the newest features in Visual Basic so it is possible that its syntax and details will change in the next releases. In fact, they may even change between the time this chapter was written and the time you read it.
If changes are needed, I will post addendums and revised example programs on the book’s web site. To learn about any changes, visit the book’s web site. If you sign up for the VB Helper newsletters at www.vb-helper.com/newsletter.html, you’ll receive weekly tips and tricks, in addition to notification when this book’s web page changes.
www.vb-helper.com/newsletter.html
Visual Basic .NET provides a rich assortment of controls that you can use to build applications. Nevertheless, those controls... more
Visual Basic .NET provides a rich assortment of controls that you can use to build applications. Nevertheless, those controls may not always be able to do what you need. In that case, you may want to build a control of your own. Building your own control lets you get exactly the behavior and appearance that you want.
Custom controls solve three significant problems. First, they let you package a particular behavior or appearance so that you can easily reuse it later. If you need to draw one engineering diagram, you can draw it on a PictureBox. If you need to draw many engineering diagrams (possibly in different applications), it would be easier to make an EngineeringDiagram control that can make all of the diagrams.
EngineeringDiagram
Second, developers are familiar with controls and comfortable using them. Any experienced Visual Basic developer understands how to create instances of a control, set its properties, call its methods, and respond to its events. If you build a custom control to perform some complex task, developers already know a lot about how to use it. You just need to explain the specific features of your control.
Finally, controls can easily save and restore property information at design time. A developer can set properties for a control at design time, and the control uses those properties at runtime. This is useful for graphical controls, where properties such as Text, BackColor, and BorderStyle determine the controls’ appearance. It is also useful for non-graphical controls such as database connection, data adapter, DataSet, and DataView controls that use properties to determine what data is loaded and how it is arranged.
Text
BackColor
BorderStyle
DataSet
DataView
This chapter explains how to build custom controls. There are three main approaches to building custom controls. First, you can derive a control from an existing control. If a control already does most of what you want your custom control to do, you may be able to inherit from the existing control and avoid reimplementing all of its useful features.
The second way to build a custom control is to compose your control out of existing controls. For example, you might want to make a color selection control that enables the user to select red, green, and blue color components by using scroll bars, and then displays a sample of the resulting color. You could build this control using three scroll bars and a PictureBox. This gives you the advantages provided by the constituent controls without requiring you to reimplement their functionality.
Finally, you can build a custom control from scratch. This is the most work but gives you absolute control over everything that the control does.
This chapter explains the basics of building a control library project and testing its controls. It also describes the three approaches to building custom controls: deriving from an existing control, composing existing controls, and building a control from scratch.
A component is similar to a control that is invisible at runtime. Like controls, you can place components on a form at design time. Unlike controls, however, components do not sit on the form itself. Instead, they sit in the component tray below the form at design time, and they are invisible to the user at runtime. Most of this chapter’s discussion of custom controls applies equally to custom components.
The clipboard is an object where programs can save and restore data. A program can save data in multiple formats and retrieve... more
The clipboard is an object where programs can save and restore data. A program can save data in multiple formats and retrieve it later, or another program might retrieve the data. Windows, rather than Visual Basic, provides the clipboard, so it is available to every application running on the system, and any program can save or fetch data from the clipboard.
The clipboard can store remarkably complex data types. For example, an application can store a representation of a complete object in the clipboard for use by other applications that know how to use that kind of object.
Drag-and-drop support enables the user to drag information from one control to another. The controls may be in the same application or in different applications. For example, your program could let the user drag items from one list to another, or it could let the user drag files from Windows Explorer into a file list inside your program.
A drag occurs in three main steps. First, a drag source control starts the drag, usually when the user presses the mouse down on the control. The control starts the drag, indicating the data that it wants to drag and the type of drag operations it wants to perform (such as Copy, Link, or Move).
When the user drags over a control, that control is a possible drop target. The control examines the kind of data being dragged and the type of drag operation requested (such as Copy, Link, or Move). The drop target then decides whether it will allow the drop and what type of feedback it should give to the user. For example, if the user drags a picture over a label control, the label might refuse the drop and display a no drop icon (a circle with a line through it). If the user drags the picture over a PictureBox that the program is using to display images, it might display a drop link icon (a box with a curved arrow in it).
Finally, when the user releases the mouse, the current drop target receives the data and does whatever is appropriate. For example, if the drop target is a TextBox control and the data is a string, the TextBox control might display the string. If the same TextBox control receives a file name, it might read the file and display its contents.
The following sections describe drag-and-drop events in more detail and give several examples of common drag-and-drop tasks. The section “Using the Clipboard” near the end of the chapter explains how to use the clipboard. Using it is very similar to using drag and drop, although it doesn’t require as much user feedback, so it is considerably simpler.
The previous chapters have dealt with general Visual Basic programming tasks. They show how to write the Visual Basic code... more
The previous chapters have dealt with general Visual Basic programming tasks. They show how to write the Visual Basic code needed to build an application.
This chapter discusses User Account Control (UAC) security issues. UAC is a system implemented by the Windows Vista and Windows Server 2008 operating systems that allows programs to elevate their privileges only when they absolutely must.
In earlier operating systems that don’t have UAC, users often logged in with administrator privileges to perform fairly routine tasks because the programs they used might need administrator privileges. Now, with UAC, users can run with normal user privileges and only elevate their privileges to perform the specific tasks that need them.
This chapter explains the fundamental ideas behind object-oriented programming (OOP). It describes the three main features... more
This chapter explains the fundamental ideas behind object-oriented programming (OOP). It describes the three main features of OOP languages: encapsulation, inheritance, and polymorphism. It explains the benefits of these features and describes how you can take advantage of them in Visual Basic.
This chapter also describes method overloading. In a sense, overloading provides another form of polymorphism. It lets you create more than one definition of the same class method, and Visual Basic decides which version to use based on the parameters the program passes to the method.
Many of the ideas described in this chapter will be familiar to you from your experiences with forms, controls, and other building blocks of the Visual Basic language. Those building blocks are object-oriented constructs in their own rights, so they provide you with the benefits of encapsulation, inheritance, and polymorphism whether you knew about them or not.
A variable holds a single value. It may be a simple value such as an Integer or String, or a reference that points to a more... more
A variable holds a single value. It may be a simple value such as an Integer or String, or a reference that points to a more complex entity. Two kinds of more complex entities are classes and structures.
Classes and structures are both container types. They group several related data values into a convenient package that you can manipulate as a group.
For example, an EmployeeInfo structure might contain fields that hold information about an employee (such as first name, last name, employee ID, office number, extension, and so on). If you make an EmployeeInfo structure and fill it with the data for a particular employee, you can then move the structure around as a single unit instead of passing around a bunch of separate variables holding the first name, last name, and the rest.
EmployeeInfo
This chapter explains how to declare classes and structures, and how to create instances of them (instantiate them). It also explains the differences between classes and structures and provides some advice about which to use under different circumstances.
In large applications, it is fairly common to have name collisions. One developer might create an... more
In large applications, it is fairly common to have name collisions. One developer might create an Employee class, while another makes a function named Employee that returns the employee ID for a particular person’s name. Or two developers might build different Employee classes that have different properties and different purposes. When multiple items have the same name, this is called a namespace collision or namespace pollution.
Employee
These sorts of name conflicts are most common when programmers are not working closely together. For example, different developers working on the payroll and human resources systems might both define Employee classes with slightly different purposes.
Namespaces enable you to classify and distinguish among programming entities that have the same name. For example, you might build the payroll system in the Payroll namespace and the human resources system in the HumanResources namespace. Then, the two Employee classes would have fully qualified names Payroll.Employee and HumanResources.Employee, so they could coexist peacefully and the program could tell them apart.
Payroll.Employee
HumanResources.Employee
The following code shows how an application would declare these two types of Employee objects:
Dim payroll_emp As Payroll.Employee
Dim hr_emp As HumanResources.Employee
Namespaces can contain other namespaces, so you can build a hierarchical structure that groups different entities. You can divide the Payroll namespace into pieces to give developers working on that project some isolation from each other.
Namespaces can be confusing at first, but they are really fairly simple. They just break up the code into manageable pieces so that you can group parts of the program and tell different parts from each other.
This chapter describes namespaces. It explains how to use namespaces to categorize programming items and how to use them to select the right versions of items with the same name.
Visual Basic .NET includes a large assortment of pre-built classes that store and manage groups of objects. These collection... more
Visual Basic .NET includes a large assortment of pre-built classes that store and manage groups of objects. These collection classes provide a wide variety of different features, so the right class for a particular purpose depends on your application.
For example, an array is good for storing objects in a particular fixed order. An ArrayList enables you to add, remove, and rearrange its objects much more easily than an array does. A Queue lets a program easily add items and remove them in first in, first out order. In contrast, a Stack lets the program remove items in last in, first out order.
ArrayList
Queue
Stack
This chapter describes these different kinds of collection classes and provides tips for selecting the right one for various purposes.
Classes are often described as cookie cutters for creating objects. You define a class, and then you can use it to make any... more
Classes are often described as cookie cutters for creating objects. You define a class, and then you can use it to make any number of objects that are instances of the class.
Similarly, a generic is like a cookie cutter for creating classes. You define a generic, and then you can use it to create any number of classes that have similar features.
For example, Visual Basic comes with a generic List class. You can use it to make lists of strings, lists of integers, lists of Employee objects, or lists of just about anything else.
List
This chapter explains generics. It shows how you define generics of your own and how you can use them.
Visual Basic .NET provides a large assortment of objects for drawing and for controlling drawing attributes. The... more
Visual Basic .NET provides a large assortment of objects for drawing and for controlling drawing attributes. The Graphics object provides methods that enable you to draw and fill rectangles, ellipses, polygons, curves, lines, and other shapes. Pen and Brush objects determine the appearance of lines (solid, dashed, dotted) and filled areas (solid colors, hatched, filled with a color gradient).
Graphics
Pen
Brush
This chapter provides an overview of the drawing process and a survey of the most important drawing namespaces and their classes. It describes in detail the most central of these classes, the Graphics object, and provides examples showing how to use it. You can download example programs demonstrating most of the methods described in this chapter on the book’s web site. The examples also include code to draw the figures in this chapter.
Chapter 31, “Brushes, Pens, and Paths,” describes some of the other important drawing classes in greater detail.
If you are new to graphics, this chapter and those that follow may involve a lot of new concepts and unfamiliar terms. The examples available on the book’s web site will help make many of the concepts more concrete. If you find some terms confusing, you can find additional details by using the advanced Microsoft search page search.microsoft.com/search/search.aspx?st=a. The advanced Google search page www.google.com/advanced_search also returns excellent results and you can enter one of the Microsoft sites www.microsoft.com, msdn.microsoft.com, or support.microsoft.com in the Domain field if you like. You can also consult online glossaries such as the Webopedia (www.webopedia.com) and Wikipedia (www.wikipedia.org) for basic definitions.
search.microsoft.com/search/search.aspx?st=a
www.google.com/advanced_search
www.microsoft.com
msdn.microsoft.com
support.microsoft.com
www.webopedia.com
www.wikipedia.org
After Graphics, Pen and Brush are the two most important graphics classes. Whenever you perform any drawing operation that... more
After Graphics, Pen and Brush are the two most important graphics classes. Whenever you perform any drawing operation that does not manipulate an image’s pixels directly, you use a Pen or a Brush.
Pen classes control the appearance of lines. They determine a line’s color, thickness, dash style, and caps.
Brush classes control the appearance of filled areas. They can fill an area with solid colors, hatched colors, a tiled image, or different kinds of color gradients.
This chapter describes the Pen and Brush classes in detail. It shows how to use these classes to draw and fill all sorts of interesting shapes.
This chapter also describes the GraphicsPath class that represents a series of lines, shapes, curves, and text. You can fill a GraphicsPath using Pen and Brush classes.
GraphicsPath
You can download example programs demonstrating most of the methods described in this chapter on the book’s web site. The examples also include code to draw the figures in this chapter.
Text is different from the lines, rectangles, ellipses, and other kinds of shapes that a program typically draws. A program... more
Text is different from the lines, rectangles, ellipses, and other kinds of shapes that a program typically draws. A program normally draws and fills a rectangle in separate steps. On the other hand, a program typically draws text in a single step, usually with a solid color.
Text also differs in the way it is drawn by the GDI+ routines. To draw a line, rectangle, or ellipse, the program specifies the shape’s location, and the GDI+ routines draw it accordingly. Text is not specified by simple location data. A program can specify the text’s general location but has only limited control over its size. Different characters may have different widths in a particular font, so strings containing the same number of characters may have different sizes when displayed.
Even if you know every character’s nominal size, you may not be able to add them up to calculate the size of a string. Fonts sometimes use special algorithms that adjust the spacing between certain pairs of letters to make the result look better. For example, a font might decrease the spacing between the characters A and W when they appear next to each other (as in AW) to allow the W to lean over the A.
This chapter describes some of the tools that Visual Basic provides for controlling text. It explains how to draw text aligned and formatted in various ways, and how to measure text so that you can figure out more exactly where it will appear.
Note that several examples use the Graphics object’s TextRenderingHint property to make text appear smoother. For more information on this property, see the section “System.Drawing.Text” in Chapter 30, “Drawing Basics.”
TextRenderingHint
Note that Windows Vista uses a slightly different underlying graphics model than previous versions of Windows. In particular, Vista has made some changes to produce better-looking, smoother text. Microsoft has worked to make the Vista graphics system compatible with GDI+, but you might encounter some small differences or glitches. For some additional information about the underlying graphics system, see the article “Graphics APIs in Windows Vista” at msdn2.microsoft.com/library/bb173477.aspx.
msdn2.microsoft.com/library/bb173477.aspx
You can download example programs that demonstrate many of these features and that produce the figures in this chapter on the book’s web site.
The... more
The Graphics class represents a drawing surface at a logical level. Below that level, a Graphics object is attached to a Bitmap or Metafile object. Those objects understand the slightly lower-level needs of managing more physical data structures. For example, a Bitmap object maps abstract drawing commands such as DrawLine and DrawEllipse to colored pixels that can be displayed on a PictureBox or saved into a file. Similarly, a Metafile maps the Graphics object’s abstract commands into metafile records that you can play back on a drawing surface, or save in a graphical metafile.
Bitmap
Metafile
DrawLine
DrawEllipse
This chapter describes the more down-to-earth Bitmap and Metafile classes. It explains methods for building, modifying, and manipulating these objects. It shows how to load and save them from graphics files and, in the case of Bitmap classes, how to work with files saved in a variety of graphic formats such as BMP, GIF, JPEG, TIFF, and PNG.
Visual Basic .NET provides several good tools for printing. String formatting objects enable you to determine how text is... more
Visual Basic .NET provides several good tools for printing. String formatting objects enable you to determine how text is wrapped and truncated if it won’t fit in a printing area. Methods provided by Graphics objects enable you to easily scale, rotate, and translate drawing commands.
The basic process, however, seems somewhat backward to many programmers. Rather than issuing commands to a printer object, a program responds to requests to draw pages generated by a PrintDocument object. Instead of telling the printer what to do, the program responds to the PrintDocument object’s requests for data.
In some cases, generating a printout using only Visual Basic commands can be difficult. The following section explains alternative methods for generating a printout and tells when you might want to use those methods. If you just want to print several pages of text, it’s often easier to pull the text into Microsoft Word or some other application that specializes in formatting text rather than writing your own.
Another option used by many developers is to purchase a third-party printing application. Some of these tools help with certain kinds of printing such as report generation. Chapter 35, “Reporting,” provides an introduction to Crystal Reports, a report generation and printing tool that is available with some versions of Visual Basic and that you can purchase separately.
In some cases, however, you cannot take an easy way out. If the program generates very complex images and graphs, or produces text that is positioned and formatted in a complex manner, you probably need to work through the Visual Basic printing system. The rest of this chapter explains the techniques that you use to generate printouts in Visual Basic. It shows how to draw graphics and text on the printer and how to scale and center the results.
Visual Studio 2008 Professional Edition and the higher editions come with Crystal Reports for Visual Studio 2008. Crystal... more
Visual Studio 2008 Professional Edition and the higher editions come with Crystal Reports for Visual Studio 2008. Crystal Reports is a product that helps you build, display, and print reports in Visual Basic applications.
Crystal Reports is a large and complex application that provides a huge number of wizards, formats, charts, and other tools for building reports, so there isn’t enough room here to do it justice. This chapter provides a quick introduction to using Crystal Reports to build a few simple examples. For more detailed information about particular topics, consult the online help at msdn2.microsoft.com/en-us/library/aa287920(VS.71).aspx. The help includes several examples that show how to make reports with certain common formats.
msdn2.microsoft.com/en-us/library/aa287920(VS.71).aspx
You may also want to visit the web site of Business Objects (the makers of Crystal Reports) at www.businessobjects.com and their web page for Crystal Reports www.businessobjects.com/products/reporting/crystalreports/default.asp.
www.businessobjects.com
www.businessobjects.com/products/reporting/crystalreports/default.asp
For more in-depth information, read a book that covers only Crystal Reports. Quite a few books about Crystal Reports are available for developers with all levels of experience, including Professional Crystal Reports for Visual Studio .NET (Wiley Publishing, Inc., 2004).
A very simple application performs a well-defined task that changes minimally over time. You may not need to configure such... more
A very simple application performs a well-defined task that changes minimally over time. You may not need to configure such an application for different circumstances.
Many more complex applications, however, must be configured differently to meet different conditions. For example, the application might display different data for different kinds of users (such as data-entry clerks, supervisors, managers, and developers). Similarly, you might configure an application for various levels of support. You might have different configurations for trial, basic, professional, and enterprise versions.
The application may also need to save state information between sessions. It might remember the types of forms that were last running, their positions, and their contents. The next time the program runs, it can restore those forms so that the user can get back to work as quickly as possible.
Visual Studio provides many ways to store and use application configuration and resource information. This chapter describes some of these tools. It starts by describing the My namespace that was invented to make these tools easier to find. It then tells how an application can use environment variables, the Registry, configuration files, resource files, and the Application object.
Application
This chapter does not explain how to work with disk files more directly. Databases, XML files, text files, and other disk files are generally intended for storage of larger amounts of data, rather than simple configuration and resource information. Those topics are described more thoroughly in Chapters 20, “Database Controls and Objects,” and 29, “File-System Objects.”
At some very primitive level, all pieces of data are just piles of bytes. The computer doesn’t really store invoices, employee... more
At some very primitive level, all pieces of data are just piles of bytes. The computer doesn’t really store invoices, employee records, and recipes. At its most basic level, the computer stores bytes of data (or even bits, but the computer naturally groups them in bytes). It is only when a program interprets those bytes that they acquire a higher-level meaning that is valuable to the user.
Although you generally don’t want to treat high-level data as undifferentiated bytes, there are times when thinking of the data as bytes lets you treat it in more uniform ways.
One type of byte-like data is the stream, an ordered series of bytes. Files, data flowing across a network, messages moving through a queue, and even the memory in an array all fit this description.
Defining the abstract idea of a stream lets applications handle these different types of objects uniformly. If an encryption or serialization routine manipulates a generic stream of bytes, it doesn’t need to know whether the stream represents a file, a chunk of memory, plain text, encrypted text, or data flowing across a network.
Visual Studio provides several classes for manipulating different kinds of streams. It also provides higher-level classes for working with this kind of data at a more abstract level. For example, it provides classes for working with streams that happen to represent files and directories.
This chapter describes some of the classes you can use to manipulate streams. It explains lower-level classes that you may use only rarely and higher-level classes that let you read and write strings and files relatively easily.
The following table summarizes the most useful stream classes.
FileStream
MemoryStream
BinaryReader, BinaryWriter
StringReader, StringWriter
StreamReader, StreamWriter
Visual Basic includes a bewildering assortment of objects that you can use to manipulate drives, directories, and files.... more
Visual Basic includes a bewildering assortment of objects that you can use to manipulate drives, directories, and files. The stream classes described in Chapter 37 enable you to read and write files, but they don’t really capture any of the special structure of the file system.
A Visual Basic application has two main choices for working with the file system: Visual Basic methods and .NET Framework classes. This chapter describes these two approaches and the classes that they use. It finishes by describing some of the My namespace properties and methods that you can use to access file-system tools more easily. For more information on the My namespace, see the section “My” in Chapter 36, “Configuration and Resources,” and Appendix S, “The My Namespace.”
Programmers have long been able to have one program to call routines provided by another program that is running either on... more
Programmers have long been able to have one program to call routines provided by another program that is running either on the local computer or some other computer on the same network. The omnipresent Internet extended this capability to new and greater levels, allowing a client program to call service routines provided by a server that could be physically on the other side of the world.
New web technologies such as Simple Object Access Protocol (SOAP) made it easy enough to build web services for use by other programs over the Internet. This gave rise to a whole new type of application that implements a significant amount of its functionality by calling services. Because these programs focus on the use of services, this design is called service-oriented architecture (SOA).
Windows Communication Foundation (WCF) is a set of classes and tools in .NET Framework 3.0 that make it easier to build SOA applications. It includes attribute classes that let you easily mark pieces of a server application to publish services for use by clients. It also includes tools to automatically generate the Visual Basic code you need to use or consume the services.
WCF is quite large and very flexible. It gives you the ability to write secure, reliable services that support transactions and can use a variety of transport methods. For example, clients and services can communicate using HTTP or TCP network protocols, or named pipes or message queues on the local computer.
Because WCF is so flexible, there isn’t space to cover it all here. Instead, this chapter provides an overview of the main concepts behind WCF, and describes a simple example client and server implementation.
The .NET Framework is a library of classes, interfaces, and types that add extra power to Visual Studio .NET. These features... more
The .NET Framework is a library of classes, interfaces, and types that add extra power to Visual Studio .NET. These features go beyond what is normally provided by a programming language such as Visual Basic.
The .NET Framework is truly enormous. To make it more manageable, Microsoft has broken it into namespaces. The namespaces form a hierarchical catalog that groups related classes and functions in a meaningful way.
For example, the System namespace contains basic classes and methods that an application can use to perform common tasks. The System.Drawing namespace is the part of the System namespace that holds graphical tools. The System.Drawing.Design, System.Drawing.Drawing2D, System.Drawing.Imaging, System.Drawing.Printing, and System.Drawing.Text namespaces further subdivide System.Drawing into finer groupings.
Many of the .NET Framework namespaces are essential for day-to-day programming. For example, many Visual Basic applications need to produce printouts, so they use the System.Drawing.Printing namespace. Different applications draw graphics or images on the screen, so they need to use other System.Drawing namespaces.
Because so much of the .NET Framework is used in everyday programming tasks, this book doesn’t strongly differentiate between Visual Basic and .NET Framework functionality. Presumably, the book could have focused solely on the Visual Basic language and ignored the .NET Framework, but it would have been a much less useful book.
Although the book covers many useful .NET Framework features, there’s a huge amount that it doesn’t cover. Currently the .NET Framework includes more than 160 namespaces that define a huge number of classes, types, enumerated values, and other paraphernalia.
The following sections describe some of the highest-level and most useful namespaces provided by the .NET Framework.
A control interacts with a program or the user through properties, methods, and events. Although each type of control provides... more
A control interacts with a program or the user through properties, methods, and events. Although each type of control provides different features, they are all derived from the Control class. This class provides many useful properties, methods, and events that other controls inherit, if they don’t take special action to override them. The following sections describe some of the most useful of these inherited features.
You can learn more about the Control class at msdn2.microsoft.com/library/system.windows.forms.control.aspx.
msdn2.microsoft.com/library/system.windows.forms.control.aspx
This appendix provides information about variable declarations and data types.... more
This appendix provides information about variable declarations and data types.
The Visual Basic operators fall into five main categories: arithmetic, concatenation, comparison, logical, and bitwise. The... more
The Visual Basic operators fall into five main categories: arithmetic, concatenation, comparison, logical, and bitwise. The following sections explain these categories and the operators they contain. The end of this appendix describes special Date and TimeSpan operators, as well as operator overloading.
This appendix provides information about subroutine, function, and generic declarations. A property procedure includes a... more
This appendix provides information about subroutine, function, and generic declarations. A property procedure includes a subroutine and function pair, so they are also described here.
Control statements tell an application which other statements to execute under a particular set of circumstances. They control... more
Control statements tell an application which other statements to execute under a particular set of circumstances. They control the path that execution takes through the code. They include statements tha