[英]How Do I Add Event Handlers to .NET Buttons Programmatically?
I'm trying to employ the strongest OOP I can muster in developing a web application, but I'm having issues adding event handlers to my objects as I create them using code. 我正在尝试使用我在开发Web应用程序时可以考虑的最强大的OOP,但是在使用代码创建事件处理程序时,我遇到了问题。 I'm sure it's a fairly simple solution that I just keep passing up, but I'm at a loss as to what to try next.
我确信这是一个相当简单的解决方案,我不断放弃,但我不知道下一步该尝试什么。 Below is some test code I've been playing with, just trying to get a button press to go do something.
下面是我一直在玩的一些测试代码,只是想按下按钮去做一些事情。
(Imagine there's a break point on the line "int i;") (想象一下,“int i”这一行有一个断点)
Button b = new Button();
b.Text = "Do Something";
b.Attributes.Add("runat", "server");
b.Attributes.Add("OnClick", "click");
form1.Controls.Add(b);
private void click(object sender, EventArgs e)
{
int i;
}
Since this is a new button created by my Page_Load, I can't just hardcode the XHTML. 由于这是我的Page_Load创建的一个新按钮,我不能只是对XHTML进行硬编码。 Debugging never hits my breakpoint.
调试永远不会到达我的断点。 I haven't had any more success with CheckBoxes either.
CheckBoxes也没有取得任何成功。
You have to subscribe to the Click
event: 您必须订阅
Click
事件:
Button b = new Button();
b.Text = "Do Something";
b.Click += click;
form1.Controls.Add(b);
private void click(object sender, EventArgs e)
{
int i;
}
By adding the onclick
Attribute to the Button's Attributes
collection, it will be rendered as an attribute on the HTML input tag. 通过将
onclick
属性添加到Button的Attributes
集合,它将呈现为HTML输入标记的属性。 In that case you could use it to execute some javascript code on the client side. 在这种情况下,您可以使用它在客户端执行一些JavaScript代码。
b.Attributes.Add("onclick", "alert('Hey')");
//Will render the button as
<input type="submit" name="x" value="Do Something" onclick="alert('Hey')">
You can do: 你可以做:
Button b = new Button();
b.Text = "Do Something";
b.Click += new EventHandler((s, ev) =>
{
int i;
});
form1.Controls.Add(b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.