You are on page 1of 37

Visual Basic .

NET 2008 Express - A "From the Ground Up" Tutorial


Part 1 of an About Visual Basic Tutorial
By Dan Mabbutt, About.com Aug 10 2008 What's this course all about? Microsoft has made it as easy as they can for you to learn Visual Basic .NET by giving away a really great development system absolutely free: Visual Basic .NET 2008 Express Edition. (The download link is below.) This is lesson 1 of a introduction using VB.NET Express. In this lesson, you learn what it is, how to get it, and how to get started by writing a program. This is a free tutorial to help beginning programmers get up to speed. No textbook is required and downloadable example programs help you learn. All you have to do is download Visual Basic Express from Microsoft and start learning. This course is also a living document. I plan to update it and extend it frequently to keep it current and add more content. (In fact, I'm updating from VB.NET 2005 to VB.NET 2008 right now. You might see "2005" in some of the later lessons. I'll get to them as soon as I can. In the meantime, be assured that not too much has changed.) If you have any suggestions about something that should be changed or added, let me know about it. The current contents of the tutorial are as follows: Part 1 - A "From the Ground Up" Tutorial - An introduction to the course. Part 2 - Visual Basic Fundamentals - The basics of the VB Language and How To Find More Information Part 3 - About Programming - Software systems and the Systems Development Life Cycle. Part 4 - What's New With Visual Basic .NET Express - Special emphasis on what's new and improved. Part 5 - The .NET Framework and Objects - How the Framework and Objects fit into VB Express Part 6 - Objects in Detail - Objects in software and version 1 of the Signature Block program 1

Part 7 - Using Data and Serializing to Files - Intro to ADO.NET, and Using Serialization in Version 2 of the Signature Block program Part 8 - Using XML - Introduces the use of XML in VB.NET Part 9 - Programming Logic and System Architecture - Systems: From the CPU Chip to Networks Part 10 - Collections of Things - How to use Arrays, Collections, Stacks and Queues Part 11 - Errors: Preventing and Handling Them - Built-In Error Prevention and Structured Error Handling We'll take it slow in Lesson 1, but we will write a program in this lesson. The first program is probably the most basic program that it's possible to write. I'll describe every step and highlight technical terms in bold. Since we're just getting started, I don't want to leave anybody behind. Don't worry. In later lessons, the pace will pick up quite a bit. The really good news is that Visual Basic .NET 2008 Express Edition is a great learning tool for beginners. It's based on exactly the same Framework 3.5 that the (much, much) more expensive versions are. (If you're into version numbering, this is version 9.0 of Visual Basic.) The following illustration shows the difference in the "new project" dialogs.

-------Click Here to display the illustration Click the Back button on your browser to return -------I do a lot of development using VB Express and I can give you my personal assurance that it's a first class development system with many of the features of the one that Microsoft sells for thousands of US dollars. My advice is, take advantage of Microsoft and use VB.NET 2008 Express. Buy the more expensive versions only when you absolutely have to. (About Visual Basic is totally independent of Microsoft and as far as I'm concerned, Bill has enough money.) As a beginners course in programming, we will be marching through a selection of the fundamentals. We'll cover how to write a program, the basics of language syntax and structure, and how to use the version of Visual Studio .NET that Visual Basic Express

uses. About Visual Basic features more advanced articles on the site but this course will make a special effort not to leave beginners and students behind. Where did Visual Basic come from? Visual Basic was invented by Microsoft, but it's based on a much earlier language called BASIC invented by Dartmouth College professors John G. Kemeny and Thomas E. Kurtz in 1964. Since C was invented almost ten years later, BASIC is one of the earliest computer languages. Every version of BASIC has been a revolutionary event in the history of programming from the very beginning. In fact, the version of BASIC created by Microsoft founders Bill Gates and Paul Allen in February 1975 has an excellent claim to being the very first PC language since the first version was written in the native machine language for the what many consider to be the first PC, the MITS Altair 8800. Since the first PC version was written directly in machine language, nothing came before it! The first version of Visual Basic came out in May of 1991. It was revolutionary because it gave people the ability to create Windows programs easily and quickly for the first time. Before Visual Basic, Windows programs were usually written using the complicated syntax of C++ and the even more complicated requirements of Windows. It was a tricky job for even the most experienced programmers. But Visual Basic opened Windows programming for everyone. That made it a key part of the amazing early success of Windows. People who didn't live through this era often don't understand that IBM and OS/2 had nearly all the money, most of the customers, and they made the computers. They had it all! Microsoft was a tiny, insignificant upstart by comparison. The programming universe was literally turned upside down when Windows and Visual Basic became the most successful software system in the world. I did live through it and as I write these words, it's even hard for me to believe just how amazing that time was. But Microsoft has never been a company that let history happen to them. They have always made their own history. In February 2002, Microsoft made a 300 billion dollar bet on a totally new technology base for their entire company. They called it .NET. Bill Gates, who usually says what he means, called .NET a "bet the company" move. If .NET had flopped, it probably would have been all over for Microsoft. On the next page, we zero in on .NET and VB.NET 2008 Express Edition! Visual Basic has always been a flagship language for Microsoft and this didn't change when .NET came out. Visual Basic remained a featured language for Microsoft development in the new .NET world although two new languages, J# and C# - .NET substitutes for Java and C++ - were announced at the same time. There is also a .NET version of C++, but it's there mainly because a lot of companies put a lot of investment into early Windows software development in C++. It's just too much

money to walk away from and it would be too difficult to recode all of it. There was a lot of pressure for Microsoft to provide a .NET version. It's too bad that VB 6 programmers didn't have this much clout with Microsoft! Because the .NET Framework does most of the work, Visual Basic, and every other .NET language, is just the skin on top of .NET. Once you learn .NET ... switching to another language syntax is a lot easier. The really important things don't change. There are getting to be quite a few .NET languages available now! Microsoft lists all these at their site:

COBOL for Microsoft .NET. Perl for Microsoft .NET. Eiffel for Microsoft .NET. Python for Microsoft .NET. Pascal for Microsoft .NET. Mercury for Microsoft .NET. Mondrian for Microsoft .NET. Oberon for Microsoft .NET. Salford FTN95 (Fortran) for Microsoft .NET. SmallTalk for Microsoft .NET. Standard ML for Microsoft .NET. Dyalog APL for Microsoft .NET.

Visual Studio .NET versus Visual Basic Express Visual Studio is not a part of the .NET Framework. It's an application that uses the .NET Framework. As amazing as Visual Studio is (and it's pretty amazing), it's not actually necessary to use Visual Studio (or VB Express) to write a VB.NET program. There are several other ways. One way is to use the free, downloadable .NET SDK and write the VB code with a plain text editor (like Notepad) and the Command Line .NET compiler, VBC.EXE. It's not easy to create a VB.NET program that way, but it's possible. And, in fact, it's a good way to make sure you really understand .NET. And there are other ways to develop Visual Basic .NET programs too! For example ... SharpDevelop It's not that difficult to write a very simple "Hello World" program and compile it using VBC. But anything more complex is a lot harder. That's what another non-Microsoft effort, SharpDevelop is all about. SharpDevelop is an open-source replacement for Visual Studio .NET.

In my opinion, we owe the good folks at SharpDevelop a debt of gratitude because they are probably one of the reasons why we can download Visual Basic .NET 2008 Express for free. But although SharpDevelop is good, VB.NET Express is better. Just a personal opinion of course. One thing that should be clear is that Visual Basic .NET 2008 Express and Visual Studio 2008 are not the same, but .NET Framework 3.5 is the same for both of them. There are some interesting consequences because of this. 1. The code you create with VB Express and Visual Studio are completely equal. After they're compiled to executable code, they are the same. 2. The limitations you accept with the free VB Express are not limitations in what the language can do, they're just limitations in how easy it is to do it. Visual Studio is just a graphical front for the .NET Framework that generates the commands and parameter files to do what you need to do. The difference in the various versions is just the features of the front end. I've said it before. "The only reason for choosing one .NET language over others is that you can code faster and create more understandable code. For me, that's Visual Basic." Framework 3.5 has some interesting new components:

Windows Workflow Foundation (WF)

Write code that describes a whole process, like an assembly line.

Windows Communication Foundation (WCF)

The buzzword here is "connected systems". We used to call them "networks" but Microsoft has much more ambitious goals in mind.

Windows Presentation Foundation (WPF)

Microsoft describes WPF (unfortunately using 'marketing language' instead of English) as "a unified programming model for building rich Windows smart client user experiences that incorporate UI, media, and documents." What the heck does that mean? For one thing, it means that a WPF application can be deployed on the desktop or hosted in a web browser. Microsoft wants to unify application services like 2D and 3D drawing, vector and raster graphics, typography and even audio and video. Microsoft Silverlight is a web-based subset of WPF. It's an ambitious goal!

VB.NET 2008 Express actually includes two new templates focusing directly on this new technology. These technologies go way beyond the scope of this introduction course, but be aware that they're available when you need them. There's another reason why this is the right time to learn VB.NET ... It's called the "Version 2.0 Rule". Learn about it on the next page. Programmers have learned to rely on the "version 2.0" rule over the years. The rule states that you should generally depend on version 2.0 of any really new product because it will take that long to work the bugs out. Besides, version 1.0 might totally flop and you don't want to be left holding the bag. This is a great rule for VB.NET Express. It's actually based on version 3.5 of the .NET Framework. Released in November 2007, it completely replaces previous versions. (In fact, you have to "convert" earlier versions of VB.NET to run with Framework 3.5 now.) Visual Basic .NET 2008 Express Edition is well past version 1.0. One "bug" that Microsoft has worked out with the .NET Framework and VB.NET Express is how to combine the opposite goals of moving "upscale" to the professional business development world and still stay affordable for students, beginning programmers, and even hobby programmers. Business success for Microsoft demands that they offer products with the performance, sophistication, and of course the huge prices in the corporate world. When I was a corporate software development manager in the old mainframe world, it was fairly easy to justify and purchase software for the mainframe in the price range of $100,000 or so (In current dollars.) But that one copy might be used by about a hundred programmers. These are the prices that Microsoft wants to charge their most affluent corporate customers. See, for example, Paul Kimmel's excellent analysis, of Visual Studio 2005: So Many Choices, So Much Marketing, So Little Time. Paul points out that a new copy of the most expensive edition of Visual Studio 2005 - Visual Studio Team Edition - will set you back nearly $11,000!!. Whoh!! You and I certainly can't afford those prices. (I buy my own software too. I'm one of you!) Microsoft knows that if they want to continue to be as successful as they have been, they must have a version of VB.NET for the rest of us because the people who can't even afford a compiler today will be making those high-dollar purchasing decisions tomorrow. The result has been the "Express" editions. (This list gets out of date quickly. Consult the link I gave you earlier for the latest information.)

SQL Server 2005 Express Edition Visual Web Developer 2008 Express Edition

and, of course ...

Visual Basic 2008 Express Edition!

Visual Basic Express is Microsoft's free, downloadable version of Visual Basic designed to get us all hooked on the product. As far as I'm concerned, it worked like a charm. I'm hooked. Be aware, however, that you do have to register with Microsoft and obtain their Windows Live ID to do any of this stuff. Why should I learn VB.NET Express? If you want to learn programming, start with Visual Basic 2008 Express! Visual Basic's clear structure and readable language syntax has made it the most successful programming environment ever, period. Until 2002, Visual Basic 6 was the flagship language and millions of programmers created world class systems using it. But the "really cool" C++ programmers still threw rocks at it because (they claimed) it wasn't "true" object oriented programming (OOP). My response (at the time) was that "object oriented" wasn't a standard, it was a philosophy and VB6 was the best compromise between programming complexity (which C++ had plenty of) and the benefits of OOP. There were very few things that VB6 couldn't do, especially if you simply used a few Windows API calls in your code. In other words, VB6 was "OOP enough" to get the most work done in the least time. It was practical and it worked! When .NET was introduced, everything changed. Even C++ programmers couldn't claim that .NET wasn't completely OOP by anyone's definition. OOP is so important to VB.NET that this tutorial covers it again in more detail in parts 5 and 6. (For the true purist, the only OOP feature C++ has that .NET doesn't have is called "multiple inheritance". Microsoft left it out because it creates more problems than it solves. It's a great example of how anything can go too far.) Visual Basic Express has almost all of the tricks that the high priced products do. And you can download more free stuff including:

Coding 4 Fun! (And other plug in code.)

Microsoft has traditionally included applications designed to show off the new features of their technology. (Who can forget NorthWind Traders? I thought they were a real store.) In the previous VB.NET 2005, Microsoft put them right there in the template menu along side the standard templates. This time, you have to download them after you install VB.NET 2008 Express.

As a general statement, Microsoft is moving away from the hard core, "Here's how to write the code to get it done." and moving toward, "Just plug this into your application and, 'presto chango', it works!" A leading category of sample apps designed just for the Express editions is identified with the new marketing phrase, Coding 4 Fun. It even has its own acronym, C4F. C4F currently includes the C4F Developers Kit and the C4F Vista P2P Kit. Some other examples that you can download today:

Popfly

A set of online visual tools on their own web site designed just for people starting to learn programming. Technically, you don't have to download anything to use it, but there is a Popfly Space plug-in that lets you download and modify code.

Facebook Dev Kit

A cooperative effort between Facebook and Microsoft that lets you write VB.NET code to customize your Facebook account. The next page shows you how to install and get ready to use Visual Basic Express! Visual Basic Express is the main requirement for this course and you can get it free from Microsoft. Here's how to do it: Go to ... http://www.microsoft.com/express/download/default.aspx ... and click Download. Note the hardware and software requirements. They're not kidding. This is heavy duty software and you have to be equipped to run it. Keep in mind that you're running exactly the same Framework 3.5 that the expensive versions of Visual Studio use. Thanks to Francis Lotuaco for suggesting that I include the link for the hardware requirements (as well as a lot of other information that you might want to browse through) right here where it's convenient. To view the VB.NET 2008 Express "ReadMe" file, click here. Also note that you really do have to completely uninstall any Beta versions before downloading and installing Visual Basic Express. Failure to uninstall the beta versions before installing the final version was a horrible problem back when Visual Basic Express was first introduced ... and it's very tough to solve. I had the most success

installing with nothing else running. This install does seem to be sensitive to other applications running during the install. Writing your first VB.NET Express program For decades, programmers have used the program "Hello World" to launch a new language and I certainly want to uphold tradition. This is literally true! The tradition dates back to 1978 when Dennis Ritchie and Brian Kernighan published the landmark book, "The C Programming Language". The Hello World program even has it's own entry in Wikipedia. As Wikipedia notes, "A 'hello world' program can be a useful sanity test to make sure that a language's compiler, development environment, and runtime environment are correctly installed." "Hello World" is simply a program that displays the phrase on a convenient output device. So, here's how to create "Hello World" using Visual Basic Express. Start Visual Basic Express and select New Project from the File menu (or press Ctrl-N). Make sure the Windows Application template is selected. Change the name to HelloWorld (If you use the default name WindowsApplication1, you won't be able to remember what it is because all your projects will have a similar generic name!) --------

10

Click Here to display the illustration Click the Back button on your browser to return -------Visual Basic Express will create a complete starter Windows program, ready for you to add your code and objects. The initial screen looks like this:

-------Click Here to display the illustration Click the Back button on your browser to return -------Notice that the default name Form1 has also been used for your startup form. It's a good idea to rename all of your project controls before you do anything else. Visual Basic will create a lot of your system automatically. If you don't provide your own names, you'll have default names that you won't understand when you start programming. The form name should be changed in two places. The File Properties for the Form1.vb file are shown in the illustration above so we'll change that first. We'll discuss properties, controls and everything else in the next lessons. For now, just remember that every object can have unique values associated with it and these values

11

are called properties. The first step in updating the properties for an object is to make sure that object is the one Visual Basic is currently referencing (this is called, "having the focus"). I changed the file name of the form to HelloForm.vb. To change the form name, first click the form in the design window to display the properties window for the form. Now change the name of the form. (I used the name HelloWorld again.) And while you're at it, you might want to scroll down in the properties and change the Text property too. Notice that when you change the Text property, the form display in the design window is automatically updated with the new name. Here's an illustration after all of these properties have been changed. --------

Now we're going to add two new controls to the form. Controls can be found in the Toolbox. The Toolbox is a good example of an Auto Hide window; a window that will automatically display when you move your mouse over the tab for it. You can pin an Auto Hide window in position by clicking the icon as shown in the illustration below.

12

The two controls that will be added are the Button and the Label. A circle is drawn around them in the illustration. --------

Click Here to display the illustration Click the Back button on your browser to return -------To add the control to the form, just click and drag it to where you want it on the form. You can also double click the control and it will be added in the upper left corner of the form. After the controls have been added, you can resize the controls and change their properties. Add one Button and one Label to the form. Change the names and position them where you want them. (I used "DisplayHello" for the Button and "HelloWorldLabel" for the Label.) Finally, change the Text property for the Button (I used "Display Hello".) and delete the Text property for the Label. You might notice that the Label might seem to disappear entirely from the display of the form when you delete the Text property. To find it again, click the down arrow in the control list at the top of the Properties window. The illustration below shows all of this detail.

13

Click Here to display the illustration Click the Back button on your browser to return -------The last thing we need to do is add the code that will display "Hello World!" in the HelloWorldLabel control when we click the DisplayHello Button. To enter code, we use a different window called the code window. The easiest way to display the code window, and get Visual Basic to give you a running start, is to double click the control that you want to use to perform some action. This displays a default event subroutine for that control with some of the code already added for you by Visual Basic Express. Notice that a Class and a Subroutine have been created for you and that they have the names that you gave to the Form and the Button. In addition the DisplayHello Button Name property has been combined with the Click event using an underscore character. This means that when the DisplayHello Button is clicked, the code you put in this subroutine will be executed. (Technically, the procedure named in the Handles clause at the end of the statement is executed. They will usually be the same, however.) I entered the code: HelloWorldLabel.Text = "Hello World!" Properties (and methods, which we'll also learn about later) for controls are identified by the dot operator. The Name of a control is connected to a method or a property with a dot. So the Text property of the HelloWorldLabel control is assigned the value "Hello World!" when the DisplayHello Button is clicked. Here's the completed program:

14

Click Here to display the illustration Click the Back button on your browser to return -------Now let's try out the program and see if it works. To run the program, click the Start Debugging icon in the Visual Basic Express toolbar. The previous illustration shows that too. The form with our two controls is displayed (the Label doesn't show until there is something in the Text property). Click the DisplayHello Button and the Text is displayed. I also changed the Font property of the Label to make it show up a little better.

15

Click Here to display the illustration Click the Back button on your browser to return -------If you've used VB 6 or previous versions, this will look very familiar to you, but trust me, there are some big differences that we'll discuss in later lessons. The goal of this lesson has been to get a working copy of Visual Basic Express on your computer and make sure that even people who haven't written a single line of programming code before could write a program. In future lessons, I won't go through the steps in this much detail. I'll assume that you know how to use Visual Basic and how to change properties and enter programming code. In future lessons, I'll also provide downloads for the programs that we create, but since the point of this program was to make sure everyone could enter and run a program themselves, I haven't done that this time. So if you have any doubts at all about what you're doing, try changing the Hello World program to do something else.

Change the Label Font property to match my example or to see what something else looks like. Add a Textbox to the form and add code that will transfer text in the TextBox to the Label. Change the title on the form instead of putting the text in a Label.

In part 2 of the tutorial, Visual Basic Fundamentals, we cover two topics that you need to get started. The first is where to find more information. Online learning is different from reading a book because you literally have millions of pages of information available to you at the click of a mouse. So it doesn't make sense to cover all of the fundamentals here. But it does make sense to give you a foundation to work from so the second topic is

16

the Visual Basic syntax and basic structures. This section of the tutorial covers the basics that you need to know to write a program without going into the details that you can and should get directly from Microsoft anyway.

Visual Basic .NET 2008 Express - Visual Basic Fundamentals


Part 2 of an About Visual Basic Tutorial
By Dan Mabbutt, About.com

See More About:


visual basic 2005 express learning to program how to get technical help visual basic fundamentals

Sponsored Links

Become a Java ProgrammerLearn methods, classes, objects and advanced concepts.www.pennfosterglobal.com Online AccountingCheck Out Online Accounting Solutions From A Trusted Source.www.ewossus.com Visual Basic TutorialTrusted Visual Basic Tutorial Answers From Users. Its Free! myLotAnswers.com Visual Basic Ads Visual Basic 6 0 VB Controls VB Course VB 6.0 VB Source Code Feb 14 2008 This is a free tutorial to help beginning programmers get up to speed using Microsoft Visual Basic 2008 Express. To get the most from this tutorial, you might want to start at the beginning: Part 1 - A "From the Ground Up" Tutorial - An introduction to the course. The Reality of Online Learning The basics that you need to code in Visual Basic .NET are explained in this segment of the About Visual Basic VB Express tutorial. This doesn't cover all of the language in

17

detail because you can get that at Microsoft's site and in the Help for VB Express. What it does is show you where you can get information and briefly explain the basic structure of the VB.NET language. The emphasis is on explaining the concepts in VB.NET rather than the specific language rules. (Programming language rules are usually called syntax.) The reality of online learning is that the best way to get help and instruction is from a variety of sources ... usually in parallel. So, if you want to learn VB Express, I think my tutorial is a great way to do it. But I expect that you will also try other web pages and maybe a book or two while you're reading my tutorial. And there is no way that I can duplicate the thousands of pages of documentation about VB.NET that you can find online, so I don't even try. What I do is explain things in a way that I think is better than Microsoft and even better than the other pages you can find. I use examples you can understand and I don't try to impress you with the biggest words I know. And I do tell you about those other sources of information. Where To Go For More Help The first stop for detailed syntax help is MSDN - the Microsoft Developers Network. This can be confusing because Microsoft uses the name MSDN for a lot of things. It's the name of a magazine and a way of buying their software on a subscription basis. But it's also the name of their web site for help with detailed questions about language syntax and rules and it's a better source for that kind of information than any other source I know. The home page for the MSDN web site is: MSDN.Microsoft.com but starting at the top and browsing is time-consuming and not an efficient way to get what you need. The best way is searching. And here's a tip: Never search for "VB". Always spell it out: Visual Basic. Microsoft doesn't use the shorthand VB on their site (there must be a rule against it) so you just won't find anything. Microsoft works hard at trying to provide developer resources. Here are just a few:

MSDN KnowledgeBase Forum Questions CodeZone Channel 9 Blogs

KnowledgeBase is a structured library of problems and solutions written by Microsoft engineers. If your question is actually more of a bug, KnowledgeBase is where to find the answer. If you see a reference to a code that starts with the letters "KB" (like, for example, "kb327433"), then it's a knowledgebase document that describes some specific

18

issue. You see these referenced in a lot of other places too. You can enter that number directly into a Microsoft search and go right to the article. The only problem with Knowledgebase (and it's actually a problem across all of Microsoft) is that the documents look like they were written by engineers. And some of them look like they were edited by a team of lawyers too. (That's where my page comes in. I write in your language!) Forum Questions can be a good source of information, but I would try that only if other sources don't work. It's a volunteer operation and it looks like it. Some of the volunteers are very smart and capable ... and some aren't. A lot of questions simply go unanswered. So you can burn through quite a bit of time just reading useless comments. But there's a better way to do this too. See below. CodeZone is a "developer community" sponsored by Microsoft. The problem with CodeZone is that it looks like a "sponsored site". This article lays out the problem. Again, there's a better way. MSDN Blogs is one of the newer ways that Microsoft is trying to "capture" developer input. But it's primarily written by Microsoft employees. The thing that is right about it is that the information is usually pretty "cutting edge" because there seems to be a competition for who can write about the most advanced topics. The thing that is wrong about it is that it's just not organized. Channel 9 In the "readme.txt" link, they write, "Channel 9 is all about the conversation. ... Channel 9 is not a marketing tool, not a PR tool, not a lead generation tool." When they say that, "It's not about the money!" then you know one thing for certain: It's about the money. On the next page, we look at the "better way" to find information. Using Google search. For most of my research, however, I still use Google. (Sorry Microsoft!) I feel like I'm giving away my best secret here, but the way to find what you need at MSDN is to use the "Site" keyword with Google. Say you want to know about "reflection" in VB.NET. Enter this key into a Google search: reflection Visual Basic site:microsoft.com This will restrict your search to only the domain name "microsoft.com". The end result is to target your search in a way that is similar to using the internal search on a web site. This trick works on my site too. reflection Visual Basic site:visualbasic.about.com

19

There are 19 hits at VisualBasic.About.Com! Google is also better, in my opinion, for searching groups, partly because Google searches all the newsgroups and partly because there is a more usable interface when you do find something you want to read or respond to. Again - Sorry Microsoft! A short detour into an "official" Microsoft source of information that doesn't work is useful here too. At the top of that list is the search embedded into the Visual Studio Help system. You get approximately the same results as going direct using your browser but it's not as fast and the interface isn't as convenient. And, finally, since the next topic in this lesson is a fast, compact discussion of Visual Basic language, keep in mind that you can find the most complete reference for Visual Basic syntax rules by using the search at Google with the search term, "Language Reference": language reference Visual Basic site:microsoft.com You'll find it handy since this tutorial will only cover the very highest of the high points. In fact, I cover them on the next page! A Visual Basic program consists of a series of statements and there are really only three kinds:

Declaration Statements

We'll take a more detailed look at these next.

Assignment Statements

This is just making one thing equal to another: myVariable = myOtherVariable + aFileVariable Visual Basic also supports assignment operators such as *= and &=. This simply combines an assignment with a operation. The operator &= is the same as a = a & b.

Executable Statements

This can be something like starting a programming loop: For i = 1 To 10 more statements Next Or calling a method somewhere else in the program:

20

DoThisInterestingMethod(myVariable, myOtherVariable) Methods will be covered extensively when we discuss Object Oriented Programming again. Variables, Constants, and Arrays All programs need data to work with. Data is stored in variables and constants while a program is working on it. A variable is just a name attached to part of computer memory that you can change. A constant is a name attached to computer memory, but it's protected from being changed. You use the Dim statement, or one of several others that control where the variable will have meaning in the program (called the Scope of the variable - Public, Private, Protected, Friend, or Protected Friend). Here's a variable declaration. Dim MyVarName As String One of the big differences between languages is the types of data that are supported. For example, whole numbers such as 1, 2, 3, -8759 and 14589729 are called integers and nearly all languages will support some form of integer. But not all languages will store them in computer memory the same way or support all possible integers. An integer in Visual Basic 6 is will occupy 16 bits (the smallest unit of data, a 1 or a 0) of memory equivalent to 2 bytes of memory - and can only store numbers in the range from -32,768 through 32,767. In all Visual Basic .NET languages, including VBE, a integer will occupy 32 bits of memory - 4 bytes - and can store numbers from -2,147,483,648 through 2,147,483,647. In addition, there are at least three kinds of integers in .NET (short, integer, and long) and more if you start counting things like the Byte data type that can technically store an integer as well. VB Express gives you a broad range of data types that you can use in your program to store not only numbers, but characters (ordinary text), dates, true or false (Boolean) or floating point numbers. (A floating point number uses a base, like 1.23 where the number of digits is the same, and then multiplies this base by a power of ten - for example 10, 100, 1000, or .001 - to get larger or smaller values. The net effect is that the decimal point can "float" forward or backward.) There is also an Object data type that you can store anything in and a User-Defined data type. (This is actually a Structure.) There is only one datatype worth mentioning that VB.NET does not support and that's one that was quite well known in VB 6 and a few earlier versions: the Variant data type. Earlier versions of Visual Basic made it easy to just start using a variable without bothering to decide what type of variable it was. This was one of the "features" of VB6 that made it unpopular with a lot of professional programmers. It turns out that this carefree way of coding can result in some nasty bugs and will also make the code run slower. In VB.NET, you can use the Object data type in a similar way but it's strongly discouraged (Object is provided for an entirely different reason) and performance is even worse.

21

You can also create a name for a whole Array of data with a single name using a declaration like this: Dim myArray(10) As String This declaration lets you store 11 (not 10, the array starts with 0) character strings (A character string is just text like, "My dog is named Spot.") and reference them by their place in the array (like myArray(4) to use the 5th one). There are lots of other more advanced ways to deal with data, such as enumerations, collections, and structures. Check MSDN for the specific details about declaring variables and constants. The key thing to remember right now is that you should declare a meaningful name for every piece of information that you will use in your program. The main thing that a statement will contain is an operation that "does something" with information (that is, data). So we discuss operations on the next page. After you declare a name for a piece of data, the next thing is usually to do some operation with the data. An example of an operation is one half of an assignment operation that we have already seen (see "assignment statement" above). Microsoft classifies all Visual Basic operators as

Arithmetic Operators

- Arithmetic operations include the familiar "+", "*", and "/" but also including interesting variations such as the modulus (Mod) and integer division "\" and a nice collection of operations that get down to single bits (1's and 0's), the bitwise And, Or, and bit shift (">>" and "<<"). One key concept to remember is that Visual Basic will apply these operators in a specific sequence if you don't add parenthesis to group things. The statement ... i=4+6*7 ... results in a value of 46 in the variable i. But ... i = (4 + 6) * 7 ... results in a value of 70 in i.

Comparison Operators

- The purpose of a comparison is to produce a Boolean true or false value that can be used somewhere else in your program, usually in something like an If block or a program loop.

22

There are six comparison operators:


= (Equality) <> (Inequality) < (Less than) > (Greater than) <= (Less than or equal to) >= (Greater than or equal to)

It's worth knowing that the Boolean value that is a result of a comparison operation is just True or False. It's not a simple number like it used to be in VB6. Microsoft has this to say about the Boolean data type: When numeric data types are converted to Boolean values, 0 becomes False and all other values become True. When Boolean values are converted to numeric types, False becomes 0 and True becomes -1. Some old VB6 programs use the values 0 and -1 instead of True and False. Never do that in VB.NET. Microsoft puts the logical operators, And, Or, AndAlso, OrElse, Xor and the Not operator in their own category because they only operate on Boolean variables. If you ever get confused about how these work, I recommend that you try diagramming them using what is called a Truth Table or Karnaugh Map.

Concatenation Operators

Just two operators, "+" and "&", which both do almost the same thing: join two strings into one. "+" is also an arithmetic operator so if you only want to concatenate strings, use "&". On the next page, we use Boolean variables to write the conditional statements that are really the only way that computers have any flexibilty to do more than one thing. On a previous page, the Boolean datatype was explained. A Boolean variable contains either "True" or "False". The various conditional expressions, like = (Equality) and <> (Inequality) result in a Boolean value that is part of a conditional statement. The conditional statements that you will see include:

Branching statements such as If statements Looping statements such as For ... Next or While blocks Selection blocks using a Select Case statement

You can code If statements on one line:

23

If Beauty = Truth Then ReadBook(Keats) Else PlayVideoGame() As a block: If Beauty = Truth Then ReadBook(Keats) Else PlayVideoGame() End If And you can use the ElseIf statement to include other conditions: If Beauty = Truth Then ReadBook(Keats) ElseIf MentalAge = PhysicalAge / 2 Then PlayVideoGame() End If A nested If looks like this: If Beauty = Truth Then If War = Peace Then If Up = Down Then ... other statements If you have a lot of nested If statements in your program or if the nesting is many levels deep, you might need to rethink your program design. This is often a sign that your program could be coded in a way that is a simpler and easier to understand. Looping Statements Code loops when you want to repeat essentially the same code. You might do this to count something. (How many branch offices have transmitted their daily report?) Or you might code a loop to repeat an operation. (Send a reminder to branch offices until all daily reports are received.) These examples demonstrates the two major types of loops. For ... Next loops repeat a block of code a specific number of times. Do While/Until loops repeat until some variable condition is met. One other thing to keep in mind is that you can test a condition before or after the statements inside the loop: Do While Beauty = Truth ... other statements Loop

24

Or: Do ... other statements Loop While Beauty = Truth When you choose the second type, the statements inside the loop will always be executed at least one time. An alternative syntax is to code While ... End While. Select Case The third way that conditional expressions are used is in Selection blocks using the Select Case statement. We'll see a programming example in the next part to select the right language label in a multi-language "Hello World" program. A Select Case block can be logically the same thing as an If block that includes ElseIf statements, so it's up to you which one you use. In the updated Signature block program, I decided to use Select Case. Since this is a course in programming as well as Visual Basic Express, the next segment of the tutorial -About Programming -- discusses the craft of programming. One of the mistakes that beginners often make is to assume that the whole job is just writing code. There's a lot more to it than that. We'll get back to the detailed job of programming in Visual Basic after we learn something about what programming is. This is a free tutorial to help beginning programmers get up to speed using Microsoft Visual Basic 2008 Express. To get the most from this tutorial, you might want to start at the beginning: Part 1 - A "From the Ground Up" Tutorial - An introduction to the course. Part 2 - Visual Basic Fundamentals - The basics of the VB Language and How To Find More Information

About Programming Although this is a tutorial on programming in Visual Basic .NET, I believe that it's important for beginners and students to understand "the big picture" - that is, how software systems are created in the real world. Most of Part 3 introduces the Systems Development Life Cycle. Multi-million dollar software projects use these same concepts, but in the real world, they're much more elaborate and sophisticated.

25

If your goal is to become a professional developer, then a thorough knowledge of systems development is essential and this lesson is just a start. But even if you only plan to put your recipe file on a computer, it's helpful to understand the purpose and scope of development tools in the real world. Although the full scope of systems development methodology only applies to large scale projects, you can start out right by applying a few basic concepts. The example program in the last part of the lesson, for example, is designed to introduce the ideas explained in the "programming" phase of a project. The Systems Development Life Cycle It's amazing how many programmers seem to think that programming is just "writing code". Imagine a customer who wants a system that will keep a constantly updated comparison of widget production for different widget manufacturing specifications? A lot of programmers say, "Sure! I'll sit down and start writing the code to do that immediately!" A week later, some programmers might ask, "What's a widget?" The real question is, "If you didn't know what a widget was, what did you spend all last week doing?" (It's worse that many managers think that writing code is all there is to the job too. I've heard this described as the "Why isn't anybody coding?" syndrome. Here's an example of the problem. The Vice President wanders through the programming shop between golf dates and doesn't see anybody actually writing any program code. Instead, they're drawing diagrams and writing use cases. At the next project review, the big question from the VP is, "Why isn't anybody coding?") Some consultants will tell you that in a well run software development project, actually writing the program code should take less time and effort than any other phase of the project. These consultants say that if you have really analyzed and designed the system correctly, writing the code will be almost automatic and the testing and implementation will take much less time too for a big net savings overall. The idea is often expressed, "measure twice, cut once." I've been the project manager of a multi-million dollar software project. I've also seen too much time used up on analysis and design. But I will say that if you don't have a very clear idea about what the program you're trying to write is supposed to do, you're wasting your time. And as a programmer, I've had a lot of my time wasted by customers who didn't know what they wanted. In the programming industry, this whole topic can become very controversial and complicated with many competing "methodologies" for doing the various steps involved in creating a software system. For our purposes, simply understand that, in general, software development is normally done in steps and the steps for a whole project are usually called the System Development Life Cycle. It's such a tradition in software development that the acronym SDLC is often used instead.

26

The most common SDLC steps are: System Request Some person or group has to be "the owner" of the new system. Analysis A description of what the new system will do must be completed. Design This step creates a detailed plan to build the new system. Programming The coding step. This is the one most people understand. Acceptance Testing The "owner" of the system "signs off" and agrees that the system does what it should do. Implementation The system is placed into production. Maintenance Nothing works forever. Times change and so do software systems. On the next page, we go through the steps in detail. System Request, Analysis, and Design System Request Some person or group has to be "the owner" of the new system. This should be an absolute requirement for every project. The reason is that somebody has to be able to say, "Yes, it's finished. I'll take it." People who are not in the software biz might be amazed to discover how often a system doesn't have an "owner" - or has lots of competing "owners". The old saying, "success has many fathers, but failure is an orphan" accounts for much of the reason why. Sometimes, the software development department just wants to build systems that nobody really wants built. (And that is a guarantee of disaster if there ever was one.) One of the first jobs that the "owner" of the system has to do in most organizations is to convince whoever supplies money for building systems that this system can be done and that it should be done. This is often called a "feasibility study". Guru Dan Clark (An Introduction to Object-Oriented Programming with Visual Basic .NET - Apress) calls it a "Software Requirement Specification" and gives it an acronym: SRS.

27

After somebody does this horrible job, they're usually "on board" to help get the system done to the bitter end. Management usually holds the "owner" of a system equally responsible for success or failure of the development project. In my experience, having the solid support from somebody who really, really wants the system built is the most important factor in whether project succeeds or fails. It's more important than picking the right technology. It's more important than having a lot of funding. And it's even more important than the skill of the programmers. If there is somebody out there that you can drown your sorrows with when things don't go well, or celebrate with when they do, you are much more likely to finish the project. Analysis A description of what the new system will do must be completed. Design This step creates a detailed plan to build the new system. These two steps often go together and they're often repeated more than once before the design is "right". The end result is a description of what the new system will do and a detailed plan of the rest of the steps to build the new system. The analysis and design phases of a project are the deadly tar pit of systems development. Many, many systems have died a horrible death in "analysis paralysis". The reason this happens is that it's incredibily difficult to decide when enough has actually been done especially in a big project. For one thing, the requirements often keep changing. The systems development people sometimes come to the conclusion that the "owner" never understood the problem in the first place. And the "owner" strikes back by saying that the developers don't listen and they're the ones who don't understand. In some cases, a requirements statement can never be completed because the owner and developers start to distrust each other. The lack of communication just keep going around and around and around until the money runs out and top management finally kills the project. Often, it's a mercy killing. This horror story, which is repeated more often than people realize, is a very big reason why "the owner" must be totally committed to completing the project before it ever starts. Only then can the compromises and hard work of ironing out the requirements in a difficult project be successful. Because this phase is so critically important to get right, most large companies employ specialists just for this part of the job. A technology called UML, the Unified Modeling Language is a traditional technology for getting the job done. Although Microsoft has been a big supporter of UML in the past, their enthusiasm for it hasn't been the same since IBM bought the leading UML company, Rational Software. Marie Huwe, general manager for Microsoft's Developer and Platform Evangelism Division was quoted as

28

saying, "We're designing for ease of use, and we didn't think UML was the way to go." Funny, they used to think that UML was the way to go. Especially for large systems development, companies often use another technology that goes by the acronym CASE - Computer Aided Systems Engineering. The basic idea is that requirements and specifications are captured in computer files. Then software can check the specifications for consistency, completeness, and in some cases, even automatically generate the program code. When you create a design for your program, keep it simple. Remember the golden rule: having a detailed design should make the programming easier, not harder. So here's a four step beginner's guide to software design. 1. Write down a description of what the system or program is supposed to do. A few paragraphs ought to do it. If you can't describe what the program will do, how will you know when you're finished? 2. List all the inputs and outputs of the program. A form, for example, can be both an input and an output. Examples of form input might be a text box, radio buttons, or even a random number that the computer creates. Examples of output might be as simple as another text box or as complex as commands sent to a rocket guidance system. 3. Describe what happens to the inputs until all the functions of the program have been described and all the outputs created. Again, when you're just starting out, a text description will do just fine. The goal is to be sure that you understand it. If you can't describe it, then you probably don't understand it. And ... perhaps most important of all 4. Keep your design up to date. As you learn about the program requirements, you'll change your mind about the design. That's good. Nobody thinks of the one, best way to do something the first time around. But just because the requirements change, never go back to bad, "no design" habits. Rules one through three worked the first time and should be followed again whenever you need to create a new design. On the next page, we finally get to the heart of the matter: writing the code! Programming The coding step. This is the one most people understand.

29

While you work on the design, you should look for functions that can be placed into their own code procedures. Look for things that seem like they are a black box. That's a function that can be completely described using only information about what goes in and what comes out. In other words, how the function does it is a "black box" and the only thing you care about is providing the input and getting the result. Knowing how to recognize these is a golden skill in analysis. An example of a black box might be a tax calculation in an accounting system. Note that the government defines the calculation and they can and do change it a lot. Also note that a system might use exactly the same calculation in a lot of different places. But since you only care about passing amounts into the calculation and getting the right result back, it's a black box. If a large system needs a tax calculation in fifty places and the government passes a new law, would you like to change the program in fifty places or just one? If you've done everything perfectly up to this point in the project, this is where it starts to really pay off. In an ideal project, the designers can simply hand the specifications to talented programmers and the new system will roll out like a train down a track. But the real world is seldom like that. This does point to one big reason why companies are willing to pay a lot for very good analysis and design. There's a lot of incentive these days to have the programming done by teams of developers that might not even be in your part of the world. Programming shops in Asia, South America and other parts of the world have specialized in building systems based on design specifications and they're good at it. Depending on where you are in the world, you might have different opinions about whether this is a good or bad thing, but the fact is that it's a growing trend and regardless of where you are, you should know and understand it. If you have created your design documents correctly, you can program the system using a technique sometimes called top down structured programming. This name has become out of fashion today, but I believe that today's hot ideas, such as Extreme Programming, are just old wine in new bottles. OOP, or Object Oriented Programming, is a logical extension of these fundamental ideas. The basic idea is to code the "top" parts of the system - the overall interface and control functions first. The smaller "black box" objects are represented by program "stubs" that don't actually do anything. To use the earlier example of a tax calculation, a "stub" might just return a random value no matter what was passed to it. In this way, you can code and test the "top" functions first and perhaps even find problems in the overall design earlier when they can be fixed a lot more easily. The "bottom" functions then become the "objects" in your Object Oriented system. Another reason for doing it this way is that as you code the "top" you often find more parts of the code that can be pushed down into objects. And that's a good thing!

30

Implementation The system is placed into production. Maintenance Nothing works forever. Times change and so do software systems. The real challenges of implementation are usually not technical. They usually have more to do with helping people understand and feel comfortable with the new system. The two things that will help you most here are first, that hero who got the system going in the first place: the system "owner" and second, great documentation. Great documentation doesn't have to be printed. Sometimes it's online tutorials or automated help systems. The most important thing to remember in implementation is, "Know your customer!" It doesn't matter how good your system really is. If your customer thinks it stinks, then it stinks. Your customer really is right. Really! Maintenance is often left completely out of discussions about systems development and, quite frankly, that burns me up. In my view, software development has long had a totally unjustified view of maintenance programming as a place where you can stick junior programmers or ... ahem ... people with "lower skill levels". I was a supervisor of maintenance programming before I became a new development project manager and I learned that maintenance is where the entire software development function lives or dies in most organizations. The people who fix it when it's broke are the ones who eventually understand a system best. They're the most reliable and knowledgeable even when it comes time to replace the system with a new one. They're the ones that you have to depend on when tons of money are being lost for every second the system is down. And they often have to do their magic after being pulled out of bed at 3 in the morning. In fact, the main reason new development sometimes has more prestige is that they get to play with all the new toys and they often get the biggest share of training. The world just ain't fair sometimes. If I could wave a magic wand and change just one thing about the way programming is done, it would be to put maintenance programmers at the very top of the salary and prestige heap in programming shops. But enough of talking about it. On the next page, we write code that takes the first step toward Object Oriented programming. It's time to write more programming code! As promised earlier, the instructions for this example program are at a little higher level this time. I won't explain every detail to keep the instructions a little shorter.

31

The example this time will be a Hello World program like Part 1, but this time, it will be coded as a subroutine (something we will see a lot of in future lessons) in a separate module. This is the first step in creating real objects. One of the main ideas in system development methodology is to "divide and conquer" - that is, divide programs into objects and conquer complexity. The more usual name is OOP - Object Oriented Programming. The code we will create in this lesson still falls short of being an actual object. We'll discuss why in later lessons. We will also use quite a few new VB.NET language elements. There will be more about them in later lessons. The idea in this program is try out software development methodology, become more familiar with coding a VB.NET Express program, and get a peek at things to come. But first, let's make sure we keep our code in sync with the SDLC, starting with the System Request! System Request "Create a program that can display Hello World in English, Spanish, or German." Notice that no technical jargon is used in the request. I didn't say "using OOP" for example. The System Request should be stated as simply as possible and still be fairly precise. In this case, you are the "System Owner" and the developer too. That's not a good combination in the real world, but this is a tutorial! Analysis As an example, I've created a very simple Use Case diagram for our program. Use Case is capitalized because it's a specific part of UML. UML doesn't have to be complex or confusing and I hope this diagram gives you a little insight into how it works. This particular diagram was created with Microsoft Visio 2003 which has extensive support for UML.

Click Here to display the illustration Click the Back button on your browser to return --------

32

Design Again, I've used Visio to create a very simple UML State Diagram for the program. The vertical boxes are called Swim Lanes in UML.

Click Here to display the illustration Click the Back button on your browser to return -------Programming Because this is a course in programming, this is where we get serious. Open the "Hello World" program from Part 1. We'll use this as a starting point for our new version. Because we're object oriented programmers, we're going to create a new module for the part of the system that actually displays the message in different languages. So the first step is to add a new module to the project (right-click the project in Solution Explorer and select Add, then Module ...). Remember that it's a good idea to rename objects as soon as they're created (I called it "HelloModule"). A "Module" is just another file to

33

hold VB code. Breaking up your system into logical components is the first step in making it OOP. The previous page showed a very simple Use Case diagram for our program. The main form, "HelloWorld.VB" and the module "HelloModule.vb" are just the two logical parts of our program. You can see them in Solution Explorer as shown below:

Click Here to display the illustration Click the Back button on your browser to return -------Click inside the module and type the statement: Sub SayHello(ByVal HelloLanguage As String) When you press the "Enter" key, something called Intellisense will add the End Sub statement automatically. This is a feature of VB.NET Express and Visual Studio that suggests coding for you to speed development and prevent errors. Now we're going to insert a Select Case block. This is just one way to add conditional logic to your VB.NET Express program. We'll see this topic again later in the course, but if you think about it, the way it works is easy to figure out. The variable HelloLanguage has a value assigned to it. If that value is any of the first three cases, then the statement following is executed. If it's not, the statement following Case Else is executed. Select Case HelloLanguage Case "English" 34

HelloWorld.HelloWorldLabel.Text = "Hello World" Case "Espaol" HelloWorld.HelloWorldLabel.Text = "Hola Mundo" Case "Deutsch" HelloWorld.HelloWorldLabel.Text = "Hallo Welt" Case Else HelloWorld.HelloWorldLabel.Text = "Error/Error/Fehler" End Select The completed HelloModule is shown in the illustration.

Click Here to display the illustration Click the Back button on your browser to return -------We're actually doing this in the reverse order of "top down structured programming". To do it "right" we should code the main parts of the program first and then code the "black boxes" (the "objects" that will work independently). But since this is a tutorial, we coded the module first. We'll code the rest of the system on the next page. The HelloWorld form code will take a few more changes. Select the Design window and add a GroupBox from the Toolbox. Here's what the VB.NET Express Help says about this control: Use a GroupBox to logically group a collection of controls on a form. The GroupBox is a container control that can be used to define groups of controls. The typical use for a GroupBox is to contain a logical group of RadioButton controls. If you have two GroupBoxes, each of which contain several option buttons (also known as radio buttons), each group of buttons is mutually exclusive, setting one option value per group.

35

That's exactly what we're going to do. So add three RadioButton controls inside the GroupBox. Again, remember to rename them as they're added. I used the name LanguageGroup for the GroupBox and English, Espaol, and Deutsch for the RadioButton controls. Change the Checked property of the one you want as a default selection to True. In Part 1, we learned about event subroutines. When the Button control in the first program was clicked the Click event was triggered and the DisplayHello_Click subroutine was automatically executed. We'll continue to use this code in our new program but instead of displaying the message directly, the subroutine in HelloModule will be called and the variable Language is passed to it so the subroutine in HelloModule will know what language to use. HelloModule.SayHello(Language) In addition, we have to capture the language selection whenever one of the RadioButton controls is selected. We'll use the CheckedChanged event for each of the three RadioButton controls to do that. Here's the code for just one of them. The others are similar. I reformatted the lines with continuation characters (the space and underscore at the end) just to make it easier to read. Private Sub English_CheckedChanged( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles English.CheckedChanged Language = "English" End Sub Notice that we need a variable (Language) to hold the language selection. Because it must be referenced by all of the CheckedChanged events, I declared it outside the subroutines. This gives the variable module scope. We'll discuss what is called scope of variables in greater detail later too. In my program, I also changed the Text property of the controls to make everything look better. The new code and the HelloWorld form are shown below:

36

Click Here to display the illustration Click the Back button on your browser to return -------At this point, you should be able to run the new, modular Hello World by pressing F5 or clicking the Run icon. Click here to download the complete code. There are a lot of improvements that can be made. For example, the Button control is always in English even though the rest of the form is in the target language. See if you can figure out how to change the button whenever a different language selection is made. In the next part of the course: What's New With Visual Basic .NET Express, we get up to speed on VB Express and what's new and different in it.

37

You might also like