How to Code and Test a Windows Forms Application

This article introduces you to the mechanics of adding code to a Windows form. It starts with an introduction to object-oriented programing, and takes you from there. The first of three parts, it is excerpted from chapter three of the book Murach's C# 2005, written by Joel Murach (Murach, 2005; ISBN: 9781890774370).

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 10
June 22, 2006
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

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 C# is an object-oriented language. In chapter 12, for example, you’ll learn how to use the C# 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 C# method 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


Figure 3-1.  Introduction to object-oriented programming

Class and object concepts

  • 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.
  • A class is the code that defines the characteristics of an object. You can think of a class as a template for an object.
  • An object is an instance of a class, and the process of creating an object from a class is called instantiation.
  • 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 C# 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 C# 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.

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 the form’s 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 addition to referring to the properties, methods, and events of objects, you can also refer to some of the properties and methods of a class directly from that class. The code shown in the Code Editor in this figure, for example, refers to the ToDecimal method of the Convert class. A property or method that you can refer to directly from a class like this is called a static member. You’ll learn more about static members in chapter 4. For now, you just need to realize that you can refer to static properties and methods using the same techniques that you use to refer to the properties and methods of an object.

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 the first few 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 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 a text box’s ReadOnly property 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 Focus 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 this keyword is used instead of the name of the form. Here, this refers to the current instance of the active form. Note also that the names of the methods are followed by parentheses.

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 and that you must code a set of parentheses after the method name.

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


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

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 a string holding the number 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.Focus();

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

this.Close();

Uses the Close method to close the form that contains the statement. In this example, thisis a keyword that is used to refer to the current instance of the 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

  • 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, you can type the first few letters of the member name, and the Code Editor will select the first entry in the list that matches those letters. Or, you can scroll down the list to select the member you want. Once it’s selected, press the Tab key to insert the member into your code.
  • 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 C# category, and check the Auto List Members and Parameters Information boxes.

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 special type of method known as an event handler. When you do that, Visual Studio generates a statement that connects, or wires, the event handler to the event. This is called event wiring, and it’s illustrated in figure 3-3.

In this figure, the user clicks the Exit button on the Invoice Total form. Then, Visual Studio uses the statement it generated to wire the event to determine what event handler to execute in response to the event. In this case, the btnExit.Click event is wired to the method named btnExit_Click, so this method is executed. As you can see, 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 presented 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


Figure 3-3.  How an application responds to events

Wiring: The application determines what method to execute

  this.btnExit.Click += new System.EventHandler(this.btnExit_Click);

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

  private void btnExit_Click(object sender, System.EventArgs e) 
  {
     this.Close();
  }

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...OOOccurs when…

Load

…the form is loaded into memory.

Closing

…the form is closing.

Closed

…the form is closed.

Concepts

  • Windows Forms applications work by responding to events that occur on objects.
  • To indicate how an application should respond to an event, you code an event handler, which is a special type of method that handles the event.
  • To connect the event handler to the event, Visual Studio automatically generates a statement that wires the event to the event handler. This is known as event wiring.
  • 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. 

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 C# 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. Then, Visual Studio opens the Code Editor, generates a method declaration for the default event of the object, and places the insertion point on a blank line between the opening and closing braces of that declaration. As a result, you can immediately start typing the C# statements that you want to include in the body of the method.

To illustrate, figure 3-4 shows the code that was generated when I double-clicked the Calculate button on the Invoice Total form. In this figure, the code for the form is stored in a file named frmInvoiceTotal.cs. In addition, the name of the method is the name of the object (btnCalculate), an underline, and the name of the event (Click). The statement that wires the Click event of this button to this event handler is stored in the file named frmInvoiceTotal.Designer.cs.

Before you start an event handler for a control, you should set the Name property of the control as described in chapter 2. That way, this name will be reflected in the method name of the event handler as shown in this figure. If you change the control name after starting an event handler for it, Visual Studio will change the name of the object in the event wiring, but it won’t change the name of the object in the method name. And that can be confusing when you’re first learning C#.

You should also avoid modifying the method declaration that’s generated for you when you create an event handler. In chapter 6, you’ll learn how to modify the method declaration. But for now, you should leave the method declaration alone and focus on adding code within the body of the method.

How to delete an event handler
 
If you add an event handler by mistake, you can’t just delete it. If you do, you’ll get an error when you try to run the application. This error will be displayed in an Error List window as shown in figure 3-6, and it will indicate that the event handler is missing.

The method that handles the Click event of the Calculate button


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

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 method that handles the event, and places the cursor within this declaration.
  2. Type the C# code between the opening brace ({) and the closing brace (}) of the method declaration.
  3. When you are finished writing 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

  • The method declaration for the event handler that’s generated when you double-click on an object in the Form Designer includes a method name that consists of the object name, an underscore, and the event name.
  • The event handler is stored in the cs file for the form.
  • Most the code that’s generated when you design a form, including the statement that wires the event to the event handler, is stored in the Designer.cs file for the form. If necessary, you can open this file to view or delete the event wiring.
  • In chapter 6, you’ll learn how to handle events other than the default event.

That’s because when you create an event handler, Visual Studio also generates a statement that wires the event to the event handler. As a result, if you delete an event handler, you must also delete the wiring for the event. The easiest way to do that is to double-click on the error message in the Error List window. This will open the Designer.cs file for the form and jump to the statement that contains the wiring for the missing event handler. Then, you can delete this statement.

The event handlers for the Invoice Total form


 
Figure 3-5 presents the two event handlers for the Invoice Total form. The code that’s shaded in this example is the code that’s generated when you double-click the Calculate and Exit buttons in the Form Designer. You have to enter the rest of the code yourself.

I’ll describe this code briefly here so you have a general idea of how it works. If you’re new to programming, however, you may not understand the code completely until after you read the next two chapters.

The event handler for the Click event of the Calculate button calculates the discount percent, discount amount, and invoice total based on the subtotal entered by the user. Then, it displays those calculations in the appropriate text boxes. For example, if the user enters a subtotal of $1000, the discount percent will be 20%, the discount amount will be $200, and the invoice total will be $800.

In contrast, the event handler for the Click event of the Exit button contains just one statement that executes the Close method of the form. As a result, when the user clicks this button, the form is closed, and the application ends.

In addition to the code that’s generated when you double-click the Calculate and Exit buttons, Visual Studio generates other code that’s hidden in the Designer.cs file. When the application is run, this is the code that implements the form and controls that you designed in the Form Designer. Although you may want to look at this code to see how it works, you shouldn’t modify this code with the Code Editor as it may cause problems with the Form Designer. The one exception is deleting unnecessary event wiring statements.

When you enter C# code, you must be aware of the coding rules summarized in this figure. In particular, note that each method contains a block of code that’s enclosed in braces. As you’ll see throughout this book, braces are used frequently in C# to identify blocks of code. Also, note that each statement ends with a semicolon. This is true even if the statement spans several lines of code.

You should also realize that C# is a case-sensitive language. As a result, you must use exact capitalization for all C# keywords, class names, object names, variable names, and so on. If you enter the name of a control or variable without using the correct capitalization, for example, the Code Editor won’t recognize the control or variable.

The event handlers for the Invoice Total form

  private void btnCalculate_Click(object sender, System.EventArgs e)
  {
     decimal subtotal = Convert.ToDecimal(txtSubtotal.Text); 
     decimal discountPercent = 0m;
     if (subtotal >= 500)
     {
        
discountPercent = .2m;
     }
     else if (subtotal >= 250 && subtotal < 500)
     {
        
discountPercent = .15m;
     }
     else if (subtotal >= 100 && subtotal < 250)
     {
        
discountPercent = .1m;
     } 

     decimal discountAmount = subtotal * discountPercent;
     decimal invoiceTotal = subtotal - discountAmount;

     txtDiscountPercent.Text = discountPercent.ToString("p1");
     txtDiscountAmount.Text = discountAmount.ToString("c");
     txtTotal.Text = invoiceTotal.ToString("c");

     txtSubtotal.Focus();
  }
 
private void btnExit_Click(object sender, System.EventArgs e)
  {
     this.Close();
  }

Coding rules

  • Use spaces to separate the words in each statement.
  • Use exact capitalization for all keywords, class names, object names, variable names, etc.
  • End each statement with a semicolon.
  • Each block of code must be enclosed in braces ({}). That includes the block of code that defines the body of a method.

Description

  1. When you double-click the Calculate and Exit buttons in the Form Designer, it generates the shaded code shown above. Then, you can enter the rest of the code within the event handlers.
  2. The first event handler for the Invoice Total form is executed when the user clicks the Calculate button. This method calculates and displays the discount percent, discount amount, and total based on the subtotal entered by the user.
  3. The second event handler for the Invoice Total form is executed when the user clicks the Exit button. This method closes the form, which ends the application.

Figure 3-5 The event handlers for the Invoice Total form

Please check back next week for the continuation of this article.

blog comments powered by Disqus
C# ARTICLES

- Beginning C#
- ASP.NET RedirectPermanent Method using C# an...
- C Programming Language and UNIX Pioneer Pass...
- Using Facebook JavaScript SDK in ASP.NET wit...
- ASP.NET Export to Excel and Word using VB.NE...
- WAV and MP3 Streaming with ASP.Net and C#
- Game Programming using SDL: the File I/O API
- C# and Java Developer Jobs on the Rise
- The Future Evolution of C# and VB.NET
- C# If and Else-if Statements
- How To Use the C# String Replace Method
- 5 Ways to Parse XML in C#
- C# Meets Design Patterns
- Coding a CRC-Generating Algorithm in C
- Cyclic Redundancy Check

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 8 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials