Search code examples
asp.netcross-page-postback

User input is overridden by page_load during cross page postback


1the source page has a page load method like below:

protected void Page_Load(object sender, EventArgs e)
        {
                TextBox1.Text = DateTime.Today.AddDays(1).ToShortDateString();
        }

it will result a textbox1.text to display tomorrow's date when the source page is rendered. I have this source page cross post back to a target page, and in the target page load event i have

if (Page.PreviousPage != null && PreviousPage.IsCrossPagePostBack == true)
            {
              TextBox SourceTextBox1 = (TextBox)Page.PreviousPage.FindControl("TextBox1");
                if (SourceTextBox1 != null)
                {
                    Label1.Text = SourceTextBox1.Text;
                 }
              }

the problem is if the user changes the content of textbox1, supposely, the label1 on target page should catch the user input and display it, but now it only displays whatever i set in the source page load event. I understand the self page post back life cycle, but this is cross page post back. IMO, the source page load event has nothing to do with this, but why it overrides the user input?? Any idea.


Solution

  • Just surround this with a if(!IsPostBack) check:

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            TextBox1.Text = DateTime.Today.AddDays(1).ToShortDateString();
        }
    }
    

    Otherwise the value will be overwritten on every postback. So when you Server.Transfer it to the other page it is already changed.