T James
T James

Reputation: 502

Adding a button event to close the form

I see a lot of questions similar to this, but nothing quite answers it.

I am wondering if there is an event that can be added to a button to directly fire the form_closing routine. I realize it is just one extra step to perform this using something like:

buttonOk.Click += new EventHandler(do_something);

private void do_something(object sender, EventArgs e)
{
    this.DialogResult = System.Windows.Forms.DialogResult.OK;
}

but there are some instances where it would be an advantage to do something like:

buttonOk.Click += new EventHandler(form_close_event..);

Upvotes: 0

Views: 76

Answers (2)

Patrick Hofman
Patrick Hofman

Reputation: 156988

You could use an anonymous method (see here) for this, but in fact, it is all the same.

buttonOk.Click += delegate(object sender, EventArgs e) { ... });

You can call whatever method from inside, so this.Close() is also okay.

Upvotes: 2

Servy
Servy

Reputation: 203835

You can use a lambda, to avoid creating a new named method, if what you want to do is sufficiently simple:

buttonOk.Click += (sender, args) => Close();

Upvotes: 4

Related Questions