MCSharp
MCSharp

Reputation: 1068

How to run code only if button was clicked in another form

I created a new form with buttons labeled as "OK" and "Cancel" This form pops up by clicking a button from the first form. I'd like to run some code only if the "OK" button was clicked in the new custom form. This is not a MessageBox().

So far I have something like this:

CustomForm c = new CustomForm();
DialogResult r = c.DialogResult;

c.ShowDialog();

if (r == DialogResult.OK)
{
    //Run code
}

This however isn't working. How do I code this properly? I also set the "OK" button as the AcceptButton in CustomForm.

Upvotes: 0

Views: 1275

Answers (3)

Uthistran Selvaraj
Uthistran Selvaraj

Reputation: 1371

You have mentioned that they are two buttons, then better you can use button click event of OK button to perform your operation. This may be correct, if I have understand your question..//

Upvotes: 0

unholysampler
unholysampler

Reputation: 17321

You need to show the dialog before you access the result. Right now you are creating the dialog, storing the value in a variable, and then allowing the user to change the result of the dialog. This does not change the value stored in your variable.

Upvotes: 0

Simon Whitehead
Simon Whitehead

Reputation: 65079

Perhaps prefer compacting it like so:

CustomForm c = new CustomForm();

if (c.ShowDialog() == DialogResult.OK) {
    // run code
}

Also, remember you have to set the DialogResult of the button on the other form to be OK:

DialogResult Property

DialogResult is an enum. As such, it is copied by value.. not by reference.

Upvotes: 4

Related Questions