2

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.

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
suman
  • 728
  • 3
  • 10
  • 29

3 Answers3

12

Use Page.LoadComplete:

protected void Page_LoadComplete(object sender, EventArgs e)
{
    display();
}
DGibbs
  • 14,316
  • 7
  • 44
  • 83
2
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
Philip Pittle
  • 11,821
  • 8
  • 59
  • 123
1

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
    }
Just code
  • 13,553
  • 10
  • 51
  • 93
The Hungry Dictator
  • 3,444
  • 5
  • 37
  • 53
  • This does not answer the question. Both of your examples would still call the function in the `Page_Load` event. He needs to call it *after*. From the OP: `NOTE: I need this function outside the Page_Load.` – DGibbs Jul 15 '14 at 08:53
  • oh.. let me change then... @DGibbs and thanx for pointing it out – The Hungry Dictator Jul 15 '14 at 08:54