【问题标题】:C# ASP Add custom behavior to every System.Web.UI.WebControls.Button.OnClick eventC# ASP 为每个 System.Web.UI.WebControls.Button.OnClick 事件添加自定义行为
【发布时间】:2017-08-09 16:16:38
【问题描述】:

我想在每次单击 System.Web.UI.WebControls.Button 的实例时运行一些代码。

有没有办法将此功能放入按钮类的默认 OnClick 方法中,还是必须创建一个继承自 System.Web.UI.WebControls.Button 的新类?

例如每次我点击一个按钮,我都想要代码

Debug.WriteLine ("hello world")
// other code here

运行, 但不想在我页面上每个按钮的 OnClick 方法中声明所有代码

protected void Button1_Click(object sender, EventArgs e)
{
    //when I get here, I want the code above to have run without having to paste it all into this method
}

protected void Button2_Click(object sender, EventArgs e)
{
    //Another button, don't want to be duplicating all that code again
}

【问题讨论】:

标签: c# asp.net oop


【解决方案1】:

感谢 Mike Cheel,他确认我确实需要创建一个新课程来实现这一目标

public class MyButton : System.Web.UI.WebControls.Button
{
    protected override void OnClick(EventArgs e)
    {
        Debug.WriteLine("hello");
    }
}

然后在设计器文件中实例化

protected global::WebApplication7.MyButton Button1;

在页面的 cs 文件中,我可以添加按钮特定的行为

protected void Button1_Click(object sender, EventArgs e)
{
    Debug.WriteLine("Goodbye");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多