Search code examples
c#user-controlsispostback

C#: Dynamic user Control IsPostback returning true event though the UC is loaded the first time


I have a Page with a Dynamic User Control in a placeholder. When I load the Page it loads a UC ( let's call it "OrigUC" ) by default. On this page I have a button , which replaced the UC with another "NewUC" . So this button postback using ajax and replaces the UC .

In the NewUC, In my Page_Load, I check for IsPostBack(), but for some reason, even though I loaded the UC for the first time it still returns me true. Why is it returning true, I thought the IsPostBack will return whether the UC since I'm checking it inside the Page_Load of the UC .Am I missing something?

Ok I now understand more the IsPostback on a user control coming from the Page it is called from... So how can I determine if it is the first time the UC is being called from the page?

Example:

If it is the first time the UC is called within the page, I need to querythe DB and also external WebS and bind the controls on the UC. If I trigger a partial postback , I do not want to query the DB and WebS again.

If (!IsUserControlPostBack) 
{ 
// Step 1 Init of UC 
// Call to DB 
// Call to WebS 
} 
else 
{ 
// A Post back occured ...  
// It can be Page who triggered it or UC and I do not want to call Step 1 again 
// DO something else. 
}

C


Solution

  • Ok I've used ViewState to store the flag that I set when loading the User Control the first time I go in.

    Hope this help another noob like me :)

        private bool IsUCPostBack
        {
            get
            {
                object o = ViewState["S2UC"];
                return o == null;
            }
            set
            {
                ViewState["S2UC"] = true;
            }
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsUCPostBack)
            {
                IsUCPostBack = true; ... } else { ...   }