Click here to Skip to main content
15,885,546 members
Articles / Mobile Apps
Article

Displaying and Working with Forms

Rate me:
Please Sign up or sign in to vote.
3.26/5 (22 votes)
14 Feb 20054 min read 157.7K   43   15
Whether you are new to development, or coming from Visual Basic, C++, Java, or Delphi, managing forms in WinForms can be initially confusing. This is an article targeted at beginners in WinForms programming to demonstrate how to easily manage and work with forms in a WinForms application.

Introduction

Whether you are new to development, or coming from Visual Basic, C++, Java, or Delphi, managing forms in a WinForms can be initially confusing. This is an article targeted at those who are new to WinForms to demonstrate how to easily manage and work with forms in a WinForms application.

Non Modal

A non modal form is a form that is opened, but allows other windows to be focused while the window is open. This allows a user to work with more than one form at a time.

Pattern

The basic pattern to open a non modal form is as follows:

C#

C#
private void button1_Click(object sender, System.EventArgs e) {
    Form2 xForm = new Form2();
    xForm.Show();
}

Visual Basic

VB
Private Sub Button1_Click(ByVal sender As System.Object, _
                    ByVal e As System.EventArgs) Handles Button1.Click
    Dim xForm As Form2
    xForm = New Form2
    xForm.Show()
End Sub

The Show method will return after the form is displayed and the next code to execute depends on the users action on the New, or any other currently open form that the user may choose.

Disposal

When a non modal form is closed, the Dispose will automatically be called by WinForms. This can be seen by setting a break point in the Dispose method (C#) and then closing the form. Because of this, there is no need to call Dispose from the code that created this form.

Modal

Modal, or dialog style forms prevent the user from removing the focus from the form. The user must either open another form, or close the form. Forms opened before the modal form cannot be accessed by the user.

Pattern

C#

C#
private void button2_Click(object sender, System.EventArgs e) {
    using (Form2 xForm = new Form2()) {
    xForm.ShowDialog(this);
    }
}

Visual Basic

VB
Private Sub Button2_Click(ByVal sender As System.Object, _
           ByVal e As System.EventArgs) Handles Button2.Click
    Dim xForm As Form2
    xForm = New Form2
    Try
       xForm.ShowDialog(Me)
       Finally
       xForm.Dispose()
    End Try
End Sub

The ShowDialog method functions differently than the Show method. ShowDialog blocks execution until the form has been closed. Because of this, the Dispose can follow the ShowDialog call immediately as it will not be called until the form has been closed. If the Dispose call was made immediately after a Show method, the form would simply flash on the screen as it would be shown, and then immediately be disposed of after it was shown.

Disposal

WinForms does not automatically call the Dispose method when a user closes a modal form. Because of this, the Dispose is explicitly called. In Visual Basic this is done by calling the Dispose method directly, while in C# the using construct is used.

Returning a Result

The ShowDialog method also differs from the Show method in that it offers a return value. The result can be used to determine how the user closed the form. To do this, the event code can either set the return value, or more simply the DialogResult property of buttons can be used.

To see this in action, drop two buttons on a modal form. Now set the DialogResult property of one to OK, and the other to Cancel. This will cause the buttons to close the form, and return the specified value as the return value of ShowDialog.

The pattern can then be modified as shown:

C#

C#
private void button2_Click(object sender, System.EventArgs e) {
    using (Form2 xForm = new Form2()) {
        if (xForm.ShowDialog(this) == DialogResult.OK) {
            // Take some action
        }
    }
}

Visual Basic

VB
Private Sub Button2_Click(ByVal sender As System.Object, _
           ByVal e As System.EventArgs) Handles Button2.Click
    Dim xForm As Form2
    xForm = New Form2
    Try
        If xForm.ShowDialog(Me) = DialogResult.OK Then
            ' Take some action
        End If
    Finally
        xForm.Dispose()
    End Try
End Sub

Passing Data

Passing data into a form can easily be done by creating public methods, members, or properties and accessing them before the form is shown.

As an example, imagine that the following is declared in the second form:

C#

C#
public void SetValue(string aValue) {
    button1.Text = aValue;
    // Do some other things
}

Visual Basic

VB
Public Sub SetValue(ByVal aValue As String)
button1.Text = aValue
' Do something else
End Sub

This method can then be called from the calling code:

C#

C#
private void button1_Click(object sender, System.EventArgs e) {
     Form2 xForm = new Form2();
     xForm.SetValue("Test");
     xForm.Show();
}

Visual Basic

VB
Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
    Dim xForm As Form2
    xForm = New Form2
    xForm.SetValue("Test")
    xForm.Show()
End Sub

This example is shown using the Show method, but can also be used with ShowDialog.

This same method can be used to retrieve data from a modal form, by calling methods, or accessing members or properties after the ShowDialog has returned, but before the Dispose has been called. In fact, this is why WinForms does not auto dispose modal forms.

An example might be as follows:

C#

C#
private void button2_Click(object sender, System.EventArgs e) {
    using (Form2 xForm = new Form2()) {
        if (xForm.ShowDialog(this) == DialogResult.OK) {
            _Value = xForm.GetValue();
        }
    }
}

Visual Basic

VB
Private Sub Button2_Click(ByVal sender As System.Object, _
         ByVal e As System.EventArgs) Handles Button2.Click
    Dim xForm As Form2
    xForm = New Form2
    Try
        If xForm.ShowDialog(Me) = DialogResult.OK Then
            _Value = xForm.GetValue()
        End If
    Finally
        xForm.Dispose()
    End Try
End Sub

where GetValue is a function of your own definition.

Static Show

If a form is always shown and certain arguments are required, the process can be encapsulated into a static method of the form class. Assuming the previous example of SetValue is a requirement, and even returning a result, it can be added to the Form2 class as follows:

C#

C#
public static string Display(string aValue) {
    using (Form2 xForm = new Form2()) {
        xForm.SetValue("Test");
        if (xForm.ShowDialog() == DialogResult.OK) {
            return GetValue();
        } 
        else {
            return "";
        }
    }
}

Visual Basic

VB
Public Shared Function Display(ByVal aValue As String) As String
Dim xForm As Form2
xForm = New Form2
    Try
        xForm.SetValue(aValue)
        If xForm.ShowDialog() = xForm.DialogResult.OK Then
        Return GetValue()
        Else
        Return ""
        End If
    Finally
        xForm.Dispose()
    End Try
End Function

The SetValue method should also be declared as private instead of public to protect it from outside use.

To show the form, the calling code appears as follows:

C#

C#
private void button1_Click(object sender, System.EventArgs e) {
    _Value = Form2.Display("Test");
}

Visual Basic

VB
Private Sub Button1_Click(ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles Button1.Click
    _Value = Form2.Display("Test")
End Sub

This of course can be done without returning a result as well, by simply changing the method type to void (C#), or type Sub (Visual Basic). In this example I have also changed it to use Show, simply as a variation.

C#

C#
public static void Display(string aValue) {
    Form2 xForm = new Form2();
    xForm.SetValue("Test");
    xForm.Show();
}

Visual Basic

VB
Public Shared Sub Display(ByVal aValue As String) As String
    Dim xForm As Form2
    xForm = New Form2
    xForm.SetValue(aValue)
    xForm.Show()
End Sub

Keeping a reference

Often it is useful to store a reference to a form for later use. Your application may need to update the form from another event, re-show the form, hide the form, etc. .NET does not support Globals, which many of us have formerly used for this purpose. However static form members can be used for this purpose.

In Form2, simply declare the following member:

C#

C#
public static Form2 Form2Ref;

Visual Basic

VB
Public Shared Form2Ref As Form2

This variable can then be used to store a reference to an instance of the form. To reference it again later, for example to re-show the form or refocus it, the following code can be used:

C#

C#
Form2.Form2Ref.Show();

Visual Basic

VB
Form2.Form2Ref.Show()

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Cyprus Cyprus
Chad Z. Hower, a.k.a. Kudzu
"Programming is an art form that fights back"

I am a former Microsoft Regional DPE (MEA) covering 85 countries, former Microsoft Regional Director, and 10 Year Microsoft MVP.

I have lived in Bulgaria, Canada, Cyprus, Switzerland, France, Jordan, Russia, Turkey, The Caribbean, and USA.

Creator of Indy, IntraWeb, COSMOS, X#, CrossTalk, and more.

Comments and Discussions

 
GeneralMy vote of 5 Pin
reza_ali2020008-Jul-12 10:06
reza_ali2020008-Jul-12 10:06 
GeneralMy vote of 1 Pin
The Aryan Monk6-Oct-10 7:47
The Aryan Monk6-Oct-10 7:47 
GeneralRe: My vote of 1 Pin
Chad Z. Hower aka Kudzu7-Jul-11 12:24
Chad Z. Hower aka Kudzu7-Jul-11 12:24 
QuestionSystem modal forms in .NET Installer Pin
nick gavrikov3-Nov-06 22:32
nick gavrikov3-Nov-06 22:32 
Generalhi... Pin
AinJheL_mi28-Jun-06 0:18
AinJheL_mi28-Jun-06 0:18 
GeneralRe: hi... Pin
Chad Z. Hower aka Kudzu25-Aug-06 5:12
Chad Z. Hower aka Kudzu25-Aug-06 5:12 
Generaluseless parameter Pin
Javier Unamuno10-Jul-05 6:41
Javier Unamuno10-Jul-05 6:41 
GeneralRe: useless parameter Pin
Javier Unamuno10-Jul-05 6:58
Javier Unamuno10-Jul-05 6:58 
GeneralRe: useless parameter Pin
Chad Z. Hower aka Kudzu10-Jul-05 11:00
Chad Z. Hower aka Kudzu10-Jul-05 11:00 
GeneralRe: useless parameter Pin
Javier Unamuno11-Jul-05 15:32
Javier Unamuno11-Jul-05 15:32 
GeneralRe: useless parameter Pin
Chad Z. Hower aka Kudzu11-Jul-05 23:47
Chad Z. Hower aka Kudzu11-Jul-05 23:47 
GeneralDispose not always called Pin
Pete Brown14-Jun-05 9:25
Pete Brown14-Jun-05 9:25 
GeneralRe: Dispose not always called Pin
Pete Brown14-Jun-05 9:27
Pete Brown14-Jun-05 9:27 
Generalmodal forms Pin
Harry Mahoney7-Apr-05 10:01
Harry Mahoney7-Apr-05 10:01 
GeneralRe: modal forms Pin
Chad Z. Hower aka Kudzu7-Apr-05 10:16
Chad Z. Hower aka Kudzu7-Apr-05 10:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.