How do I use Form.ShowDialog?

Given that your only tag is C#, and you expect an OK and CANCEL button, it seems to me that you are actually looking for the MessageBox function. Creating and disposing a Form just for the sake of showing a messagebox dialog is uncessary.

if (MessageBox.Show("boxtext", "boxcaption" MessageBoxButtons.OKCancel) == DialogResult.OK) 
{
// Read the contents of testDialog's TextBox. 
// cl.AcceptButton.DialogResult = DialogResult.OK;
this.label4.Text = cl.textBox1Text;
}else
{
    this.label4.Text = "Cancelled";
}

MessageBox is a wrapper for the same-named WIN32 API Function:

int WINAPI MessageBox(
  _In_opt_  HWND hWnd,
  _In_opt_  LPCTSTR lpText,
  _In_opt_  LPCTSTR lpCaption,
  _In_      UINT uType
);

Note: If you already have a window-handle / Form make sure to pass it as the first parameter to MessageBox.


You will need to add them yourself, you can add the buttons to your Form and set their DialogResult Property. This will return the DialogResult and close the Form without you having to wire up any code. Here is an example using a Method to return the Value of The TextBox on Form2(There are two Buttons on Form2 with their DialogResults set to Cancel and Ok respectivly).

Form1

public partial class Form1 : Form
{
    Form2 frm2;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        frm2 = new Form2();
        DialogResult dr = frm2.ShowDialog(this);
        if (dr == DialogResult.Cancel)
        {
            frm2.Close();
        }
        else if (dr == DialogResult.OK)
        {
            textBox1.Text = frm2.getText();
            frm2.Close();
        }
    }
}

Form2

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public string getText()
    {
        return textBox1.Text;
    }
}

Tags:

C#