Loading

Modal Forms in C#

Submitted by: 
Language: 
Visitors have accessed this post 1450 times.

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:

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

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.


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th>
  • You may insert videos with [video:URL]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.