views:

486

answers:

1

I am trying to set a ViewState-variable when a button is pressed, but it only works the second time i click the button. Here is the codebehind:

protected void Page_Load(object sender, EventArgs e)
{
 if (Page.IsPostBack)
 {
  lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString());
 }
}

private string YourName
{
 get { return (string)ViewState["YourName"]; }
 set { ViewState["YourName"] = value; }
}


protected void btnSubmit_Click(object sender, EventArgs e)
{
 YourName = txtName.Text;

}

Is there something I am missing? Here is the form-part of the design-file, very basic just as a POC:

<form id="form1" runat="server">
<div>
Enter your name: <asp:TextBox runat="server" ID="txtName"></asp:TextBox>
<asp:Button runat="server" ID="btnSubmit" Text="OK" onclick="btnSubmit_Click" />
<hr />
<label id="lblInfo" runat="server"></label>
</div>
</form>

PS: The sample is very simplified, "use txtName.Text instead of ViewState" is not the correct answer, i need the info to be in ViewState.

+7  A: 

Page_Load fires before btnSubmit_Click.

If you want to do something after your postback events have fired use Page_PreRender.

//this will work because YourName has now been set by the click event
protected void Page_PreRender(object sender, EventArgs e)
{
    if (Page.IsPostBack)
        lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString());
}

The basic order goes:

  • Page init fires (init cannot access ViewState)
  • ViewState is read
  • Page load fires
  • Any events fire
  • PreRender fires
  • Page renders
Keith