3

我在这样的PreRender事件中动态创建一个按钮:

Button myButton = new Button();
myButton.Text = "Test";
myButton.Click += new EventHandler(myButton_Click);
myDiv.Controls.Add(myButton);

此按钮在浏览器中呈现,但是当我单击该按钮时,单击事件不会触发。我试图在PageLoad事件中创建一个相同的按钮并且它工作得很好,但是我必须在PreRender事件中创建这个按钮,因为创建这个动态按钮是否取决于我只在这个事件中获得的值。当我单击在 中创建的动态按钮时PreRender,单击事件会触发,我该怎么办?

4

6 回答 6

2

您应该在页面的 OnInit 事件中将您的按钮添加到页面,并在 OnLoad 期间或之前连接它的点击事件,然后您可以启用/禁用您的按钮或使用您在 PreRender 事件期间拥有的变量使您的按钮可见/不可见. 有关更多详细信息,请参阅 Joel Coehoorn对此问题的回答。否则,请尝试使用 PlaceHolder 控件,尽管这可能会更棘手。

protected override void OnInit (EventArgs e)
{
  Button myButton = new Button();
  myButton.Text = "Test";
  myButton.Click += new EventHandler(myButton_Click);
  myDiv.Controls.Add(myButton);

  base.OnInit(e);
}

protected override void OnPreRender(EventArgs e)
{
  myButton.Visible = myConditional;

  base.OnPreRender(e);
}
于 2012-05-04T13:09:16.677 回答
0

In PreRender you can create some var, which will tell you, that you need create button. And on Render create that button by hand with need JavaScript or with sending form. But you can't use such simple syntax as +=EventHandler, more code need.

于 2012-05-04T12:40:20.967 回答
0

According to this link from MSDN, you must add button and event related to it if needed durign the OnInit() as explained here : MSDN Lifecycle

"Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page. Use this event to read or initialize control properties."

To do so, try something like that :

protected override void OnInit(EventArgs e)
{
   // Do some stuff here
   base.OnInit(e);
}
于 2012-05-04T12:42:12.417 回答
0

You should move control creation earlier in the page lifecycle. Control events are fired after Load and before PreRender so OnLoad or anything earlier should do.

于 2012-05-04T12:42:37.420 回答
0

您应该在 preinit 阶段添加按钮,否则它不会触发

Asp 网络生命周期

将此事件用于以下 (PREINIT):

  • 创建或重新创建动态控件。
于 2012-05-04T12:37:22.567 回答
0

也许在中创建按钮并在中PreRender绑定点击事件PageLoad

于 2012-05-04T12:37:33.797 回答