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

StackOverflow https://stackoverflow.com//questions/9701649

  •  13-12-2019
  •  | 
  •  

Question

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

Was it helpful?

Solution 2

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 { ...   }

OTHER TIPS

The IsPostBack property determines if the request was a POST HTTP request not if your control did anything. Because the page was submitted via a button the request is a PostBack request (in ASP.NET terms). Basically this property does not do what you think it does and in fact is not related in any way.

The button is performing a "postback". IsPostBack is true for the Page object in which the user control is being loaded.

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