开发者

Maintaining usercontrol state on dynamically added usercontrols

I have a page that dynamically creates multiple usercontrols on the page_init event, and adds it to a placeholder on the page.

The usercontrols themselves databind to a repeater on page_init to a collection of about 10 strings, which outputs a div for each item.

There's also a "view more" link button on the user control. When I click the "view more" button it databinds another collection to a second repeater, with even more divs.

The problem: After clicking "view more" on one of the usercontrols, if I click "view more" on another usercontrol, the "view more" data is lost on the first usercontrol. I suspect it's because I'm not re-adding the controls, so viewstate isn't re-loaded.

Anyone have any ideas or am I just way off on this one? 开发者_如何学CThank you.


Problem is you need to re-create the dynamic controls on each postback and recreate their viewstate. Take a look at this article Dynamic Web Controls, Postbacks, and View State


Stan is right.

When you click in the link a postback occurs and you lost everything

I ran across the same problem, my aproach was recreate the dinamics UserControls on every postback.

this article http://www.codeproject.com/KB/user-controls/DynamicUC.aspx shows a example, but i implement a diferent code like this:

my page have the following method which dinammicaly add the controls to an PlaceHolder.

    private void AdicionarControlesDinamicamente(int idPergunta)
{
    if (idPergunta > 0)
    {
        this.IdPerguntaAtual = idPergunta;
        PerguntaAtual = new Pergunta(this.IdPerguntaAtual);

        UserControl uc = LoadControl(PerguntaAtual.TipoResposta.CaminhoUserControl, PerguntaAtual.IdPergunta);
        phResposta.Controls.Add(uc);

        ViewState["ControlesDinamicosPerguntaCarregados"] = true;
    }
}

note this line of code ViewState["ControlesDinamicosPerguntaCarregados"] = true; i store an information tha says that the controls already have been added to page.

then a ovveride the CreateChildControls to recreate the controls

    protected override void CreateChildControls()
{
    base.CreateChildControls();

    // CHeck if the controls have been added to page, case true, i call IncluirControlesDinamicamente() again
    // The Asp.Net will look into viewstate and wil find my controls there, so "he" will recreate their for me
    if (ViewState["ControlesDinamicosPerguntaCarregados"] != null)
        if (Page.IsPostBack)
            AdicionarControlesDinamicamente(this.IdPerguntaAtual);
}

I think this help you.

PS: Sorry my english.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜