如何保持一个动态控制(C#) [英] How to persist a dynamic control (c#)
问题描述
按标题,我创建了一个自定义的控制。
As per the title, I have created a custom control.
在某个按钮单击事件,此控件实例,然后添加到页面中。
On a certain button click event, this control is instantiated, then added to the page.
这是一个动态的控制,与它自己的按钮事件。
It is a dynamic control, with it's own button events.
为了才会触发这些按钮事件,控制必须由的Page_Load
/ 的onload结束绘制
,在随后的Page_Load /的onload生命周期阶段
In order for these button events to be triggered, the control must be drawn by the end of Page_Load
/ OnLoad
, in the subsequent page_load / onload lifecycle stage.
我的问题是我怎么坚持这种控制?因为它包含非序列化的项目,我不能把它存储在会话
对象。
My problem is how do I persist this control? I cant store it in the Session
object because it contains non-serializable items.
推荐答案
您应该重新在每个回传动态控件。要做到这一点,最好的地方是方法的CreateChildControls
。
You should recreate dynamic controls on every postback. The best place to do that is method CreateChildControls
.
要动态地添加按钮单击单击处理程序设置一些标志后,控制(persistent标志 - 所以应该在ViewState中还是在的sessionState) - 它应该表明,在下一个页面创建您的控制应该被添加到它。在这之后,你应该设置 ChildControlsCreated = FALSE;
结果
在此之后的CreateChildControls被再次执行,你的控制正确地创建并持久(直到你不清楚标志)。
To add dynamically control after button click set in click handler some flag (persistent flag - so it should be in viewstate or in sessionstate) - it should indicate that on next page creation your control should be added to it. After this you should set ChildControlsCreated = false;
After this CreateChildControls are executed again and your control is created correctly and is persistent (till you not clear flag).
所以应该以这种方式来完成:
So it should be done in this way:
protected override void CreateChildControls()
{
base.CreateChildControls();
if (ViewState["AddControl"] == true)
{
Controls.Add(new MyControl() {Id = "someId" });
}
}
和BTN处理程序
private void OnShowControlClick(object sender, EventArgs e)
{
ViewState["AddControl"] = true;
ChildControlsCreated = false;
}
这篇关于如何保持一个动态控制(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!