简体   繁体   English

ASP.NET中的动态按钮-未触发EventHandler

[英]Dynamic button in asp.net - EventHandler is not fired

I created a button from code behind: 我从后面的代码创建了一个按钮:

Panel dynamicPanel = new Panel();
Button dynamicButton = new Button();
dynamicButton.Text = "View";            
dynamicButton.Click += new EventHandler(dynamicButton_Click);
dynamicPanel.Controls.Add(dynamicButton);
dynamicDiv.Controls.Add(dynamicPanel);

and the OnClick method: OnClick方法:

protected void dynamicButton_Click(object sender, EventArgs e)
{
    Response.Write("view button response");
    string script = "alert(\"view clicked.\");";
    ScriptManager.RegisterStartupScript(this, GetType(), 
        "ServerControlScript", script, true);
}  

When I click the button, there is postback (IsPostback with Javascript alert) but the EventHandler is not fired. 当我单击按钮时,会有回发(带有Java警报的IsPostback),但不会触发EventHandler。 I can say that content that was visible on the page disappears if that is a clue. 我可以说,如果有线索,页面上可见的内容就会消失。

I need to create this in a custom protected void method. 我需要在自定义受保护的void方法中创建此文件。

Your code looks a bit weird to me, but as for the problem "When I click the button, the method is not fired": Try renaming the method dynamicREGButton_Click() to dynamicButton_Click() . 您的代码对我来说似乎有些奇怪,但是对于问题“当我单击按钮时,不会触发该方法”:尝试将方法dynamicREGButton_Click()重命名为dynamicButton_Click()

I assume you have a method dynamicButton_Click() in your code already; 我假设您的代码中已经有一个dynamicButton_Click()方法; otherwise, you could not compile. 否则,您将无法编译。 However, the method you register via dynamicButton.Click += new EventHandler(...); 但是,您通过dynamicButton.Click += new EventHandler(...);注册的方法dynamicButton.Click += new EventHandler(...); is the method you call. 是您调用的方法。 The code you showed us doesn't match in that regard. 您向我们展示的代码在这方面不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM