INTRODUCTION

SO YOU WANT TO LEARN VISUAL BASIC PROGRAMMING? Excellent choice!

Visual Basic is a powerful, all-purpose programming language that enables you to build robust applications that run on the desktop or over the Web. Visual Basic provides all the tools that you need to build a huge variety of applications:

  • Database applications

  • Point of sales systems

  • Web applications

  • Two- and three-dimensional graphics programs

  • Image processing and photo manipulation systems

  • Computer-aided design (CAD) systems

  • Document layout and printing systems

  • Hardware control systems

  • High-performance games

  • Much, much more

Note

This book refers to Visual Basic using its full name only, but Visual Basic programmers often refer to the language as VB. You'll also often see it referred to as VB in discussions on the Internet.

Of course, there are some problems that you won't be able to solve even with Visual Basic. If you want a program that picks the winning number on a roulette wheel or that can predict stock prices, you may have better luck using tarot cards (or a degree in economics), but for tractable problems Visual Basic is a great choice.

This book is a self-paced guide to Visual Basic programming in the Visual Studio environment. It uses short, easy-to-follow lessons, reinforced by step-by-step instructions, screencasts, and supplemental exercises to help you master Visual Basic programming quickly and painlessly. It explains how to write Visual Basic programs that interact with the user to read inputs, calculate results, and display outputs. It shows how to read and write files, make printouts, and use databases.

This book won't make you an expert, but it will give you a solid understanding of how to write Visual Basic programs. When you've finished reading this book and working through the Try It sections, you'll be able to write nontrivial programs of your own. You may not be able to accurately pick winning lottery numbers (if you do, please let me know!), but you will be able to build some useful programs. And you'll be ready to learn more about specialized topics such as database programming, file processing, and graphics.

WHO THIS BOOK IS FOR

This book is for anyone who wants to learn how to write programs using Visual Basic. Whether you want to move into a lucrative career as a software developer, add a few new skills to your resume, or pick up a fascinating new hobby, this book can get you started.

This book does not assume you have any previous programming experience. It assumes you can turn your computer on and surf the Web, but that's about it for previous qualifications. It is suitable as a first programming book for high school or college students, but its self-paced, hands-on approach also makes it ideal if you're trying to learn to program on your own.

I say all this because I don't want to receive a bunch of flaming e-mails complaining that the material in this book is too basic. So I'm warning you right now: If you've been programming in C++ or C# for 16 years, don't blame me if a lot of this material seems pretty simple to you. Don't waste your time complaining; go find a more advanced book.

WHAT THIS BOOK COVERS (AND WHAT IT DOESN'T)

This book explains Visual Basic programming. It explains how to write, debug, and run desktop applications that interact with the user and the computer. It shows how to understand object-oriented concepts, perform calculations, manipulate files and strings, produce printouts, and interact with simple databases.

Programming in any language is an enormous topic, however, so this book doesn't cover everything. It doesn't explain how to design databases, build cryptographically secure web applications, create multithreaded programs that run on multiple cores or computers, or build massive networked games like World of Warcraft. All of those tasks are possible using Visual Basic, however, and after you finish this book you'll be ready to move on to more advanced books that cover those topics.

To make everything fit into a single book, I had to make some tough choices about what to include and what to omit. This book focuses on desktop applications because if you want to learn Visual Basic programming, then you probably have a computer that can run applications. It doesn't cover ASP.NET programming using Visual Basic — not because it's a bad thing to learn but because it's a less self-contained learning environment. Visual Studio will enable you to build ASP.NET web applications, but unless you have a web server that supports ASP.NET you won't be able to exercise the full power of ASP.NET.

Similarly, there are many ways to approach database programming. In this book, I've tried to give you a taste of database programming without being completely overwhelming. The book's lessons explain how to use objects to manipulate data in a database and how to use the Entity Framework to perform simple database queries. Database programming is an enormous topic, however, and no general programming book can hope to cover it in its entirety.

Still, while no introductory book can cover every programming topic, the topics this book does cover give you a good foundation of fundamental programming skills that you can use as a base for further study.

THE WROX 24-HOUR TRAINER APPROACH

Educators have known for many years that different people use different learning styles most effectively. Personally, I learn best by watching and doing. However, different students may learn best by:

  • Reading a textbook

  • Looking at nonwritten material such as pictures and graphs

  • Listening to an instructor lecture

  • Watching someone demonstrate techniques

  • Doing exercises and examples

Good instructors try to incorporate material that helps students with all of these learning styles. Combining text, lecture, demonstration, discussion, and exercises enables every student to pick up as much as possible using whichever methods work best.

Like a good instructor, this book uses materials that address each learning style. It uses text and figures to help visual learners, screencasts that provide visual demonstrations and auditory instruction, step-by-step instruction to help you do it yourself, and exercises for independent study.

The book is divided into small, bite-size lessons that begin with a discussion of a particular concept or technique, complete with figures, notes, tips, and other standard fare for instructional books. The lessons are short and tightly focused on a single task so you can finish each one in a single sitting. You shouldn't need to stop in the middle of a lesson and leave concepts half-learned (that is, if you turn off your phone).

After describing the main concept, the lesson includes a Try It section that invites you to perform a programming exercise to solidify the lesson's ideas.

The Try It begins with a high-level overview. It then contains several subsections:

  • Lesson Requirements describes the exercise so you know what should happen.

  • Hints provides pointers about how to solve the trickier parts of the problem.

  • Step-by-Step provides a numbered series of steps that show exactly how to solve the problem.

A screencast on the accompanying DVD shows me (the author) working through the Try It problem. Additional commentary at the end of the screencast highlights extensions of the lesson's main concepts.

After the Try It's Step-by-Step section, the lesson concludes with extra exercises that you can solve for further practice and to expand the lesson's main ideas. I recommend that you at least skim the exercises and ask yourself if you think you could do them. Solutions to all of the exercises are available for download on the book's web site.

The one thing that a good classroom experience offers that this book doesn't is direct interaction. You can't shout questions at the instructor, work as a team with fellow students, or discuss exercises with other students.

Nonetheless, there are at least three things you can do to get this kind of interaction. First, join the Wrox P2P (peer-to-peer) discussion forum for this book. As the section "p2p.wrox.com" later in this introduction indicates, you can join the discussion forum to post questions, provide answers, see what other readers are doing with the book's material, and generally keep tabs on book-related topics. I highly recommend that you join the discussion right away so you don't forget. (You can join other Visual Basic discussion groups on the Web, too, but this one is dedicated to this book and you know I'll be watching it closely.)

Second, you can browse or subscribe to my newsletters at www.vb-helper.com/newsletter.html to receive occasional newsletters describing new example programs, articles, and commentary. Many of the entries describe tips, tricks, and short example programs that demonstrate techniques you may find useful for your Visual Basic programs.

Finally, if you get stuck on an exercise or some other program you're working on, e-mail me at . I won't solve the exercises for you, but I'll try to clarify problems or give you any hints you need so you can solve them yourself.

HOW THIS BOOK IS STRUCTURED

This book is divided into six sections, each containing a series of short lessons. The lessons are generally arranged in order, with later lessons depending on earlier ones, so you should study the lessons more or less in order, at least until sections V and VI. The lessons in sections V and VI cover slightly more specialized topics and their order is less critical.

The following sections describe the book's contents in detail.

Section I: The Visual Studio IDE and Controls

The lessons in this section explain how to use the Visual Studio integrated development environment (IDE) and how to use the controls that make up a user interface. These form the foundation on which you build everything else in a Visual Basic program.

Lesson 1, "Getting Started with the Visual Studio IDE," explains Visual Studio. It describes some of the IDE's useful features and demonstrates how to build a simple program and run it. From the very first lesson, you'll be able to build a program!

Lesson 2, "Creating Controls," explains what controls are, what they are for, and how to use them. It shows how to add controls to a form to make a user interface. In Visual Basic programs, controls are critical for getting the job done.

Lesson 3, "Making Controls Arrange Themselves," explains how to use control properties to make controls automatically rearrange themselves at run time to take full advantage of the available space. When the user resizes a form, the controls can automatically move and resize as needed.

Lesson 4, "Handling Events," explains what events are. It shows how to catch events to respond to user actions so the user can interact with the program.

Lesson 5, "Making Menus," explains how to add main menus and context menus to an application, and how to respond when the user selects a menu item. By responding to menu events, the program gives the user an easy and well-understood way to control the application.

Lesson 6, "Making Tool Strips and Status Strips," explains how to build tool strips and status strips, and how to handle their events. Tool strips provide a faster method for the user to control the application than menus, while status strips provide useful feedback to let the user know what the program is doing.

Lesson 7, "Using RichTextBoxes," explains the RichTextBox control and shows how to manipulate it with code. The RichTextBox enables the user to enter text and, if the program provides the right tools, lets the user format the text with different fonts, colors, bullets, and other text decorations.

Lesson 8, "Using Standard Dialogs," explains how to use standard dialogs to display messages and questions, change fonts and colors, browse for folders, and let the user select files for opening and saving.

Lesson 9, "Creating and Displaying New Forms," explains how a program can display new instances of forms and interact with the controls on those forms. This is important for more complicated programs that cannot do everything they need to on a single form.

Lesson 10, "Building Custom Dialogs," explains how to use new forms as custom dialogs. It shows how to display a custom dialog and determine which button the user pressed to close it.

Section II: Variables and Calculations

The lessons in this section deal with variables and calculations. They explain how variables hold values and how a program can use them to calculate results. Whereas the lessons in Section I explain how to make controls that enable the user to enter information, the lessons in this section explain how to do something with that information.

Lesson 11, "Using Variables and Performing Calculations," explains how to declare and use variables and constants, and how to perform simple calculations. It also shows how to convert information from one data type to another. For example, it demonstrates how to take an age entered by the user and convert it from a textual value (for example, "47") into a numeric value (47). (It's a small distinction to a person but a huge one to a program.)

Lesson 12, "Debugging Code," explains techniques for finding and fixing bugs. It shows how to determine which line of code the program is executing, examine and modify variable values, and use watches to keep track of variable values. Almost every nontrivial program starts with a bug or two. This lesson shows how to find those bugs.

Lesson 13, "Understanding Scope," explains how scope restricts a variable's accessibility to certain pieces of code. It also explains why a programmer should restrict scope as much as possible.

Lesson 14, "Working with Strings," explains how to combine, manipulate, and format strings. It explains the String class's ToString and Format methods, which enable you to build nicely formatted strings to show the user.

Lesson 15, "Working with Dates and Times," explains how to use date and time values. It explains the Date and TimeSpan classes, and shows how to use and format them.

Lesson 16, "Using Arrays and Collections," explains single- and multi-dimensional arrays and collection classes such as List and Stack. It explains how to declare and initialize arrays and collections.

Lesson 17, "Using Enumerations and Structures," explains how to define and use customized data types such as structures and enumerations. These help make the code easier to understand, debug, and maintain.

Section III: Program Statements

The lessons in the previous sections explain how to write code that flows through a series of steps, one at a time in a predefined order. The lessons in this section explain how to make code follow more complex paths. They explain how code can choose between one path and another and repeat operations. While controls and message boxes are more visible pieces of an application, these statements let the program do most of its work.

Lesson 18, "Making Choices," explains how programmers can control the flow of code with If, Select Case, nested If, and cascading If statements. These statements let the program take different actions depending on the situation.

Lesson 19, "Repeating Program Steps," explains looping code that uses statements such as For, For Each, Do, and While. It explains how to use these statements to iterate through a series of integer values, arrays, and lists, and how to break out of loops.

Lesson 20, "Reusing Code with Procedures," explains how a programmer can write procedures and why procedures are important. It explains the syntax of declaring subroutines and functions, defining return values, and using parameters passed by value or by reference.

Lesson 21, "Handling Errors," explains how to use Try blocks to handle unexpected errors. It also explains how to raise errors to tell other parts of the program that something has gone wrong.

Lesson 22, "Preventing Bugs," explains bug proofing techniques that make it easier to detect and correct bugs. It explains how to use Assert statements to validate inputs and results so you can catch bugs quickly, rather than let them remain hidden in the code.

Section IV: Classes

Structures, enumerations, and procedures are all programming abstractions that let you think about pieces of the program at a higher level. For example, when you call the CalculateInterest procedure, you don't need to know how it works, just that it does.

The ultimate programming abstraction is the class. A class lets you think about data and functions packaged as a single unit. For example, a Customer class might include data (name, employee ID, office number) together with functions (ScheduleWork, PrintPaycheck).

The lessons in this section deal with classes. They explain how to create and use classes and how to use more advanced class features such as generics and operator overloading.

Lesson 23, "Defining Classes and Their Properties," explains how to define classes. It explains the main benefits of classes and how to build simple properties to hold data for classes.

Lesson 24, "Defining Class Methods and Events," explains how to add methods and events to a class. Methods enable the program to make an object perform some action, and events enable an object to tell the program that something interesting has happened.

Lesson 25, "Using Inheritance and Polymorphism," explains two of the most important and confusing aspects of classes: inheritance and polymorphism. It explains how you can make one class inherit from another to reuse code and how you can make an object of one class behave as if it were from another class.

Lesson 26, "Initializing Objects," explains constructors, destructors, and initializers, and shows how to use them to make creating objects easier.

Lesson 27, "Fine-Tuning Classes," explains how you can overload and override class methods. These techniques enable you to make classes more flexible and easier to use.

Lesson 28, "Overloading Operators," explains operator overloading. This technique enables you to define the behavior of operators such as +, *, and % for objects other than numbers.

Lesson 29, "Using Interfaces," explains what a class interface is and how to build one. Just as a program's user interface defines features that a program shows to the user, a class interface defines features that a class shows to the program's code.

Lesson 30, "Making Generic Classes," explains how to build new generic classes. Lesson 16 shows how to use generic collection classes such as List to work with specific kinds of data. This lesson explains how you can build your own generic classes and methods.

Section V: System Interactions

Earlier lessons explain how to enable a program to interact with the user. The lessons in this section explain methods a program can use to interact with the operating system and other programs.

Lesson 31, "Reading and Writing Files," explains how a program can read and write files. It explains how to use streams to manipulate the text in a file all at once or in pieces — for example, one line at a time.

Lesson 32, "Using File System Classes," explains ways in which a program can use classes to find, examine, and manipulate directories and files. It describes file-handling classes such as DriveInfo, DirectoryInfo, Directory, and FileInfo.

Lesson 33, "Printing," explains how to create printouts and print previews. It describes how to draw simple shapes and text on one or more pages sent to the printer.

Lesson 34, "Using the Clipboard," explains how to move text, images, and other data in and out of the clipboard. Using the clipboard in this way is somewhat crude, but it's simple and flexible, enabling your program to interact with many others without understanding anything about how those other applications work.

Lesson 35, "Providing Drag and Drop," explains how a program can use drag-and-drop to interact with other programs. It explains how to start a drag, provide "drag over" feedback, and handle a drop. Like the clipboard, drag and drop enables your program to interact with others without knowing how the other programs work.

Section VI: Specialized Topics

The lessons presented in the earlier sections cover topics that are generally useful for a large variety of programs. Whether you are writing a sales tax calculator, an invoice tracking system, or a word guessing game, techniques such as handling events, debugging code, using If statements, and printing will be useful to you.

This section introduces topics that are more specialized, so you might not need them in every program you write. For example, localizing your application for different locales is important for some applications but not for every program you write.

Each of the lessons in this section provides a sense of what its topic is about, and offers enough detail to get started, but a lesson cannot cover its topic in complete detail due to the topic's length and complexity.

Lesson 36, "Using the My Namespace," explains the My namespace, which makes using certain .NET features easier. This namespace provides shortcuts for performing common tasks such as reading and writing entire files; saving and restoring program settings; and checking the network's status.

Lesson 37, "Localizing Programs," explains how to make programs that can run in multiple cultures. It shows how to use different text and images for different locales and discusses some of the other issues an international application must address.

Lesson 38, "Manipulating Data with LINQ to Objects," explains how you can use Language-Integrated Query (LINQ) to filter and extract values from collections and other enumerable lists into new ones. This enables you to perform database-like queries on data stored in program objects instead of in an actual database.

Lesson 39, "Manipulating Databases with the Entity Framework," explains how you can use the Entity Framework (EF) to manipulate database entities as if they were objects inside the program. It enables your program to treat records in tables as if they were instances of classes and enables your program to fetch, modify, and save records while treating them as objects.

Appendices

This book's appendices summarize useful information for handy reference.

Appendix A, "Glossary," explains common programming terms that you may encounter while studying Visual Basic programming.

Appendix B, "Control Summary," summarizes each of the standard controls provided by Visual Basic. You can use it to help select the right control for your needs.

Appendix C, "What's on the DVD?," goes into more detail about using the DVD that comes with the book.

WHAT YOU NEED TO USE THIS BOOK

To get the most out of this book, you need to install Visual Studio 2010 and Visual Basic.

You don't need any fancy version of Visual Studio or Visual Basic Professional Edition. In fact, the Professional Edition, Team System Development Edition, and Team System Team Suite versions don't really add all that much that you're likely to want when you're just getting started. Mostly they add support for performing unit tests, managing test cases, profiling code, building code libraries, and performing other tasks that are more useful for programming teams than they are for individuals, particularly beginners. In short, to work through this book, the Express Editions (which are free) are good enough.

The following list describes some links that you may find useful for learning about and installing different Visual Studio products:

  • Visual Basic Developer Center (msdn.microsoft.com/vbasic): This page contains links to Visual Basic information such as downloads, "getting started" articles, and other resources.

  • Visual Studio Developer Center (msdn.microsoft.com/vstudio): This page contains links to Visual Studio information such as downloads, "How Do I" videos, and other resources.

  • Visual Studio Express Edition home page (www.microsoft.com/express/Windows): This page contains information about Express Editions of Visual Studio products such as Visual Basic, Visual C#, Visual C++, and Visual Web Developer.

Note

Sometimes Microsoft moves their links around, so the URLs listed here may not work by the time you read this. In that case, just go to Microsoft's web site msdn.microsoft.com and search for the location you want, such as "Visual Studio Express Edition home page."

At a minimum, visit the Visual Studio Express Edition home page (www.microsoft.com/express/Windows) and download and install Visual Basic Express Edition. You should also occasionally check the Visual Basic home page for service packs and extra tools that may be available.

Running any version of Visual Studio will require that you have a reasonably fast, modern computer with a large hard disk and lots of memory. For example, I'm fairly happy running my Intel Core 2 system at 1.83 GHz with 2GB of memory and a huge 500GB hard drive. That's a lot more disk space than necessary but disk space is relatively cheap, so why not buy a lot?

You can run Visual Studio on much less powerful systems but using an underpowered computer can be extremely slow and frustrating. Visual Studio has a big memory footprint, so if you're having performance problems, installing more memory may help.

Of course, buying a superfast, quad-core desktop system with 6GB of RAM and 1TB of disk space will give you outstanding performance, but it will add dramatically to the $0 you're spending on Visual Basic Express Edition.

CONVENTIONS

To help you get the most from the text and keep track of what's happening, several conventions are used throughout the book.

Warning

Boxes with a warning icon like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.

Note

The pencil icon indicates notes, tips, hints, tricks, and asides to the current discussion. They are offset and placed in italics like this.

Note

References such as this one tell you when to look at the DVD for screencasts related to the discussion.

As for styles in the text:

  • New terms and important words are italicized when they are introduced. You can also find many of them in the glossary in Appendix A.

  • Keyboard strokes look like this: [Ctrl]+A. This one means to hold down the [Ctrl] key and then press the A key.

  • URLs, code, and e-mail addresses within the text are shown in monofont type, such as www.vb-helper.com, x = 10, and .

    I use a monofont type with no highlighting for most code examples.
    
    I use bold to emphasize code that's particularly important in the present context.

The Code Editor in Visual Studio provides a rich color scheme to indicate various parts of code syntax such as variables, comments, and Visual Basic keywords. That's an excellent tool to help you learn language features in the editor and to help prevent mistakes as you code. However, the colors don't show up in the code in this book.

SOURCE CODE

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. (I like to type in code when I work through a book because it helps me focus on it line by line so I get a better understanding.)

Many of the examples in the book show only the code that is relevant to the current topic and may be missing some of the extra details that you need to make the example work properly. To fill in the missing pieces, you may need to write your own code or download the book's code.

All of the source code used in this book is available for download on the book's web sites. As I indicated earlier in this introduction, either go to the Wrox web site (www.wrox.com) and search for the book or visit my web page for the book at www.vb-helper.com/24hourvb.html. Any updates to the code will be posted in both of these places.

Note

At the Wrox web site, because many books have similar titles, you may find it easiest to search by ISBN. This book's ISBN is 978-0-470-94335-9.

ERRATA

The Wrox editors and I make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or a faulty piece of code, we would be very grateful for your feedback. By sending in errata you may save another reader hours of frustration, and at the same time you will be helping us provide even higher quality information.

To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that have been submitted for this book and posted by Wrox editors. A complete book list, including links to each book's errata, is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don't spot "your" error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We'll check the information and, if appropriate, post a message to the book's errata page and fix the problem in subsequent editions of the book.

P2P.WROX.COM

For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based system for you to post messages relating to Wrox books and related technologies, and to interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At p2p.wrox.com you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

  1. Go to p2p.wrox.com and click the Register link.

  2. Read the terms of use and click Agree.

  3. Complete the required information to join as well as any optional information you wish to provide and click Submit.

  4. You will receive an e-mail with information describing how to verify your account and complete the joining process.

Note

You can read messages in the forums without joining P2P but in order to post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to This Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

E-MAIL ME

If you have questions, comments, or suggestions, please feel free to e-mail me at .

E-MAIL ME
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset