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 code-behind:
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.
Page_Loadfires beforebtnSubmit_Click.If you want to do something after your postback events have fired use
Page_PreRender.The basic order goes: