views:

177

answers:

2

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();

    } }
+3  A: 

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.

Mike C.
That make sens. Thanks
Rob
+3  A: 

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

Joel Coehoorn
thanks Joel for great explanation, however I still do not get it why in the example below sb.Append adding string. When button is clicked postback is fired. So should behave like previously. StringBuilder sb = new StringBuilder(); protected void Page_Load(object sender, EventArgs e) { sb.Append("one"); lbl.Text = sb.ToString(); } protected void cmdSb_Click(object sender, EventArgs e) { sb.Append("two"); lbl.Text = sb.ToString(); }
Rob
You only append "one" to the stringbuilder it it's _not_ a postback. When you're click event fires, it _is_ a postback. Are you seeing "onetwo" in this case instead of just "two", as I would expect?
Joel Coehoorn