09 March 2008

ViewState in ASP.NET Embedded Code Blocks

This morning I had trouble getting an ASP.NET user control to access its ViewState on postback. The crucial trick was to populate control items in a Page_Load function not in an embedded code block. The reason is because the code block is only run at render time which happens after the ViewState has been saved.

(I had been loading the user control dynamically using LoadControl, but that turned out to be not relevant.)

Now, within a user control, suppose I have a wee label and an ineffectual button:
<asp:label id="saver" runat="server" />
<asp:button id="Button1" runat="server" text="Go" />

If the label is set using an embedded code block
<% if (!IsPostBack) saver.Text = "Am I saved"; %>
then it is not preserved/shown after the "Go" button has been pressed.

However, if it is set in Page_Load then the label text is shown correctly after "Go" is pressed.
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
saver.Text = "Am I saved";

No comments: