How to Code and Test a Windows Forms Application

Yesterday we finished an article series that showed you how to design a user interface for a Windows Forms application. Today, we'll kick off a five-part article series that shows you how to bring that application to life. This article is excerpted from chapter three of Murach's Visual Basic 2008, written by Anne Boehm (Murach, 2008; ISBN: 1890774456).

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 3
July 08, 2009
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

In the last chapter, you learned how to design a form for a Windows Forms application. In this chapter, you’ll learn how to code and test a Windows Forms application. Here, the emphasis will be on the Visual Studio skills that you need for entering, editing, and testing the Visual Basic code for your applications. You’ll learn how to write that code in the rest of this book.

An introduction to coding

Before you learn the mechanics of adding code to a form, it’s important to understand some of the concepts behind object-oriented programming.

Introduction to object-oriented programming

Whether you know it or not, you are using object-oriented programming as you design a Windows form with Visual Studio’s Form Designer. That’s because each control on a form is an object, and the form itself is an object. These objects are derived from classes that are part of the .NET Class Library.

When you start a new project from the Windows Application template, you are actually creating a new class that inherits the characteristics of the Form class that’s part of the .NET Class Library. Later, when you run the form, you are actually creating an instance of your form class, and this instance is known as an object.

Similarly, when you add a control to a form, you are actually adding a control object to the form. Each control is an instance of a specific class. For example, a text box control is an object that is an instance of the TextBox class. Similarly, a label control is an object that is an instance of the Label class. This process of creating an object from a class can be called instantiation.

As you progress through this book, you will learn much more about classes and objects because Visual Basic is an object-oriented language. In chapter 11, for example, you’ll learn how to use the Visual Basic language to create your own classes. At that point, you’ll start to understand what’s actually happening as you work with classes and objects. For now, though, you just need to get comfortable with the terms and accept the fact that a lot is going on behind the scenes as you design a form and its controls.

Figure 3-1 summarizes what I’ve just said about classes and objects. It also introduces you to the properties, methods, and events that are defined by classes and used by objects. As you’ve already seen, the properties of an object define the object’s characteristics and data. For instance, the Name property gives a name to a control, and the Text property determines the text that is displayed within the control. In contrast, the methods of an object determine the operations that can be performed by the object.

An object’s events are signals sent by the object to your application that something has happened that can be responded to. For example, a Button control object generates an event called Click if the user clicks the button. Then, your application can respond by running a Visual Basic procedure to handle the Click event.

By the way, the properties, methods, and events of an object or class are called the members of the object or class. You’ll learn more about properties, methods, and events in the next three figures.

A form object and its ten control objects

Class and object concepts

  1. An object is a self-contained unit that combines code and data. Two examples of objects you have already worked with are forms and controls.
  2. A class is the code that defines the characteristics of an object. You can think of a class as a template for an object. 
     
  3. An object is an instance of a class, and the process of creating an object from a class is called instantiation
     
  4. More than one object instance can be created from a single class. For example, a form can have several button objects, all instantiated from the same Button class. Each is a separate object, but all share the characteristics of the Button class.

Property, method, and event concepts

  1. Properties define the characteristics of an object and the data associated with an object.
  2. Methods are the operations that an object can perform. 
     
  3. Events are signals sent by an object to the application telling it that something has happened that can be responded to. 
     
  4. Properties, methods, and events can be referred to as members of an object. 
     
  5. If you instantiate two or more instances of the same class, all of the objects have the same properties, methods, and events. However, the values assigned to the properties can vary from one instance to another.

Objects and forms

  • When you use the Form Designer, Visual Studio automatically generates Visual Basic code that creates a new class based on the Form class. Then, when you run the project, a form object is instantiated from the new class.
  • When you add a control to a form, Visual Studio automatically generates Visual Basic code in the class for the form that instantiates a control object from the appropriate class and sets the control’s default properties. When you move and size a control, Visual Studio automatically sets the properties that specify the location and size of the control.  

 

Figure 3-1.  Introduction to object-oriented programming

How to refer to properties, methods, and events

As you enter the code for a form in the Code Editor window, you often need to refer to the properties, methods, and events of its objects. To do that, you type the name of the object, a period (also known as a dot operator, or dot), and the name of the member. This is summarized in figure 3-2.

In some cases, you will refer to the properties and methods of a class instead of an object that’s instantiated from the class. You’ll see examples of that in later chapters. For now, you just need to realize that you refer to these properties and methods using the same general syntax that you use to refer to the properties and methods of an object. You enter the class name, a dot, and the property or method name.

To make it easier for you to refer to the members of an object or class, Visual Studio’s IntelliSense feature displays a list of the members that are available for that class or object after you type a class or object name and a period. Then, you can highlight the entry you want by clicking on it, typing one or more letters of its name, or using the arrow keys to scroll through the list. In most cases, you can then complete the entry by pressing the Tab or Enter key.

To give you an idea of how properties, methods, and events are used in code, this figure shows examples of each. In the first example for properties, code is used to set the value that’s displayed for a text box to 10. In the second example, code is used to set the ReadOnly property of a text box to True. Although you can also use the Properties window to set these values, that just sets the properties at the start of the application. By using code, you can change the properties as an application is running.

In the first example for methods, the Select method of a text box is used to move the focus to that text box. In the second example, the Close method of a form is used to close the active form. In this example, the Me keyword is used instead of the name of the form. Here, Me refers to the current instance of the active form. Note also that the names of the methods are followed by parentheses. If a method requires parentheses like these, they’re added automatically when you press the Enter key after entering the method name.

As you progress through this book, you’ll learn how to use the methods for many types of objects, and you’ll learn how to supply arguments within the parentheses of a method. For now, though, just try to understand that you can call a method from a class or an object.

Although you’ll frequently refer to properties and methods as you code an application, you’ll rarely need to refer to an event. That’s because Visual Studio automatically generates the code for working with events, as you’ll see later in this chapter. To help you understand the code that Visual Studio generates, however, the last example in this figure shows how you refer to an event. In this case, the code refers to the Click event of a button named btnExit.

A member list that’s displayed in the Code Editor window

The syntax for referring to a member of a class or object

  ClassName.MemberName
  objectName.MemberName

Statements that refer to properties

 

txtTotal.Text = 10 Assigns the value 10 to the Text property of the text box named txtTotal.  
txtTotal.ReadOnly = True Assigns the True value to the ReadOnly property of the text box named txtTotal so the user can’t change its contents.
  

 

Statements that refer to methods  

 

txtMonthlyInvestment.Select()

Uses the Select method to move the focus to the text box named txtMonthlyInvestment.

Me.Close()

Uses the Close method to close the form that contains the statement. In this example, Me is a keyword that is used to refer to the current instance of the form class.

 

 

Code that refers to an event  

 

btnExit.Click

Refers to the Click event of a button named btnExit.

 

 

How to enter member names when working in the Code Editor

  1. To display a list of the available members for a class or an object, type the class or object name followed by a period (called a dot operator, or just dot). Then, type one or more letters of the member name, and Visual Studio will filter the list so that only the members that start with those letters are displayed. You can also scroll through the list to select the member you want.
  2. Once you’ve selected a member, you can press the Tab key to insert it into your code, or you can press the Enter key to insert the member and start a new line of code. 
     
  3. By default, all the available members are displayed in the list. To display just the common members, click the Common tab at the bottom of the list. 
     
  4. If a member list isn’t displayed, select the Tools->Options command to display the Options dialog box. Then, expand the Text Editor group, select the Basic group, and check the Auto List Members and Parameter Information boxes.

Figure 3-2.  How to refer to properties, methods, and events

How an application responds to events

Windows Forms applications are event-driven. That means they work by responding to the events that occur on objects. To respond to an event, you code a procedure known as an event handler. In figure 3-3, you can see the event handler for the event that occurs when the user clicks the Exit button on the Invoice Total form. In this case, this event handler contains a single statement that uses the Close method to close the form.

This figure also lists some common events for controls and forms. One control event you’ll respond to frequently is the Click event. This event occurs when the user clicks an object with the mouse. Similarly, the DoubleClick event occurs when the user double-clicks an object.

Although the Click and DoubleClick events are started by user actions, that’s not always the case. For instance, the Enter and Leave events typically occur when the user moves the focus to or from a control, but they can also occur when code moves the focus to or from a control. Similarly, the Load event of a form occurs when a form is loaded into memory. For the first form of an application, this typically happens when the user starts the application. And the Closed event occurs when a form is closed. For the Invoice Total form in this figure, this happens when the user selects the Exit button or the Close button in the upper right corner of the form.

In addition to the events shown here, most objects have many more events that the application can respond to. For example, events occur when the user positions the mouse over an object or when the user presses or releases a key. However, you don’t typically respond to those events.

Event: The user clicks the Exit button

Response: The procedure for the Click event of the Exit button is executed

  Private Sub btnExit_Click(ByVal sender As System.Object,
          ByVal e As System.EventArgs) Handles btnExit.Click
      Me.Close()
  End Sub

Common control events  

 

Event

Occurs when…

Click

…the user clicks the control.

DoubleClick

…the user double-clicks the control.

Enter

…the focus is moved to the control.

Leave

…the focus is moved from the control.

 

 

Common form events  

 

Event

Occurs when…

Load

…the form is loaded into memory.

Closing

…the form is closing.

Closed

…the form is closed.

 

Concepts

  1. Windows Forms applications work by responding to events that occur on objects.
  2. To indicate how an application should respond to an event, you code an event handler, which is a Visual Basic procedure that handles the event. 
     
  3. An event can be an action that’s initiated by the user like the Click event, or it can be an action initiated by program code like the Closed event.

Figure 3-3.   How an application responds to events

How to add code to a form

Now that you understand some of the concepts behind object-oriented coding, you’re ready to learn how to add code to a form. Because you’ll learn the essentials of the Visual Basic language in the chapters that follow, though, I won’t focus on the coding details right now. Instead, I’ll focus on the concepts and mechanics of adding the code to a form.

How to create an event handler for the default event of a form or control

Although you can create an event handler for any event of any object, you’re most likely to create event handlers for the default event of a form or control. So that’s what you’ll learn to do in this chapter. Then, in chapter 6, you’ll learn how to create event handlers for other events.

To create an event handler for the default event of a form or control, you double-click the object in the Form Designer. When you do that, Visual Studio opens the Code Editor, generates a procedure declaration for the default event of the object, and places the insertion point between the Sub and End Sub statements that it has generated. Then, you can enter the Visual Basic statements for the procedure between the Sub and End Sub statements.

To illustrate, figure 3-4 shows the Sub and End Sub statements that were generated when I double-clicked the Calculate button on the Invoice Total form. In the Sub statement, Visual Studio generated a procedure name that consists of the name of the object that the event occurred on (btnCalculate), an underscore, and the name of the event (Click).

This procedure name is followed by two arguments in parentheses that you’ll learn more about later. And the arguments are followed by a Handles clause that says that the procedure is designed to handle the Click event of the button named btnCalculate. It is this clause, not the procedure name, that determines what event the procedure handles.

For now, you should avoid modifying the procedure declaration that’s generated for you when you create an event handler. In chapter 6, though, you’ll learn how to modify the declaration so a single procedure can provide for more than one event.

The procedure that handles the Click event of the Calculate button

How to handle the Click event of a button

  1. In the Form Designer, double-click the control. This opens the Code Editor, generates the declaration for the procedure that handles the event, and places the cursor within this declaration.
  2. Type the Visual Basic code between the Sub statement and the End Sub statement. 
     
  3. When you finish entering the code, you can return to the Form Designer by clicking the View Designer button in the Solution Explorer window.

How to handle the Load event for a form

  • Follow the procedure shown above, but double-click the form itself.

Description

  1. The procedure declaration for the event handler that’s generated when you double-click on an object in the Form Designer includes a procedure name that consists of the object name, an underscore, and the event name.
  2. The Handles clause in the procedure declaration determines what event the procedure handles using the object name, dot, event name syntax. 
     
  3. In chapter 6, you’ll learn how to handle events other than the default event.

Figure 3-4.   How to create an event handler for the default event of a form or control

 

  • Please check back tomorrow for the continuation of this article.

     

     
  • blog comments powered by Disqus
    VISUAL BASIC.NET ARTICLES

    - Basic Form Properties and Modality in VB.NET
    - Multiple Document Interfaces in Visual Basic
    - Visual Basic for Beginners
    - ASP.NET Image to PDF with VB.Net
    - MySQL in ASP.NET: Mono using VB.NET
    - AsyncFileUpload File Type and File Size Vali...
    - Visual Studio: Adding Functionality and Style
    - Clocks and Countdowns
    - User-defined Functions using Visual Basic Ap...
    - Understanding Object Binding in VBA
    - Mastering the Message Box
    - Testing a Windows Forms Application
    - Using Visual Basic.NET Features to Code a Wi...
    - Correcting Code in a Windows Forms Applicati...
    - Write Readable Code and Comments for Windows...

    ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
     
     
     

    ASP Free Forums 
     RSS  Tutorials RSS
     RSS  Forums RSS
     RSS  All Feeds
    Site Map 
    Request Media Kit
    Write For Us Get Paid 
    Weekly Newsletter
     
    Developer Updates  
    Free Website Content 
    Privacy Policy 
    Support 


    © 2003-2012 by Developer Shed. All rights reserved. DS Cluster 1 - Follow our Sitemap
    Most Popular Topics
    All ASP.Net Tutorials