what is correct way to assign a custom event handler?

R

Rich P

I have a (test) form with 3 panels and a button on each panel. I want
to assign a single event handler to the 3 buttons using an anonymous
method (just experimenting here) - this based on an example in a prior
post (of mine). The compiler is complaining as noted below. What is the
correct way to do this?

using...
...
namespace CsharpProj2008
{
public partial class Form1 : Form
{
string[] s1 = new string[] { "test1", "test2", "test3 };

public frmMultiBtns()
{
InitializeComponent();
}

//>>---complaining in this block

button1.Click += (sender, e) => GeneralPurposeClickHandler(sender, e,
s1[0]);
button2.Click += (sender, e) => GeneralPurposeClickHandler(sender, e,
s1[1]);
button3.Click += (sender, e) => GeneralPurposeClickHandler(sender, e,
s1[2]);

//>>

private void Form1_Load(object sender, EventArgs e)
{
//can't use "sender" here because already declared
}

void GeneralPurposeClickHandler(object sender, EventArgs e, string s2)
{
Control ctl = (Control)sender;
Panel panel = (Panel)ctl.Parent;
Console.WriteLine(ctl.Name + " " + panel.Name + " " + s2);

}

}
}


Thanks,

Rich
 
J

Jeff Johnson

//>>---complaining in this block

button1.Click += (sender, e) => GeneralPurposeClickHandler(sender, e,
s1[0]);
button2.Click += (sender, e) => GeneralPurposeClickHandler(sender, e,
s1[1]);
button3.Click += (sender, e) => GeneralPurposeClickHandler(sender, e,
s1[2]);

//>>

From what you posted, this code is outside of any methods. Put it in the
constructor.
 

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