我如何附加一个事件处理程序在运行时创建ASP.NET控件? [英] How do I attach an event handler to an ASP.NET control created at runtime?
问题描述
早上好,大家好。
我有控制和事件处理相连的问题。可以说,我想创建一个的LinkButton
。
I have a question connected with controls and event handling. Lets say I want to create a LinkButton
.
protected void loadLinkButton()
{
ContentPlaceHolder content = (ContentPlaceHolder)this.Master.FindControl("MainContent");
LinkButton lnk = new LinkButton();
lnk.ID = "lnikBtn";
lnk.Text = "LinkButton";
lnk.Click += new System.EventHandler(lnk_Click);
content.Controls.Add(lnk);
}
下面是事件处理程序:
protected void lnk_Click(object sender, EventArgs e)
{
Label1.Text = "ok!";
}
如果我跑在的Page_Load
的 loadLinkButton
功能一切正常。但是,当我尝试运行 loadLinkButton
单击简单的按钮,则会创建链接按钮,但事件没有被处理。
If I run the loadLinkButton
function inside Page_Load
everything is ok. But when I try to run the loadLinkButton
by clicking simple button, link button is created but event is not handled.
protected void Button1_Click(object sender, EventArgs e)
{
loadLinkButton();
}
我有什么办法解决呢?或loadLinkButton必须始终再生的的Page_Load
, Page_init
等。
推荐答案
在使用动态控制的工作,我随时添加在控制 Page_Init ,因为视图状态会加载初始化后发生的权利。如果你将它添加到Page_Load中,还有就是你将失去的ViewState的机会。只要确保你提供了一个独特的控制ID。
When working with dynamic controls, I always add the control in Page_Init, because viewstate loading will happen right after Init. If you add it to Page_Load, there is a chance that you will lose viewstate. Just make sure you provide a unique control ID.
这篇关于我如何附加一个事件处理程序在运行时创建ASP.NET控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!