ge1serf
ge1serf

Reputation: 25

Dynamic control creation

I read about the dynamic control creation in ASP.NET this piece of text:

...When using dynamic controls, you must remember that they will exist only until the next postback. ASP.NET will not re-create a dynamically added control. If you need to re-create a control multiple times, you should perform the control creation in the Page.Load event handler. This has the additional benefit of allowing you to use view state with your dynamic control. Even though view state is normally restored before the Page.Load event, if you create a control in the handler for the Page.Load event, ASP.NET will apply any view state information that it has after the Page.Load event handler ends. This process is automatic ...

I wanted to try it on example create a button declaratively -

<asp:Button ID="Button1" runat="server" Text="Button" 
             onclick="Button1_Click"  />

and dynamically on behind code 5 checkboxes -

protected void Page_Load(object sender, EventArgs e)
{
  for (int i = 0; i <= 5; i++)
    {
      var chBox = new HtmlInputCheckBox();
      Controls.Add(chBox);
    }

}

But when i check some checkboxes and hit the button, after postback all checkboxes states are erased. It mean ASP.NET does not manage view states of dynamic controls automatically? I tried to enable view state to each of checkbox and for whole page, but its doesn't work. Can someone explain: 1. Why is it so? 2. How to avoid this?

Upvotes: 0

Views: 842

Answers (4)

ge1serf
ge1serf

Reputation: 25

As I understand - there is no matter where to create controls in OnInit or OnLoad (but some books suggests in onLoad), the matter is where to place them - if you place through Controls.Add - it place them out of <form></form> so postback does not takes control's states. after cretating a placeholder inside <form></form> and add dynamic controls to this placeholder everthing start to work fine.

Upvotes: 0

Kirtan
Kirtan

Reputation: 21695

The controls can be created on Page_Init.

protected void Page_Init(object sender, EventArguments e)
{
  //Generate the checkboxes dynamically here.
  CheckBox c;
  for (int i = 0; i < 5; i++) {
    c = new CheckBox();
    c.ID = "Checkbox" + i.ToString();

    divContainer.Controls.Add(c); //create a div with runat="Server" attribute or use an asp:Panel, etc. container controls.
  }
}

After that, try clicking the button again, the state will be always be maintained.

Upvotes: 0

Jason Coyne
Jason Coyne

Reputation: 6636

You must set an ID for each dynamic control so that they can be synchronized across postbacks.

Upvotes: 0

Andrew Hare
Andrew Hare

Reputation: 351456

The reason this is happening is because in order for ASP.NET to restored POSTed values, those controls need to be a part of the page before Load. In order to make this work you need to (if possible) create your controls OnInit of the page.

Upvotes: 2

Related Questions