Why my data is lost after postback

Eimatsu picture Eimatsu · Apr 3, 2011 · Viewed 8.7k times · Source

I have a simple form as:

        <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1"
            runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

And code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        string myVariable;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                myVariable = "abc";
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

        }
    }
}

At FormLoad, the myVariable is assigned to "abc".

At form, enter something to textbox and submit form. The myVariable's value is turned to "null"

Why my data at myVariable is lost? :(

I'm using: VS2008 SP1 Please help!

Answer

Ranhiru Jude Cooray picture Ranhiru Jude Cooray · Apr 3, 2011

A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server.

Quoted from ASP .NET State Management. I thoroughly suggest you go through the State Management features of ASP .NET.

Also, all state management features aren't meant to store everything. This is another article, that will recommend which state management feature to use for what sort of situation.