How to persist a dynamic control (c#)

久未见 提交于 2019-12-01 10:47:28

问题


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.

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.


回答1:


You should recreate dynamic controls on every postback. The best place to do that is method 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" });
        }
}

And btn handler

private void OnShowControlClick(object sender, EventArgs e)
{
         ViewState["AddControl"] = true;
         ChildControlsCreated = false;
}



回答2:


Usually for dynamic controls, they will have to be added on every postback and also the events need to be wired up every time.




回答3:


I believe all you need to do is recreate it with the same ID during pre init and the asp.net engine will populate it from the view state.

This is off the top of my head, so I might have the details off a bit.




回答4:


As with all HTML pages, the control must be recreated on each page request. ASP.NET handles a lot of this 'under the hood' with mechanisms such as ViewState and Session.

If your control is not (or can't be) tracked by ViewState, then you need to handle this yourself.

I don't know how complex your control is, but as a starting point you may wish to read up on handling the CreateChildControls event here (MSDN)



来源:https://stackoverflow.com/questions/5567707/how-to-persist-a-dynamic-control-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!