O'Reilly logo

Programming Visual Basic .NET by Dave Grundgeiger

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

An Example Visual Basic .NET Program

The first program to write is the same for all languages: Print the words hello, world

—Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language

It has become a tradition for programming books to begin with a hello, world example. The idea is that entering and running a program—any program—may be the biggest hurdle faced by experienced programmers approaching a new platform or language. Without overcoming this hurdle, nothing else can follow. This chapter contains three such examples: one that creates a console application, one that creates a GUI application, and one that creates a browser-based application. Each example stands alone and can be run as is. The console and GUI applications can both be compiled from the command line (yes, Visual Basic .NET has a command-line compiler!). The browser-based application requires a computer running Internet Information Server (IIS).

hello, world

This is the world’s favorite programming example, translated to Visual Basic .NET:

Imports System

Public Module Hello
   Public Sub Main(  )
      Console.WriteLine("hello, world")
   End Sub
End Module

This version of hello, world is a console application -- it displays its output in a Windows command-prompt window. To compile this program, enter it using any text editor, such as Windows’s Notepad, save it in a file whose name ends with .vb, such as Hello.vb, and compile it from the Windows command line with this command:

vbc Hello.vb

The command vbc invokes the Visual Basic .NET command-line compiler, which ships with the .NET Framework SDK, and instructs it to compile the file named in the command-line argument. Compiling Hello.vb generates the file Hello.exe. After compiling, type Hello at the command line to run your program. Figure 1-1 shows the results of compiling and running this program.

Compiling and running hello, world

Figure 1-1. Compiling and running hello, world

If you’re accustomed to programming in Visual Basic 6, you can see even from this little program that Visual Basic has changed dramatically. Here’s a breakdown of what’s happening in this code.

The first line:

Imports System

indicates that the program may use one or more types defined in the System namespace . (Types are grouped into namespaces to help avoid name collisions and to group related types together.) Specifically, the hello, world program uses the Console class, which is defined in the System namespace. The Imports statement is merely a convenience. It is not needed if the developer is willing to qualify type names with their namespace names. For example, the hello, world program could have been written this way:

Public Module Hello
   Public Sub Main(  )
      System.Console.WriteLine("hello, world")
   End Sub
End Module

However, it is customary to use the Imports statement to reduce keystrokes and visual clutter.

An important namespace for Visual Basic developers is Microsoft.VisualBasic. The types in this namespace expose members that form Visual Basic’s intrinsic functions and subroutines. For example, the Visual Basic Trim function is a member of the Microsoft.VisualBasic.Strings class, while the MsgBox function is a member of the Microsoft.VisualBasic.Interaction class. In addition, Visual Basic’s intrinsic constants come from enumerations within this namespace. Much of the functionality available in this namespace, however, is also duplicated within the .NET Framework’s Base Class Library. Developers who are not familiar with Visual Basic 6 will likely choose to ignore this namespace, favoring the functionality provided by the .NET Framework. The .NET Framework is introduced later in this chapter and is explained in detail in Chapter 3.

Next, consider this line:

Public Module Hello

This line begins the declaration of a standard module named Hello. The standard-module declaration ends with this line:

End Module

In Visual Basic 6, various program objects were defined by placing source code in files having various filename extensions. For example, code that defined classes was placed in .cls files, code that defined standard modules was placed in .bas files, and so on. In Visual Basic .NET, all source files have .vb filename extensions, and program objects are defined with explicit syntax. For example, classes are defined with the Class...End Class construct, and standard modules are defined with the Module...End Module construct. Any particular .vb file can contain as many of these declarations as desired.

The purpose of standard modules in Visual Basic 6 was to hold code that was outside of any class definition. For example, global constants, global variables, and procedure libraries were often placed in standard modules. Standard modules in Visual Basic .NET serve a similar purpose and can be used in much the same way. However, in Visual Basic .NET they define datatypes that cannot be instantiated and whose members are all static. This will be discussed in more detail in Chapter 2.

The next line in the example begins the definition of a subroutine named Main:

Public Sub Main(  )

It ends with:

End Sub

This syntax is similar to Visual Basic 6. The Sub statement begins the definition of a subroutine -- a method that has no return value.

The Main subroutine is the entry point for the application. When the Visual Basic .NET compiler is invoked, it looks for a subroutine named Main in one of the classes or standard modules exposed by the application. If Main is declared in a class rather than in a standard module, the subroutine must be declared with the Shared modifier. This modifier indicates that the class does not need to be instantiated for the subroutine to be invoked. In either case, the Main subroutine must be Public. An example of enclosing the Main subroutine in a class rather than in a standard module is given at the end of this section.

If no Main subroutine is found, or if more than one is found, a compiler error is generated. The command-line compiler has a switch (/main: location) that allows you to specify which class or standard module contains the Main subroutine that is to be used, in the case that there is more than one.

Lastly, there’s the line that does the work:

Console.WriteLine("hello, world")

This code invokes the Console class’s WriteLine method, which outputs the argument to the console. The WriteLine method is defined as a shared (also known as a static) method. Shared methods don’t require an object instance in order to be invoked; nonshared methods do. Shared methods are invoked by qualifying them with their class name (in this case, Console).

Here is a program that uses a class instead of a standard module to house its Main subroutine. Note that Main is declared with the Shared modifier. It is compiled and run in the same way as the standard module example, and it produces the same output. There is no technical reason to choose one implementation over the other.

Imports System

Public Class Hello
   Public Shared Sub Main(  )
      Console.WriteLine("hello, world")
   End Sub
End Class

Hello, Windows

Here’s the GUI version of hello, world:

Imports System 
Imports System.Drawing
Imports System.Windows.Forms

Public Class HelloWindows

   Inherits Form

   Private lblHelloWindows As Label

   Public Shared Sub Main(  )
      Application.Run(New HelloWindows(  ))
   End Sub

   Public Sub New(  )

      lblHelloWindows = New Label(  )            
      With lblHelloWindows
         .Location = New Point(37, 31)
         .Size = New Size(392, 64)
         .Font = New Font("Arial", 36)
         .Text = "Hello, Windows!"
         .TabIndex = 0
         .TextAlign = ContentAlignment.TopCenter
      End With
      Me.Text = "Programming Visual Basic .NET"
      AutoScaleBaseSize = New Size(5, 13)
      FormBorderStyle = FormBorderStyle.FixedSingle
      ClientSize = New Size(466, 127)

   End Sub

End Class

This is similar to the hello, world console application, but with extra stuff required since this is a GUI application. Two additional Imports statements are needed for drawing the application’s window:

Imports System.Drawing
Imports System.Windows.Forms

The HelloWindows class has something that Visual Basic programs have never seen before, the Inherits statement:

Inherits Form

The Visual Basic .NET language has class inheritance. The HelloWindows class inherits from the Form class, which is defined in the System.Windows.Forms namespace. Class inheritance and the Inherits statement are discussed in Chapter 2.

The next line declares a label control that will be used for displaying the text Hello, Windows:

Private lblHelloWindows As Label

The Label class is defined in the System.Windows.Forms namespace.

As is the case with console applications, GUI applications must have a shared subroutine called Main:

Public Shared Sub Main(  )
   Application.Run(New HelloWindows(  ))
End Sub

This Main method creates an instance of the HelloWindows class and passes it to the Run method of the Application class (defined in the System.Windows.Forms namespace). The Run method takes care of the housekeeping of setting up a Windows message loop and hooking the HelloWindows form into it.

Next is another special method:

Public Sub New(  )

Like Main, New has special meaning to the Visual Basic .NET compiler. Subroutines named New are compiled into constructors . A constructor is a method that has no return value (but can have arguments) and is automatically called whenever a new object of the given type is instantiated. Constructors are explained further in Chapter 2.

The constructor in the HelloWindows class instantiates a Label object, sets some of its properties, sets some properties of the form, and then adds the Label object to the form’s Controls collection. The interesting thing to note is how different this is from how Visual Basic 6 represented form design. In Visual Basic 6, form layout was represented by data in .frm files. This data was not code, but rather a listing of the properties and values of the various elements on the form. In Visual Basic .NET, this approach is gone. Instead, Visual Basic .NET statements must explicitly instantiate visual objects and set their properties. When forms are designed in Visual Studio .NET using its drag-and-drop designer, Visual Studio .NET creates this code on your behalf.

The command line to compile the Hello, Windows program is:

vbc HelloWindows.vb /reference:System.dll,System.Drawing.dll,System.Windows.Forms.dll /target:winexe

(Note that there is no break in this line.)

The command line for compiling the Hello, Windows program has more stuff in it than the one for the console-based hello, world program. In addition to specifying the name of the .vb file, this command line uses the /references switch to specify three .dlls that contain the implementations of library classes used in the program (Form, Label, Point, etc.). The hello, world console application didn’t require references when being compiled because all it used was the Console class, defined in the System namespace. The Visual Basic .NET command-line compiler includes two references implicitly: mscorlib.dll (which contains the System namespace) and Microsoft.VisualBasic.dll (which contains helper classes used for implementing some of the features of Visual Basic .NET).

Besides the /references switch, the command line for compiling the Hello, Windows program includes the /target switch. The /target switch controls what kind of executable code file is produced. The possible values of the /target switch are:


Creates a console application. The generated file has an extension of .exe. This is the default.


Creates a GUI application. The generated file has an extension of .exe.


Creates a class library. The generated file has an extension of .dll.

The output of Hello, Windows is shown in Figure 1-2.

Hello, Windows!

Figure 1-2. Hello, Windows!

GUI applications are explained in detail in Chapter 4 and Chapter 5.

Hello, Browser

Here is a browser-based version of the hello, world application. Because the simplest version of such an application could be accomplished with only HTML, I’ve added a little spice. This web page includes three buttons that allow the end user to change the color of the text.

<script language="VB" runat="server">

      Sub Page_Load(Sender As Object, E As EventArgs)
         lblMsg.Text = "Hello, Browser!"
      End Sub

      Sub btnBlack_Click(Sender As Object, E As EventArgs)
         lblMsg.ForeColor = System.Drawing.Color.Black
      End Sub

      Sub btnGreen_Click(Sender As Object, E As EventArgs)
         lblMsg.ForeColor = System.Drawing.Color.Green
      End Sub

      Sub btnBlue_Click(Sender As Object, E As EventArgs)
         lblMsg.ForeColor = System.Drawing.Color.Blue
      End Sub



      <title>Programming Visual Basic .NET</title>

      <form action="HelloBrowser.aspx" method="post" runat="server">
         <h1><asp:label id="lblMsg" runat="server"/></h1>
            <asp:button type="submit" id="btnBlack" text="Black" 
               OnClick="btnBlack_Click" runat="server"/>
            <asp:button id="btnBlue" text="Blue" 
               OnClick="btnBlue_Click" runat="server"/>
            <asp:button id="btnGreen" text="Green" 
               OnClick="btnGreen_Click" runat="server"/>


To run this program, enter it using a text editor and save it in a file named HelloBrowser.aspx. Because the application is a web page that is meant to be delivered by a web server, it must be saved onto a machine that is running IIS and has the .NET Framework installed. Set up a virtual folder in IIS to point to the folder containing HelloBrowser.aspx. Finally, point a web browser to HelloBrowser.aspx. The output of the Hello, Browser application is shown in Figure 1-3.

Hello, Browser!

Figure 1-3. Hello, Browser!


Be sure to reference the file through the web server machine name or localhost (if the web server is on your local machine), so that the web server is invoked. For example, if the file is in a virtual directory called Test on your local machine, point your browser to http://localhost/Test/HelloBrowser.aspx. If you point your browser directly to the file using a filesystem path, the web server will not be invoked.

Going into detail on the Hello, Browser code would be too much for an introduction. However, I’d like to draw your attention to the <asp:label> and <asp:button> tags. These tags represent server-side controls . A server-side control is a class that is instantiated on the web server and generates appropriate output to represent itself on the browser. These classes have rich, consistent sets of properties and methods and can be referenced in code like controls on forms are referenced in GUI applications.

ASP.NET has many other nifty features, some of which are:

  • Web pages are compiled, resulting in far better performance over classic ASP.

  • Code can be pulled out of web pages entirely and placed in .vb files (called code-behind files) that are referenced by the web pages. This separation of web page layout from code results in pages that are easier to develop and maintain.

  • ASP.NET automatically detects the capabilities of the end user’s browser and adjusts its output accordingly.

Browser-based applications are discussed in detail in Chapter 6.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required