0

I am new to C#, I am creating a application in which there is a need of using two forms one is Mainform and other is DialogForm.

The DialogForm has two buttons btnYes and btnNo.

whenever the user clicks the close button, FormClosing Event invokes in which I am calling the DialogForm as shown below:

DialogForm ex = new DialogForm();
ex.ShowDialog(this);

Now I want to give e.cancel=false for btnYes and e.cancel=true for btnNo. (this explained by my sir, only basics)

I know how to give functions to a Button which is in same Form but I dont know how to if the Form is different.

I have gone through some links but as I am new to c#, I can't understand it. If you atleast provide me some links that would be appreciable.

Thanks in advance.

Community
  • 1
  • 1
Mr_Green
  • 40,727
  • 45
  • 159
  • 271

1 Answers1

1

Forms have a property DialogResult. You can set it in the button event handlers.

DialogResult = DialogResult.Yes;
// or
DialogResult = DialogResult.No;

Then you can call the form like this

if (ex.ShowDialog(this) == DialogResult.Yes) {
    // Do something
} else {
    // Do something else
}

You can also set the CancelButton property of the form in the properties window. Microsoft says:

Gets or sets the button control that is clicked when the user presses the ESC key.

The form has also an AcceptButton property. Microsoft says:

Gets or sets the button on the form that is clicked when the user presses the ENTER key.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • Yeah its working. But is there any other way to call a other form button. I mean using `instance` or anything else? please give any link , i dont want to waste your time @Olivier Jacot-Descombes – Mr_Green Sep 15 '12 at 15:19
  • 1
    You can make the button click event handler public and call it from elsewhere. `public void btn_(object sender, EventArgs e) { ... }`. `otherform.btn_Click(this, EventArgs.Empty);`. If you want to close another form, just call `otherform.Close();`. And, of cause, you can always create your own public methods in a form. E.g. `public void ClearAllFields() { ... }`. – Olivier Jacot-Descombes Sep 15 '12 at 15:49