Question

How to avoid overriding?

 public partial class test : System.Web.UI.Page {
    StringBuilder sb = new StringBuilder();

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            sb.Append("one");
            lbl.Text = sb.ToString();
        }

    }
    protected void cmdSb_Click(object sender, EventArgs e)
    {


        sb.Append("two");
        lbl.Text = sb.ToString();

    } }
Was it helpful?

Solution

Remember, every time you do any postback, even if it's just to handle an event, the full page life cycle will run. To help understand this, you can think of your code as if it were all in one big function, more like this:

public partial class test : System.Web.UI.Page
{
    // Page_Load runs for EVERYTHING
    protected void Page_Load(object sender, EventArgs e)
    {
        // -- Constructor Area
        StringBuilder sb = new StringBuilder();

        // -- Page Init Area

        // -- ViewSate is loaded

        // -- Page Load Area
        if (!IsPostBack)
        {
            sb.Append("one");
            lbl.Text = sb.ToString();
        }

        // -- Validation controls are checked

        // -- If valid, start handling events

        // Handle your click event
        if (cmdSb_Clicked)
        {
            sb.Append("two");
            lbl.Text = sb.ToString();
        }


        // -- DataBinding Area

        // -- Save ViewState           

        // -- Render Page: the class is turned into html that is sent to the browser

        // -- Unload -- Page is disposed

    }
}

Of course this isn't what actually happens, but starting thinking of it like this and you're on the right track. In this case, note that your click event will never run at the same time as your !IsPostBack code, but you're using a new StringBuilder every time.

Check here for more information on the page lifecycle:
http://msdn.microsoft.com/en-us/library/ms178472.aspx

OTHER TIPS

ASP.NET is stateless, which means your StringBuilder instance will not persist through the PostBack unless you save it to something like viewstate or session state.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top