Quentin91360
Quentin91360

Reputation: 122

Button_click before Page_load

I am working with a generic list in a simple page containing a user control.

I populate this list by using Session variable. This Session variable is set in my Button_click event.

When user click on the button the session variable is set and a postback happens.The problem is that the Page_load is called before the Button_clicked event...As we know it's the standard page's lifecycle.

Finally,my generic List is not updated because the session variable is set after page_load.

EDIT:My session variable is set up in a function handled by a delegate on button click of my User Control.

Is there a solution to prevent this? Is there a solution to keep value of this list accross many postback withtou using session variable?

Thank you for your help,

Quentin

Upvotes: 2

Views: 1910

Answers (4)

Quentin91360
Quentin91360

Reputation: 122

I find the solution: I have to override the Pre_render function of the main page. Indeed,the lifecycle is: Page_load->Button_click->Page_PreRender.

So in my Pre_render function I can get my Session variable setted up and use it as I want.

From what I understood,the Pre_Render event is often used for initializing value of controls just before they are displayed on the Page.

Thank you for your help.

Upvotes: 1

Jeremy Howard
Jeremy Howard

Reputation: 176

You could also try moving your code from Page_Load to Page_PreRender which will fire after your button click event. This should solve the issue you are having.

Upvotes: 0

daniloquio
daniloquio

Reputation: 3902

In the Click event, you should do three things:

  1. Save your generic list to Session.
  2. Save a cookie like flag (can be a session value) signaling that the list has been saved.
  3. Resonse.Redirect(Request.RawURL) Redirect to the same page.

And in the Page_Load event you should do something like this:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Session["MyFlag"] != null)
        {
            //Perform whatever you need to do with your already saved generic list in Session
            Session["MyFlag"] = null;
        }
    }
}

If you need to store a complex object like a generic list across postbacks Session is your friend. If you need to store just a value you can use a cookie or a ASP.HiddenField, but for this you are better using Session.

Upvotes: 1

Luis Hernández
Luis Hernández

Reputation: 92

Why don't you set your session inside of:

if(!IsPostback)
{
    // your session setting here (or method)
}

So it will keep the value across the postback without setting it with every postback.

Also you can declare a method that you can easily call from the !IsPostback or your cick event.

Upvotes: 0

Related Questions