3D-kreativ
3D-kreativ

Reputation: 9297

Forms opens two times

In the code below, I open a form with frmContact.ShowDialog(); and then when I close the form by clicking on the OK button in the form it closes, but then it opens again because I have the frmContact.ShowDialog() in the if statement. Could this be done in some oterh way?

        // Button add new customer
    private void btnAdd_Click(object sender, EventArgs e)
    {
        ContactForm frmContact = new ContactForm();

        frmContact.ShowDialog(); // Show the contact form window

        if (frmContact.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show("OK", "Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }

Upvotes: 0

Views: 106

Answers (4)

user1378813
user1378813

Reputation:

private void btnAdd_Click(object sender, EventArgs e)
{
    ContactForm frmContact = new ContactForm();

    frmContact.ShowDialog();
}

Upvotes: 0

Tigran
Tigran

Reputation: 62256

Just leave the second if, like this:

private void btnAdd_Click(object sender, EventArgs e)
{
    ContactForm frmContact = new ContactForm();   

    if (frmContact.ShowDialog() == DialogResult.OK) //just one call
    {
        MessageBox.Show("OK", "Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
}

Upvotes: 2

Jon
Jon

Reputation: 437424

Simply remove the first call:

ContactForm frmContact = new ContactForm();

if (frmContact.ShowDialog() == DialogResult.OK)
{
    MessageBox.Show("OK", "Test", ...);
}

Another option (especially useful if the code that shows the form is not next to the code that checks the return value) is to use Form.DialogResult:

ContactForm frmContact = new ContactForm();
frmContact.ShowDialog();

if (frmContact.DialogResult == DialogResult.OK)
{
    MessageBox.Show("OK", "Test", ...);
}

Upvotes: 8

Nick
Nick

Reputation: 25799

Just get rid of the first ShowDialog.

Upvotes: 6

Related Questions