4

I'm building a button in my code behind file and want to bind the click function to an existing click function of a different button. How do I handle this? I was hoping for something simple like:

Button b = new Button();
b.onClick = otherClickEvent();

but apparently that's not doable. Am I missing something here. I'm aware of OnClientClick, but that only deals with the JS side of things apparently.

4 Answers 4

17
Button b = new Button();
b.Click += new EventHandler(b_Click);

and later on the page

private void b_Click(object sender, EventArgs e)
{
    your code
}
Sign up to request clarification or add additional context in comments.

1 Comment

Note this has to be set on every load, even during the postback itself. I had it behind my usual page load's if postback, return, and it didn't work.
6

b.OnClick += otherClickEvent;

To add event handlers in C#, use +=. To remove them, use -=.

Comments

3

AJ is almost correct here. You can use Method Group Conversion syntax for this and write it like this:

b.OnClick += otherClickEvent;

1 Comment

Oops! Right you are. Editing my answer.
0

In VB.NET use

AddHandler btn.Click, AddressOf FunctionName

instead

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.