Reputation: 2981
As the title really, I'm in one part of my code and I would like to invoke any methods that have been added to the Button.Click handler.
How can I do this?
Upvotes: 1
Views: 5944
Reputation: 85
AVOID. Really. Seems like you handle some important logic right in the event handler.
Move the logic out of the handler.
Upvotes: 4
Reputation: 23935
You can do it via reflection..
Type t = typeof(Button);
object[] p = new object[1];
p[0] = EventArgs.Empty;
MethodInfo m = t.GetMethod("OnClick", BindingFlags.NonPublic | BindingFlags.Instance);
m.Invoke(btnYourButton, p);
Upvotes: 2
Reputation: 6102
You will need an event to act as a proxy, but you are pretty much better off just refactoring your code.
private EventHandler ButtonClick;
protected override void CreateChildControls()
{
base.CreateChildControls();
m_Button = new Button{Text = "Do something"};
m_Button.Click += ButtonClick;
ButtonClick += button_Click;
Controls.Add(m_Button);
}
private void MakeButtonDoStuff()
{
ButtonClick.Invoke(this, new EventArgs());
}
private void button_Click(object sender, EventArgs e)
{
}
Do not do this if you really dont need it. It will make a mess of your code.
Upvotes: 1
Reputation: 14057
Do you mean you need to access it from elsewhere in your code? It may be an idea to refactor that section to it's own method then call that method whenever you need to access it (including in the Click event)
Upvotes: 7