2

I've been creating several custom controls in ASP.NET - mostly for practice and a deeper understanding of the language.

I've been fiddling with a button but I can't seem to get it to handle its own OnClick event. Can anyone help me out?

public class CustomButton : System.Web.UI.WebControls.Button
{
    private string href = "";

    public CustomButton(string name = "Custom Button", string link = "~/errors/404.aspx", string css = "custom_button")
    {
        this.Text = name;
        this.href = link;
        this.CssClass = css;
        //this.OnClick += redirect;
        this.Attributes.Add("OnClick", "redirect");
    }
    protected void redirect(object sender, EventArgs e)
    {
        // I want this function to redirect the user to another page.
    }
}

3 Answers 3

2

You should override the OnClick method:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclick.aspx

The OnClick method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class.

1
  • Thanks! That's much simpler than I thought it was going to be.
    – wmaynard
    Sep 7, 2013 at 10:34
0
this.OnClick+= redirect(sender,e);

Try that?

2
  • For derived classes is better to override the OnClick method.
    – Alberto
    Sep 7, 2013 at 10:20
  • 1
    Ah, did not know that. Thanks for pointing that out. Learn something new everyday.
    – Haedrian
    Sep 7, 2013 at 10:21
0

If you want to call to a javascript function you might want to try this:

this.OnClientClick = "Function()";

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.