Windows Forms, how to avoid a Dialog Box to close

When displaying a Form as a Dialog/Modal Box sometimes you may need to avoid the Dialog form to close.

Let’s say we have a main form that displays another form as a Modal dialog to finally display some information from that form.

Choose favorite pet form

Choose favorite pet form



Here is the code for the “Choose your favorite pet” Dialog form:

public partial class ChoosePetDialogForm : Form
{
    public string ChosenPet { get; private set; }

    public ChoosePetDialogForm()
    {
        InitializeComponent();
        ChosenPet = "Nothing";
    }

    private void choosePetButton_Click(object sender, EventArgs e)
    {
        var petRadioChecked = this.petListGroup
                                    .Controls
                                    .OfType<RadioButton>()
                                    .FirstOrDefault(r => r.Checked);
        if (petRadioChecked != null)
        {
            ChosenPet = petRadioChecked.Text;
        }
    }
}

The choosePetButton is associated to a DialogResult of value DialogResult.OK:

Button Dialog Result

Button Dialog Result

That makes the ChoosePetDialogForm “return” the value DialogResult.OK when called as a Dialog Box when the choosePetButton is clicked.

And the code for the caller form:

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

    private void takeTestButton_Click(object sender, EventArgs e)
    {
        ChoosePetDialogForm dialog = new ChoosePetDialogForm();
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show(dialog.ChosenPet, "Pet Chosen:");
        }
    }
}

Let’s say now that I want to make some validation before the Modal Dialog form closes, for example allow only “platypus” as favorite pet. How can I make the modal dialog to continue running after clicking a button?

if (!radioButtonPlatypus.Checked)
{
    // avoid the modal dialog to close
}

Well, as explained on the DialogResult Enumeration documentation, we simply need to set the DialogResult property value of the Modal form to DialogResult.None.

if (!radioButtonPlatypus.Checked)
{
    // avoid the modal dialog to close
    this.DialogResult = DialogResult.None;
    MessageBox.Show("Wrong pet! Try again.");
}

This way the Modal form will not close.