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

后端 未结 10 1984
你的背包
你的背包 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:43

    Don't use the FormClosing event for this, you'll want to allow the user to dismiss the dialog with either Cancel or clicking the X. Simply implement the OK button's Click event handler and don't close until you are happy:

    private void btnOk_Click(object sender, EventArgs e) {
      if (ValidateControls())
        this.DialogResult = DialogResult.OK;
    }
    

    Where "ValidateControls" is your validation logic. Return false if there's something wrong.

    0 讨论(0)
  • 2020-12-29 19:43

    Just add one line in the event function

    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) 
                 {
                    this->DialogResult = System::Windows::Forms::DialogResult::None;
                 }
    
    0 讨论(0)
  • 2020-12-29 19:46

    You can catch FormClosing an there force the form to remain opened. use the Cancel property of the event argument object for that.

    e.Cancel = true;
    

    and it should stop your form from closing.

    0 讨论(0)
  • 2020-12-29 19:50

    You can probably check the form before the users hits the OK button. If that's not an option, then open a message box saying something is wrong and re-open the form with the previous state.

    0 讨论(0)
  • 2020-12-29 19:52

    You can cancel closing by setting the Form's DialogResult to DialogResult.None.

    An example where button1 is the AcceptButton:

    private void button1_Click(object sender, EventArgs e) {
      if (!validate())
         this.DialogResult = DialogResult.None;
    }
    

    When the user clicks button1 and the validate method returns false, the form will not be closed.

    0 讨论(0)
  • 2020-12-29 19:52

    This doesn't directly answer your question (other already have), but from a usability point of view, I would prefer the offending button be disabled while the input is not valid.

    0 讨论(0)
提交回复
热议问题