Preventing a dialog from closing in the button's click event handler

后端 未结 10 2050
你的背包
你的背包 2020-12-29 19:40

I have a dialog that I show with .ShowDialog(). It has an OK button and a Cancel button; the OK button also has an event handler.

I want to

10条回答
  •  误落风尘
    2020-12-29 19:55

    Given that you've specified you want a pop error dialog, one way of doing this is to move your validation into a OnClosing event handler. In this example the form close is a aborted if the user answers yes to the question in the dialog.

    private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
       // Determine if text has changed in the textbox by comparing to original text.
       if (textBox1.Text != strMyOriginalText)
       {
          // Display a MsgBox asking the user to save changes or abort.
          if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
             MessageBoxButtons.YesNo) ==  DialogResult.Yes)
          {
             // Cancel the Closing event from closing the form.
             e.Cancel = true;
             // Call method to save file...
          }
       }
    }
    

    By setting e.Cancel = true you will prevent the form from closing.

    However, it would be a better design/user experience to display the validation errors inline (via highlighting the offending fields in some way, displaying tooltips, etc.) and prevent the user from selecting the OK button in the first place.

提交回复
热议问题