简体   繁体   中英

Viewstate issue when dynamically adding controls in ASP.net

Markup looks like this:

<form id="form1" runat="server">

  <asp:TextBox ID="txt1" runat="server"></asp:TextBox>
  <asp:Button ID="Button1" runat="server" Text="Do Something" />

</form>

Code behind looks like this:

protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack)
        txt1.Visible = false;

      Form.Controls.AddAt(0, new TextBox() { ID = "blah", Text = "blah", EnableViewState = true });
    }

The problem is that when I click on the button, txt1 becomes visible again, even though I had set it's visibility to hidden. Viewstate should have retained it's visibility to hidden but for some reason does not.

Important: This only happens when I dynamically add a control using Form.Controls.AddAt. Doing so seems to mess up the viewstate for all controls after the dynamically added control.

Any ideas why? Or how to use AddAt without messing up the viewstate for all subsequent controls on the page?

Like Stilgar said, add the control in Init() instead.

The issue is that ViewState is loaded according to controls' indices between Init() and Load(), and you're messing with the order of the controls after that point. In other words, the ViewState mechanism thinks it needs to set the second TextBox's Visible property to false, but txt1 is the first TextBox at the time it makes that evaluation.

It used to be that ViewState was loaded by a control's ID (which was a FAR superior/more predictable approach), but the ASP.NET team flubbed things up big time in more recent versions of the framework.

See here for more info on page lifecycle and ViewState: Last event in page that can still affect a page's viewstate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM