1

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?

4 Answers 4

7

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Well this is actually what I have done so far but I was just wondering if it was possible really.
4

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

Move the logic out of the handler.

Comments

2

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);

3 Comments

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 ;)
yeah i agree, i wasn't passing judgement on what the OP actually wants to do - merely suggesting a possible solution ;)
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.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.