Last post Nov 22, 2011 12:51 AM by milanbetter
Nov 20, 2011 05:52 PM|milanbetter|LINK
I have noticed some strange behavior when PlaceHolder is used to dynamicly load controls. I suspect to some kind of BUG or behaivor at design. ViewState is lost when control Text property is assigned before control is added to PlaceHolder.
Let me explain: When line of code:
PlaceHolder1.Controls.Add(lb) is before assigning Text property:lb.Text = "SOME TEXT",
system works well and ViewState is normaly read after postback. But then
PlaceHolder1.Controls.Add(lb) is after lb.Text = "SOME TEXT", ViewState fails to run correctly and lb.Text is lost after PostBack.
I use Asp.Net 3.5 (Visual Studio 2008 SP1).
Here are sample of not working code, but if you move PlaceHolder1.Controls.Add(lb) just before lb.Text assgning it will works fine.
Default.aspx.cs and Default.aspx are
public partial class _Default : System.Web.UI.Page
protected void Page_Init(object sender, EventArgs e)
Label lb = new Label();
lb.Text = "SOME TEXT";
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<form id="form1" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="btSubmit" runat="server" Text="Submit" />
Nov 21, 2011 08:48 PM|atconway|LINK
ViewState fails to run correctly and lb.Text is lost after PostBack
Just remember that dynamically created controls will always be lost after postback regardless if using a PlaceHolder or not. You will need to recreate them and add them back to the Placeholder on every postback. I suggest in the Page_OnInit() event or somewhere
similar. Have a look to the following for additional information:
As far as the order of instantion, assignment of properties, and being added to the Placeholder, the MSDN does it in exactly the aforementioned order. Take a look to the following for a code example:
How to: Add PlaceHolder Web Server Controls to a Web Forms Page:
I think the behavior you are seeing is by design and might be where you are doing the assignment. You should really have your code in the OnInit() event. The following post highlights a similar issue that you are having:
Dynamically Loaded Control can not maintain values at PostBack?
"Figure 4 illustrates the sequence of events that transpire, highlighting why the change to the Label's Text property needs to be stored in the view state."
Understanding ASP.NET View State (above excerpt):
If you really think there is a reproducible bug and its not by design, you can report it to Microsoft Connect below:
Hope this helps!
Nov 22, 2011 12:51 AM|milanbetter|LINK