[英]C# ASP Add custom behavior to every System.Web.UI.WebControls.Button.OnClick event
I want to run some code every time an instance of System.Web.UI.WebControls.Button is clicked. 我想每次单击System.Web.UI.WebControls.Button的实例时运行一些代码。
Is there a way I can drop this functionality into the default OnClick method for the button class, or will I have to make a new class that inherits from System.Web.UI.WebControls.Button? 有没有办法可以将此功能放到按钮类的默认OnClick方法中,还是必须制作一个继承自System.Web.UI.WebControls.Button的新类?
For example everytime I click a button, I want the code 例如,每次我单击按钮时,我都需要代码
Debug.WriteLine ("hello world")
// other code here
to run, but do not want to declare all that code in the OnClick method of every button on my page 运行,但不想在我页面上每个按钮的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
}
Thanks to Mike Cheel who confirmed that I do indeed need to make a new class to achieve this 感谢Mike Cheel,他确认我确实确实需要参加新的课程才能实现这一目标
public class MyButton : System.Web.UI.WebControls.Button
{
protected override void OnClick(EventArgs e)
{
Debug.WriteLine("hello");
}
}
which is then instantiated in the designer file 然后在设计器文件中实例化
protected global::WebApplication7.MyButton Button1;
and in the cs file for the page I can add my button specific behaviour 在页面的cs文件中,我可以添加按钮的特定行为
protected void Button1_Click(object sender, EventArgs e)
{
Debug.WriteLine("Goodbye");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.