Problem with dynamic controls in .NET

前端 未结 9 1190
迷失自我
迷失自我 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);
    

提交回复
热议问题