Thomas Nguyen
Thomas Nguyen

Reputation: 494

How to reload/redisplay a form from within itself?

I have a form which I use as a modal dialog box for data entry. When the user clicks on the OK button on the form, I want the button handler to perform data validations and if there is any error the form should reload/redisplay itself instead of returning to the caller. Is this possible?

Caller code:

DatasetProperties propsWindow = new DatasetProperties();
if (propsWindows.ShowDialog() == DialogResult.Cancel)
    return;
// Do other stuffs here

Form code:

public partial class DatasetProperties : Form
{
    // Constructor here

    // OK button handler
    private void btnOK_Click(object sender, EventArgs e)
    {
        // Do data validations here
        if (errorsFound)
        {
            // How to reload/redisplay the form without return to caller?????
        }
     }
 }

Thanks for any help,

Upvotes: 0

Views: 649

Answers (3)

polkduran
polkduran

Reputation: 2551

You can set the Form.DialogResult inside your DatasetProperties.btnOK_Click method to DialogResult.None, this way your DatasetProperties form will not return to the caller Form ('close').

// OK button handler
private void btnOK_Click(object sender, EventArgs e)
{
    // Do data validations here
    if (errorsFound)
    {
        this.DialogResult = System.Windows.Forms.DialogResult.None;
        // How to reload/redisplay the form without return to caller?????
    }
 }

This way you can 'stay' in your DatasetProperties form as long as you have errors. From the msdn, when the DialogResult Enumeration is set to None Nothing is returned from the dialog box. This means that the modal dialog continues running.

Upvotes: 1

Alyafey
Alyafey

Reputation: 1453

as user1646737 mentioned you can use FormClosing event like this:

private void btnOK_Click(object sender, EventArgs e)
{
    // Do data validations here
    Close();
}

Event:

private void DatasetProperties_FormClosing(object sender, FormClosingEventArgs e)
  {
      e.Cancel = errorsFound;
  }

Upvotes: 1

user1646737
user1646737

Reputation: 169

Don't let the user close the form without validation.

Use the FormClosing event. Here's an example. In lieu of the messageBox, include your validation code. If it doesn't validate, e.cancel = true.

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("Are you sure you want to cancel without saving any changes?", "Confirm Cancel", MessageBoxButtons.YesNo) != DialogResult.Yes)
            e.Cancel = true;
    }

Upvotes: 2

Related Questions