| isual Basic .NET is a hot topic of conversation in the development world thanks to features such as Web Services, inheritance and many other new language features, support of the MicrosoftÂ® .NET Framework, and much more. To show you what all the fuss is about, I'm going to kick the tires of Visual Basic .NET this month.|
Traditionally, the first thing that a developer does with a new language is create a Hello World program. I am going to start with this simple task, then build on it using WindowsÂ® Forms, describing practical features of Windows Forms that you can use in your applications. In addition, I'll touch on some of the differences between forms in Visual BasicÂ® 6.0 and Visual Basic .NET. Needless to say, there are quite a few little surprises along the way as you begin to build applications with Visual Basic .NET.
Creating Form1 When you first start Visual Basic, it will display the Visual StudioÂ® home page (see Figure 1). To start your new Windows Forms project, click the Create New Project link, which will display the New Project Wizard. Then select the Visual Basic Projects folder and click the Windows Application icon. To complete the process, enter a new name for your project in the Name field and click Open. My first sample project is named HelloNetWorld.
Figure 1 Visual Studio Home Page
After the New Project Wizard completes, there will be a new form in your project named Form1.vb. This is just like previous versions of Visual Basic, except for the .vb extension, which replaces the old .frm extension. For the moment, ignore the References folder that is now in your project.
The first task in creating my Hello World application is to add some type of control that will contain my text to the interface. The controls are in the toolbox, just as you'd expect. The toolbox should be hidden along the left-hand side of the Visual Studio interface, if you have chosen the default Visual Studio configuration. Developers who have used Visual InterDevÂ® 6.0 or any other tool that runs in the Visual Studio 6.0 IDE will be somewhat at home with the Visual Basic .NET interface, as the behavior of many of its features is similar to their behavior in Visual Studio 6.0. To access the toolbox, move the mouse over the toolbox area and hover for a second. The toolbox should expand to the right. To select a control for the form, make sure the Windows Forms section of the toolbox is displayed.
For this first example, select the Label control and drag and drop it onto the form. The label should now be highlighted, and its Text property should be selected in the Properties window. Simply enter the text "Hello World" and press enter, and the text will be placed in the Text property. This control behavior is nice because you can drag the control, drop it, then just start typing if the control's default property is Text. (Speaking of the Text property, the Caption properties of many controls in previous versions of Visual Basic such as labels and command buttons have been changed to Text to make the default display text property consistent across all controls.) You can also place controls by selecting the control in the toolbox and drawing it, like you would in previous versions of Visual Basic.
Figure 2 New Hello World Form
At this point, you can press F5 to run your project and display your new form, which will look like the one in Figure 2. Since all of this is not very different from form creation in Visual Basic 6.0 and earlier, you'll be able to get your project up and running quickly.
Adding a Second Form Now that we have a simple application running, it's time to dig deeper. You can add a second form to the project, which will be similar to the way you did it in Visual Basic 6.0. First, right-click the project name in the Solution Explorer. Next, select Add... from the context menu, then choose Add Windows Form. The Add New Item dialog will be displayed with a Windows Form selected. Click Open to take the default name Form2.vb. Add a label control to the form and set its Text property to "Hello World 2".
Wouldn't it be nice if you could link these forms so the user could display Form2 from Form1 and so forth? In Visual Basic 6.0 and earlier you could do this using form1.show connected to a button to display form1. Not so in Visual Basic .NET, as the syntax has changed. To demonstrate this, click Form1.vb [Design]* in the top-left corner of the Form Designer to display Form1 in design view. Next, add a command button to Form1 from the toolbox. Set the button's name property to cmdForm2 and set its Text property to "Show Form 2". You will need to widen the button to show all of its text, and you can do this by dragging the handles or setting the Width property. Some properties, such as Width, are subproperties of another property. For instance, to set Width, you must expand the Size property. Also, the Location property contains the X and Y properties which replace the Left and Top properties, respectively.
Now, let's use the new command button to display Form2. Double-click the button to open its Click event code. For the moment, ignore the other code you see, just make sure the cursor is placed in the cmdForm2_Click procedure. The first step in displaying another form is to create a reference to it. You do this by creating a variable that references Form2 like this:
This statement creates a variable of type Form2. You are really creating a reference to the Form2 object the same way you would create a reference to a component. When you reference the form in your code, you use the reference variable to reference an instance of the form. The New operator tells Visual Basic to create an instance of the form the first time it is accessed. To display the form, you can now call the Show method of the form like this:
Dim frmForm2 As Form2 = New Form2()
Now, press F5 to run the project. You can display Form2 from the first form by clicking the button you placed on Form1.
So far, using Windows Forms in your Visual Basic project is not too different from the traditional Visual Basic-based forms. You should begin to understand that everything accessed by the .NET Frameworkâ"from UI elements to XML documentsâ"is now represented as an object. This is a big change for many developers, and it requires you learn a slightly new way of working with features such as forms because you must create a reference to an object before you can use it. In Visual Basic 6.0 and before, forms were automatically referenced for you, so you didn't need this step.
Because forms are now classes, you have a lot of new power to control how they work. You can add methods to a form by simply defining a new procedure such as the CalcIt procedure:
You can also add properties to a form by defining a public variable:
Public Function CalcIt(ByVal x As Integer, ByVal y As Integer) _
CalcIt = x * y
Now you can access the method or property in your code just like it was a built-in method or property of the form. For instance, you can set the MyResult data member by using this statement in another form or class:
Public MyResult As Integer
frmForm1.MyResult = 29
The Forms Class Let's go back to Form1 and see what is going on behind the scenes. Double-click Form1 to display its code. Scroll up to the top of the code window and look at the Imports definitions. These default Import statements import namespaces from several system classes that are used in creating and managing forms and components. System.WinForms, in particular, contains the Form class that I'm using to create a form. The default Import statements in the sample project (after I added the controls mentioned earlier to the form) look like this:
The rest of the code in the form is part of the Form class. Each form code contains a Class statement that defines the form:
Next, the Inherits statement inherits the WinForms.Form class, creating the foundation for the form
Public Class Form1
Now the new form knows how to behave because it is based on the WinForms.Form class. You can see this in action by commenting out the Inherits statement and trying to compile or run the project. Referencing any property or method of that form that is based upon the inherited class will generate a compile error, like this:
This error is telling me that on line 58, the Form1.Text property is not part of the form. This is because the Text property of the form is inherited and is really part of System.WinForms.Form.
The name 'Text' is not a member of 'HelloNetWorld.Form1'.
The next part of the forms code is the New subprocedure. This procedure is the constructor for the form and replaces both the Form_Initialize and Form_Load events supported by previous versions of Visual Basic. The default New procedure for Form1 looks like this:
The first three statements in the New procedure initialize the form. Your initialization code should go after the TODO statement at the end of the procedure.
Public Sub New()
Form1 = Me
'This call is required by the Windows Forms designer.
'TODO: Add any initialization after
'the InitializeComponent() call
The Dispose procedure definition redefines the default Dispose method from MyBase, the base class. This allows the form to create its own base procedure that cleans up both the base class and the components class:
The Windows Forms designer uses the area of the form after the last procedure (Dispose) for its code. This is where the forms designer puts code that is a result of your interaction with it. The section starts out with the #Region tag:
Overrides Public Sub Dispose()
The next few lines of code define references to the various classes that the form uses. Notice that my label and button controls are referenced here:
#Region " Windows Form Designer generated code "
The controls and Form1 are defined WithEvents to expose the class events for each to the form.
'Required by the Windows Forms designer
Private components As System.ComponentModel.Container
Private WithEvents cmdForm2 As System.WinForms.Button
Private WithEvents Label1 As System.WinForms.Label
Dim WithEvents Form1 As System.WinForms.Form
The next piece of code is the InitializeComponent procedure definition (see Figure 3). This procedure initializes the form and its various components. As stated in the code, make sure you use the forms designer, not the code editor, to modify the form. Notice that InitializeComponent contains code to set all of the properties you modified using the forms designer. The last two lines of the code add the controls to the forms control collection. This procedure is a useful bit of sample code because it demonstrates how to programmatically create and use controls. You can literally copy the code from this procedure and use it in other forms. The way the forms designer adds the code to the form puts the GUI magic to work for you but also lets you see behind the magic curtain to understand what is going on.
The Visual Studio editors have been nicely designed to work with both GUI and code. Figure 4 shows the Visual Studio interface with Form1's code displayed. A really nice feature of the editor is the facility for expanding and collapsing sections of code, which can help you cut out some of the background noise when you want to concentrate on a particular section. Notice how the definition for InitializeComponent in Figure 4 has a + sign to its left and an ellipsis (ï¿½) to the right. This indicates that the full definition has been collapsed. You expand this code by clicking the + sign or hide it with the - sign, which is displayed when the code is visible.
Finally, the next statement ends the region that belongs to the forms designer:
The last procedure defined in Form1 is the command button cmdForm2 click event. This code displays Form2:
The last statement in the form is the End Class statement to end the class definition:
Protected Sub cmdForm2_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Dim frmForm2 As Form2 = New Form2()
Conclusion Windows Forms in the .NET platform provides an unparalleled opportunity for developers. As you can see from the simple example in this column, Windows Forms are easy to use and are truly just another object in your application, making it simple to use forms and add features such as properties and methods to them. Furthermore, because of this, it should be easy for you to automate many form and control features. Also, since Windows Forms are generic (within .NET), it's easy to create a form in Visual Basic or C# and use that form in any language that supports .NET.
If you look behind the scenes at the properties of various controls, you will see dramatic changes. I will explore these changes in future columns and see how they can be of use in your applications. Next month, I will dig into Windows Forms again, looking at form inheritanceâ"a powerful new feature that provides common GUI elements for your applications.
Send questions and comments for Ken to email@example.com.