处理动态加载的用户控件中的按钮单击事件
我有一个空白的用户控件(子控件),在 Page_Load 期间我创建了一些文本框和一个按钮。我还向按钮添加了一个事件。
然后,我从另一个用户控件(父控件)中的占位符动态加载该用户控件。 两个控件都正确呈现,但是当我单击按钮时,事件没有被触发。 关于如何处理该事件有什么想法吗?
子代码:
protected void Page_Load(object sender, EventArgs e)
{
/*... other user controls ..*/
UpdateButton = new LinkButton();
UpdateButton.ID = "buttonid";
UpdateButton.Text = "text";
UpdateButton.Click += new EventHandler(UpdateButton_Click);
this.Controls.Add(UpdateButton);
}
protected override void Render(HtmlTextWriter writer)
{
for (int i = 0; i < this.Controls.Count; i++)
{
this.Controls[i].RenderControl(writer);
}
}
public void UpdateButton_Click(object sender, EventArgs e)
{
//Do stuff
}
父代码:
protected void Page_Load(object sender, EventArgs e)
{
placeholder.Controls.Clear();
ChildControl uc = (ChildControl)LoadControl("~/UserControls/ChildControl.ascx");
placeholder.Controls.Add(uc);
}
如果我直接使用子控件(即没有父控件),则会引发并很好地处理单击事件。但是当我使用父控件时,调试器甚至不会在 UpdateButton_Click() 内命中断点。
提前致谢。
I have a blank user control (child) and during Page_Load i create some text boxes and a button. I also add an event to the button.
I then load that user control dynamically from a placeholder in another usercontrol (parent).
Both controls are rendered correctly but when i click on the button, the event isnt fired.
Any ideas on how to handle the event?
Child code:
protected void Page_Load(object sender, EventArgs e)
{
/*... other user controls ..*/
UpdateButton = new LinkButton();
UpdateButton.ID = "buttonid";
UpdateButton.Text = "text";
UpdateButton.Click += new EventHandler(UpdateButton_Click);
this.Controls.Add(UpdateButton);
}
protected override void Render(HtmlTextWriter writer)
{
for (int i = 0; i < this.Controls.Count; i++)
{
this.Controls[i].RenderControl(writer);
}
}
public void UpdateButton_Click(object sender, EventArgs e)
{
//Do stuff
}
Parent code:
protected void Page_Load(object sender, EventArgs e)
{
placeholder.Controls.Clear();
ChildControl uc = (ChildControl)LoadControl("~/UserControls/ChildControl.ascx");
placeholder.Controls.Add(uc);
}
If i use the child control directy (ie without the parent the control) the click event is raised and handled nicely. But when i use the parent control, the debugger wont even hit a breakpoint inside UpdateButton_Click().
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想我知道可能会发生什么。在您的父 Page_Load 中,您正在调用
placeholder.Controls.Clear();
这会执行您想象的操作并清除控件,包括已发生的任何事件。删除这条线会发生什么?每次回发时都会创建一个额外的吗?I think I know what might be happening. In your parent Page_Load you are calling
placeholder.Controls.Clear();
This does what you would imagine and clears the control, including any events that have occurred. What happens when remove this line? Do you get an additional one created on each postback?