views:

2542

answers:

5

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?

+6  A: 

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)

Damien
Well this is actually what I have done so far but I was just wondering if it was possible really.
John_
Yeah, It's possible as shown below :P But ideally avoided
Damien
+1  A: 

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.

Lars Mæhlum
+3  A: 

AVOID. Really. Seems like you handle some important logic right in the event handler.

Move the logic out of the handler.

+2  A: 

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);
flesh
Reflection and dynamic invoking is painfully slow, tho I guess triggering a button click isn't a repeating occurrence. And using reflection to trigger a private method results in bad karma ;)
Lars Mæhlum
yeah i agree, i wasn't passing judgement on what the OP actually wants to do - merely suggesting a possible solution ;)
flesh
I agree, you never ever want to do this in this case, refactoring is the best answer. But you do show how it could be done.
KeesDijk
+1  A: 

Thanks for the show and tell - I just borrowed it with good success!

Bruce