70-526 MCTS


Add a Windows Form to a project at design time

Forms can be added to an application in a number of ways at design time. The next few sections cover each of these approaches.


Creating the first form at design time

When you create a new Windows Application project, a Form called Form1 is automatically added to the project. So that you are familiar with this, create a new Windows Application project now.

  1. Launch Visual Studio .NET or Visual C# Express. On the start page, click on Create: Project... (alternatively, you can select the File menu, then New Project). The New Project dialog appears as in figure 1. Choose Windows Application and Name the project anything you like.



    Figure 1 - New Project dialog

  2. When you click OK, the IDE is now in the design view as shown in figure 2.



    Figure 2 - The Windows Design Form

  3. Build the application by pressing the shortcut key, F6. There should be no build errors, so run the application by pressing the shortcut F5.

Hey presto, a windows application is running. It does not do anything, but at least it works. Close the application.


Adding subsequent forms

Adding a second Form to the application can be achieved in one of two ways.

  1. The first way is to use the Solution Explorer. If you expand all of the tree, you will see a similar set of files as shown below.



    Figure 3 - The Solution Explorer

    Right-click on the project name, point to Add, then click on Windows Form.



    Figure 4 - Add a Windows Form

    This brings up the Add New Item dialog.



    Figure 5 - Add New Item dialog

    The Windows Form icon is highlighted, with a default name of Form2. Every time you create a new form, the IDE defaults the name to Form plus the next available number. You can change the name of the form at this point to anything you like, then select OK and hey presto, your application now has two forms in it.

  2. The second way is to select the Project menu, then select Add Windows Form. This brings up the Add New Item dialog. Now enter a name for the Form just like before.

Adding a Form by hand

A new form can be added to an application by doing all of the work yourself (why you would want to - who knows!). So let us create a new form by hand and watch what happens when we add it to the windows application.

  1. Create a Windows Forms application.

  2. Create a new text file and call it Form2.cs in the project directory of the application we created in the previous step. Also create a second text file named Form2.Designer.cs

  3. Add the following code to the file Form2.cs.

    using System;
    using System.Windows.Forms;
    
    public partial class Form2 : Form
    {
      public Form2()
      {
        InitializeComponent();
      }
    }
  4. Add the following code to the file Form2.Designer.cs.

    partial class Form2 
    {
      private System.ComponentModel.IContainer components = null;
    
      protected override void Dispose(bool disposing)
      {
        if (disposing && (components != null))
        {
          components.Dispose();
        }
        base.Dispose(disposing);
      } 
    
      private void InitializeComponent()
      {
        this.components = new System.ComponentModel.Container();
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.Text = "Form2";
      }
    }
  5. On the Project menu, select Add Existing Item... and choose the file Form2.cs. Notice that the IDE includes both of the files in the solution.

What we have done is pretty much add the same code that the IDE would have added for us. But we need to understand what we have added and what is missing from our code that is in the IDE generated code.


Under the hood

In the first file, Form2.cs, the class is defined by the code

public partial class Form2 : Form 
{
  // Form implementation
}

Form2 is the name of the class. It is derived from the System class Form. This is done by writing a colon (:) after the class name, and adding the class from which it is derived from after the colon. In our case Form2 is derived from System.Windows.Forms.Form.

The partial keyword means that the code for the class is located in more than one place (usually in more than one file).

Within this code is the constructor for the class. A constructor is a method that is invoked upon instantiation of a class. In C# these are known as "instance constructors". An instance constructor is a member that implements the actions required to initialize an instance of a class. A constructor is invoked when you use the new operator.

Form2 MyForm = new Form2();

Every constructor has the same defining layout and has the same name as the name of the class:

[modifier] constructor_name (parameters)
{
  // constructor body
}

The [modifier] can be private, public, protected or internal.

The constructor_name of a constructor must be the same as the name of the class.

A constructor can take zero or more arguments as parameters. A constructor with zero arguments (that is no-argument) is known as default constructor. A class can have more than one constructor, by giving each constructor a different set of parameters. This gives the user the ability to initialise the object in more than one way.

The // constructor body can be used to initialise the object into a known starting state.

The second file, Form2.Designer.cs, contains those parts of class that you usually do not need to worry about as the IDE takes care of them for you.

The InitializeComponent() method is used for storing all of the customizations made to the form, such as altering its width and height, border style, etc. It is also modified when you add new components such as buttons and listboxes etc. A call to this method is made in the constructor of the class. The use of the keyword this is used to qualify that the properties being changed apply to the current instance of the class.

Within the class an, instance of a Container object is used to hold all of the components that will be added to the form. An example of a component is a Timer, Tooltip or SaveFileDialog. Click on the link an article on the difference between a Control and a Component.

private System.ComponentModel.IContainer components = null;

Lastly we add a dispose method to release all the resources that the form owns. The form should also release all resources owned by its base types by calling its parent type's Dispose method.

protected override void Dispose(bool disposing)
{
  if (disposing && (components != null))
  {
    components.Dispose();
  }
  base.Dispose(disposing);
}

As long as you know and understand the code for what you want to do then you can add it programmatically.


Example - Add a button

To add a button to the form we need two pieces of code. This first is a declaration of a button in the file Form2.Designer.cs just within the class.

private System.Windows.Forms.Button button1;

Secondly we add the following code to the InitializeComponent() method after the code that already exists.

// Create the new button
this.button1 = new System.Windows.Forms.Button();

// Set up its properties
this.button1.Location = new System.Drawing.Point(30, 30);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Hello";
this.button1.UseVisualStyleBackColor = true;

// Add it to the form
this.Controls.Add(this.button1);

Et voila, a form with a button added without the use of the IDE.


Adding a Form at run time

Forms can not only be added at Design time, but they can be created on the fly at run-time. To do this, you need to have a Form already defined in code, like Form2 above. All you have to do is simply declare and instantiate a variable that represents the form.

Form2 myForm;
myForm = new Form2();

Then to show the new form that has been created, simply call the Show method.

myForm.Show();

MSDN references

  • IContainer Interface
  • Container Class
  • IDisposable.Dispose Method
  • How to: Create a Windows Application Project
  • Creating a New Windows Form
  • Walkthrough: Creating a Simple Windows Form
  • Walkthrough: Creating an Accessible Windows-based Application


    << Previous Contents Next >>

    © Publicjoe, 2007