December 3, 2010

C# - Modal and Modeless dialogs in C#


In this article I will walk you through how do you create different forms and access form from other forms. While we developing I will help you to understand model and modeless forms and some important control properties.

We will create three forms. One is Main form that will invoke and display About form and Address Form. The About form is invoked as Modeless dialog and Address Form is invoked as Model dialog.

Let us start the step by step.

Note: If you are experienced, and do want to slide fast:
1)      Open the attached project
2)      Look at the form properties in bold as well refer the brown texts here
3)     Search the project with two tags: _Mode_less , _Model [ To follow the code easily at a glance]

Main Form

First we will design the Main form that invokes two other forms. Follow the steps below:

1. Open visual studio 2005 and create a new Visual C# Windows Application.
2. Use the below picture as the reference for creating the Form

I marked all the controls with some numbers to ask you make some changes on the corresponding controls.
1: TextBox Control. Actually no property change is required for this text box. When I am creating the picture I forgot it and kept a number for it. So leave it as default
2: Button Control. Change the Name property to btnGetAddress
4: Button Control. Change the Name property to btnAbout
3: TextBox Control. Change the Name property to txtAddress. Set MultiLine to true. This will allow you resize the text box to have different height. When MultiLine property is false the resize in terms of Height is not allowed. Set the ReadOnly to true. This property allows the control not editable by the end user. But, you can edit it through the code at runtime. Change the BackColor property to White as the ReadOnly property changed it to some Gray color.

If you wish you can set the Background and foreground colors as you like.

The About Box (Form)

This is the second form that we are going to add to our project. When you created Windows Application, the wizard created a main form for us and that for is the Start Up form. 

Suppose if you want to change the Startup form, what will you do?
Double click the Program.cs file and scroll to find the below piece of code:

static void Main()
    Application.Run(new frmMain());

The Application.Run method takes our Main form Object and displays it. I renamed the form1 to frmMain by right clicking it in the solution explorer and using the Rename menu option.

To add our second form:
1) Goto the solution Explorer using View|Solution Explorer if it is already not available on your right side pane.
2) Select the solution Name, right click on it, and chose Add|New Item

3) In the displayed dialog select Windows Form and Change the File Name to frmAbout.cs

4) Place a Label control on the Form. Set the Text property as shown in the Picture below. Note, you need to use the Down Arrow button of the text property value to type multiple lines for the label. The screen shot is shown below:



The Address Dialog Box

Now we will add a new form and display it like Model dialog. Follow the Steps below and I will tell you what is Model dialog and Modeless dialog when you run the finished application.

1) Add a new Windows form as you did in the previously. Name the file as AddressDlg.cs
2) Place 5 Labels and 5 Text boxes to the Form. Add two button controls
3) Arrange the Form as shown below:

1: Set the Name property to txtDoorNumber
2: Set the Name property to txtStreet
3: Set the Name property to txtArea
4: Set the Name property to txtCity
5: Set the Name property to txtPin
7: Set the Name property to btnOK. Set the text property to OK. And select OK as the DialogResult Property.
8: Set the Name property to btnCancel. Set the text property to OK. And select Cancel as the DialogResult Property.
9: Set the Name property to AddressDlg. Select btnOK for the AcceptButton property. Select btnCancel for the CancelButton property.

We are done with designing the Address form. Now let me explain about the above form. As I already told, we are going to display the above form as model. What is the difference between model and modeless dialogs (or forms)?

When we display a form as Modeless, you can still access the Main form that called the Modeless dialog. But, the access to the Main form is prohibited when we display the same dialog as Model. Let us say the Instance of the above dialog as X, X.Show() will display the dialog as modeless where as X.ShowDialog() will display the dialog as Model. If you remember, in this Article we are going to display about for as Modeless and Address form as Model.

We set btnOK as AcceptButton and btnCancel as the Cancelbutton properties for the form. This is to hook-up the Esc and Enter keystrokes on the form to the OK and Cancel button clicks. So hitting enter button on the form runs the OK button event handler. Hitting Esc will run the cancel button event handler.

The ShowDialog() function will return some constants based on how the form is closed (actually hide) by the interacting user. We can set these constants to the button on the form. We set DialogResult property for the button btnOK as OK, and for the button btnCancel as Cancel. For Example if the user closes the dialog by clicking the btnOK the constant OK is passed back to the caller.

Hope all the designs are done now. If you need you can open the attached project for reference. Open the forms and look at the properties that appear in bold.

Button Handler on Main form

First let us display the About Form as Modeless dialog.

1) Open the Main form in the designer.
2) Double click the button About.
3) Now add the following code in the handler you are in:

//001_Mode_less: Display the Modeless Dialog
frmAbout AboutForm = new frmAbout();

In the above code first we created the object of frmAbout and the object name is AboutForm. Then we are calling AboutForm.Show() to display the about form as modeless dialog. Also note the calling code is not blocked and it continues executing the next statement after the call to the Show method. That means User Interaction is allowed on both About Form as well as the Main Form that invoked it.

4) Now, double click the … button
5) In the Handler write the following code [Please try writing in stead of copy paste. The pop-ups on the code window give you some Nice Exp

//004_Model: Invoke the Model Dialog and set the Readonly Address
//Text box
AddressDlg dlg = new AddressDlg();
if (dlg.ShowDialog() == DialogResult.OK)
    txtAddress.Text  = dlg.Address;
    txtAddress.Text = "---";

After creating the instance (dlg) of AddressDlg we are displaying the dialog as model dialog. This we use the method ShowDialog() and the call to this method block the calling code until the dialog is closed. The return value of function (The value you set for the button’s DialogResult property) is checked to make sure OK button is clicked by the user. In that case (OK button click) we take the Address property from dialog and display it in the Multi Line text box Address.

Note that all the controls in the Form are Private. If you need you can change it by setting the Modifier property of the control, which is not advisable. I do expose a property Address, which stores the values, entered by the user in the text fields.

Coding the Address Form (OK. Model Dialog)

1) Right click and select view code on the Address Form
2) Declare a private string that stores the address entered in the text boxes

//002_Model: Declare a Private Field
private string mAddress;

3) Next add a public property that give access to the Address field

//003_Model: Read Only Property
public string Address
    get { return mAddress; }

4) Go to the design view of the address
5) Double click the button OK
6) In the displayed event handler write the following code

//001_Model: Set the Address Member variable based on the User Input
mAddress = txtDoorNumber.Text + ";" + txtStreet.Text + Environment.NewLine +
    txtArea.Text + Environment.NewLine + txtCity.Text + Environment.NewLine +
    "Pin -" + txtPin.Text;

We store all the Address parts in the local private field by combining all the text values entered in the form. And, we do this on the handler for OK button click, as we know all the texts are ready from user perspective. The Address property is public and gives access to the Field mAddress for external world.

Run the Project

1) Click the Run button
2) Click the About Button

Now you can move the both Main for about forms. Which means the caller Main form is not blocked and responds to your User input Click & Drag (Move).

3) Close the about form (If you need)
4) Click the Ellipsis (…) button

The displayed address form blocks the caller that the main form. When the address form is closed, the main form will start receiving user input.

5) Type in the Address Parts and Close the Dialog. [ You can try Esc and Hitting Enter and Clicking cancel. ]

Source Code: Download

No comments:

Post a Comment

Leave your comment(s) here.

Like this site? Tell it to your Friend :)