Skip to main content

Modal Forms in C#


This tutorial will show you how to use the Modal Forms in C#. in C# instead of using a method “Show()” we will change it into “ShowDialog()”method and this creates a Modal form. This Modal form is something you need deal with before you can proceed with your program process.
To display a dialog box modally, here’s the following code:

  1. Form2 formDialog = new Form2();
  2. formDialog.ShowDialog();

In C#, a ShowDialog method has an optional argument that can be used to specify a parent-child relationship for a form.
At this time, let’s create a new project called “modal” then on the form1 design it look like as shown below:

n1

Then add another from and design it looks like as shown below:
n2

Next double click the “Ok” button and the code view will appear. Then add the following code:

  1. private void ok_Click(object sender, EventArgs e)
  2. {
  3. this.DialogResult = DialogResult.OK;
  4. }

The code above will record the result of the button click, and set it to OK. Then double click the “Abort” button and add the following code:
  1. private void abort_Click(object sender, EventArgs e)
  2. {
  3. this.DialogResult = DialogResult.Abort;
  4. }

At this time, let’s go back to Form1 then double click the “Click Me!” button and add the following code:

  1. Form2 formDialog = new Form2();
  2. formDialog.ShowDialog();
  3.  
  4. if (formDialog.ShowDialog() == DialogResult.OK)
  5. {
  6. MessageBox.Show("OK button is click!");
  7.  
  8. }else if (formDialog .ShowDialog () == DialogResult .Abort )
  9. {
  10. MessageBox.Show("Abort button is click!");
  11. }

The code above will simply checks to see if the OK or the Abort button is clicked. If so, it display a message. you can now try to run the application and test it. In my example, I just simply click the “OK” button and the output looks like as shown below.

n3

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.