问题
I have an event handler, i would like to pass some parameters to the event
like this, that line trigger an error: method name expected
p.Click += new System.EventHandler(P_Click(sender, new MyEventArgs { design = reader1["desig_prd"].ToString(), prix = (float)reader1["prix_prd"] }));
my P_Click event
public void P_Click(Object sender, EventArgs e)
{
var args = (MyEventArgs)e;
string deignation = args.design;
MessageBox.Show(deignation);
}
and i have class MyEventArgs like this
class MyEventArgs : EventArgs
{
public string design { get; set; }
public float prix { get; set; }
}
Any help? Thanks in advance
回答1:
You can't pass arguments to your method when you subscribing an event handler.You should just specify the method name:
p.Click += new EventHandler(P_Click);
Or short notation:
p.Click += P_Click;
If you want to trigger this manually and pass some arguments then you should call your method with that arguments:
P_Click(this, new MyEventArgs { design = reader1["desig_prd"].ToString(),
prix = (float)reader1["prix_prd"]
});
But this is usually a bad practice, (triggering event handler methods manually).Instead use PerformClick method after subscribe your event handler and of course create another method for your arguments, and call that method from P_Click
:
p.PerformClick();
回答2:
Change it to this
p.Click += new System.EventHandler(P_Click);
回答3:
Use a lambda to close over the data that you want to use in your event handler:
p.Click += (s, args) =>
P_Click(reader1["desig_prd"].ToString(), (float)reader1["prix_prd"]);
回答4:
You misunderstood how events work.
p.Click
is the event.
P_Click
is the event handler.
You don't send the sender and event args - because the event does.
So to hook the event all you need is p.Click += new System.EventHandler(P_Click);
or event simply p.Click += P_Click;
You don't need MyEventArgs
(at least not for this case), and instead, just calculate these values in the event hadler itself:
public void P_Click(Object sender, EventArgs e)
{
var design = reader1["desig_prd"].ToString();
var prix = (float)reader1["prix_prd"];
...
}
来源:https://stackoverflow.com/questions/22256284/method-name-expected-c-sharp