EventHandler & Return Types

M

markliam

I have auto-generated some code for a button by double clicking it.
By default, the code is created with a return type of void and
assigned to a click event. Now, I want the function to return a
DialogResult instead, so I go and replace 'void' with DialogResult in
the function header, but then I get an error stating it's the wrong
return type.

Double clicking the error in Visual Studio takes me to where the
EventHandler is assigned to the click event, but since only asks for
the name of the function and not a return type, I don't see how the
return type can be wrong.

The auto-generated function looked like:
private void button1_Click(object sender, EventArgs e)

I changed it to:
private DialogResult button1_Click(object sender, EventArgs e)

And the error takes me inside the InitializeComponent() function on
the line:
this.button1.Click += new System.EventHandler(this.button1_Click);

What am I doing wrong here?
 
K

Kevin Spencer

The Event Handler for an Event must match the signature of the delegate that
handles the Event. The Button.Click event is designed to be handled by a
method with a void return signature, taking 2 arguments, an object and an
EventArgs instance. This is because the Button.Click event is a
System.EventHandler delegate method. System.EventHandler is a delegate class
that defines the signature of the event handler.

--
HTH,

Kevin Spencer
Chicken Salad Surgeon
Microsoft MVP
 
M

Morten Wennevik [C# MVP]

Hi,

In addition to Kevin's answer, if you are using button1 to close the dialog, use

private void button1_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}

If you are calling button1_Click from somewhere you wish to return a DialogResult to do

private void button1_Click(object sender, EventArgs e)
{
CommonClickMethod();
}

private DialogResult CommonClickMethod()
{
return DialogResult.Cancel;
}

and call CommonClickMethod instead of button1_Click
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top