c# - 如何让按钮处理 OnClick 事件?

标签 c# asp.net

我一直在 ASP.NET 中创建多个自定义控件 - 主要是为了练习和更深入地了解该语言。

我一直在摆弄一个按钮,但我似乎无法让它处理自己的 OnClick 事件。谁能帮帮我吗?

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.
    }
}

最佳答案

您应该重写 OnClick 方法:

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.

关于c# - 如何让按钮处理 OnClick 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18672240/

相关文章:

c# - 如何在 mvc5 中将文化设置为全局

javascript - 单击父节点时显示子节点并隐藏父节点

c# - ASP.NET MVC : Requested registry access denied when creating performance counters

.net - 通过 DataReader 两次

c# - RadioButtonList 在 doPostBack 之后不会更改 - ASP.NET JS C#

c# - Azure Functions #r 仅允许在脚本中使用

c# - 如何在 View 模型中存储 linq 查询结果

c# - 故障转移后连接到镜像数据库

asp.net - Visual Studio 2015 的项目模板

c# - 如何处理 CSV 文件中的引号?