How can I call (web) Button.Click in C #?

As a name really, I'm in one part of my code and I would like to call any methods that have been added to the Button.Click handler.

How can i do this?

+1


source to share


4 answers


Do you mean that you need to access it from somewhere else in your code? Maybe an idea to refactor this section to your own method and then call that method whenever you need to access it (including in the Click event)



+7


source


TO AVOID. Indeed. It looks like you are handling important logic in your event handler.



Move the logic out of the handler.

+4


source


You can do this through 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);

      

+2


source


You will need an event to act as a proxy, but you are 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)
    {

    }

      

Don't do this unless you really need to. This will make your code a mess.

+1


source







All Articles