PRB: Cannot Maintain ViewState on Mobile Controls That You Create Dynamically (309088)



The information in this article applies to:

  • Microsoft Mobile Internet Toolkit (MMIT)

This article was previously published under Q309088

SYMPTOMS

When you dynamically create mobile controls, the control may not render after you post back to the server.

CAUSE

The ASP.NET page framework creates statically declared controls for you automatically on every request. If you create and add controls dynamically in your code, you must create these controls in every request.

RESOLUTION

When you dynamically create mobile controls, you must re-create the control on each post back to the server.

STATUS

This behavior is by design.

MORE INFORMATION

Use the following code to reproduce this problem. This code sample dynamically creates a list control that does not render after you post back the page to the server.
<%@ Page language="c#" Inherits="System.Web.UI.MobileControls.MobilePage" %>
<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

<script runat=server>
  private void Page_Load(object sender, System.EventArgs e)
  {
    if(!Page.IsPostBack)
    {
      // Create the mobile list control.
      System.Web.UI.MobileControls.List myListControl = new System.Web.UI.MobileControls.List();

      // Create items to add to the mobile list control.
      myListControl.Items.Add("John");
      myListControl.Items.Add("Sue");
      myListControl.Items.Add("Robert");

      Form1.Controls.Add(myListControl);
    }
  }

</script>

<mobile:Form id="Form1" runat="server">
  <mobile:Command Text="PostBack" Runat="server" />
</mobile:Form>
				
This problem occurs because the list control appears within an if-else statement that checks the IsPostBack property of the page. If the code determines that the page is not posted back, the list control is created. If the code determines that the page is posted back, the control is not re-created; therefore, the control does not render after the post back.

To resolve this problem, remove the if(!Page.IsPostBack) condition.

Modification Type:MajorLast Reviewed:6/14/2002
Keywords:kbDSupport kbprb kbServerControls kbWebForms KB309088