Setting viewstate on postback

I am trying to set the ViewState variable when the button is clicked, but it only works the second time I click the button. Here is the code:

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 simple, like 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.Textinstead of ViewState" is not the right answer, I need the information that will be in the ViewState.

+5
source share
1 answer

Page_Loadtriggered before btnSubmit_Click.

If you want to do something after your postback events 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());
}

Basic order:

  • (init ViewState)
  • ViewState
  • PreRender
+12

All Articles