Problem with dynamic controls in .NET

前端 未结 9 1123
迷失自我
迷失自我 2020-12-13 07:50

Problem with dynamic controls

Hello all,

I\'m wanting to create some dynamic controls, and have them persist their viewstate across page loads. Easy enough,

相关标签:
9条回答
  • 2020-12-13 08:11

    ViewState works on the Page and its child objects. The new control in [Case 2] has not been added to the Page (or any of its children). In fact, in case of the code above, the object will be out of scope as soon as the OnPreRender method ends and will be garbage collected.

    If you absolutely have to swap out the control, you will need to remove the old control from its parent using Remove() method and add the new control at the right place using AddAt().

    If the control was the only child of the parent, the code would be something like the following.

    ValueLinkButton tempLink = new ValueLinkButton();
    Control parent = FindControl("valueLinkButton").Parent;
    parent.Remove(FindControl("valueLinkButton"));
    parent.AddAt(0, tempLink);
    
    0 讨论(0)
  • 2020-12-13 08:12

    I believe that once you have added the dynamic controls to the page in PageLoad, the ViewState is bound to the controls and the "ViewState still needs to be bound" flag (in concept, not an actual flag) is cleared. Then, when you recreate the controls, the existing ViewState is no longer bound.

    I faced something similar last year, only in my case I did not want the ViewState to rebind. My issue is that I was not recreating the previous controls, which is why I think that the pseudo-flag notion above applies.

    0 讨论(0)
  • 2020-12-13 08:23

    I'm already re-creating the controls in my OnLoad event.

    That's your problem. OnLoad is too late. Use Init instead.

    0 讨论(0)
提交回复
热议问题