suman
suman

Reputation: 728

Is it possible to call a function after Page_Load event?

I have this page say test.aspx.Its codebehind is like the code below.

protected void Page_Load(object sender, EventArgs e)
{

}

public void display()
{
   // some block statements
}

Since the function display() is outside the Page_Load it is never called. So how do I make this call to this function after Page_Load.

NOTE: I need this function outside the Page_Load.

Upvotes: 2

Views: 24477

Answers (3)

The Hungry Dictator
The Hungry Dictator

Reputation: 3484

If you want to load that function on the time of load only then do like this

protected void Page_Load(object sender, EventArgs e)
{
    if(!isPostBack)
    {
        display();
    }

}

public void display()
{
   // some block statements
}

as this will load only once. But if u want to load it on each post back then do like this

protected void Page_Load(object sender, EventArgs e)
{
    if(!isPostBack)
    {}
    dispplay();
}

public void display()
{
   // some block statements
}

There's a default event called Page_LoadComplete which will execute when page is loaded fully But,If you write your code in a Page_Load Event that code will execute and your controls will be accessible there So best to call like in a page_load for once with first postback ;)

But, still if you want to go after page load then go for the Page_LoadComplete

  protected void Page_LoadComplete(object sender, EventArgs e)
    {
        display();
    }


 public void display()
    {
       // some block statements
    }

Upvotes: 1

DGibbs
DGibbs

Reputation: 14618

Use Page.LoadComplete:

protected void Page_LoadComplete(object sender, EventArgs e)
{
    display();
}

Upvotes: 12

Philip Pittle
Philip Pittle

Reputation: 12295

protected void Page_Load(object sender, EventArgs e) 
{
    //call your function
    display(); 
}

protected void Page_PreRender(object sender, EventArgs e) 
{
    //call your function even later in the page life cycle
    display(); 
}

public void display()
{
  // some block statements
}

Here is the documentation that discusses the various Page Life Cycle methods: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.90).aspx

After Page_Load you have:

  • PreRender
  • Render
  • Unload

Upvotes: 2

Related Questions