Solved

ASP.NET - Page_PreLoad() and Page_InitComplete() events for a user control

Posted on 2009-04-09
3
2,701 Views
Last Modified: 2012-05-06
I've got a situation where I need the code in a user control to run before the page it is sitting in.  To do this I am trying to use a method other than Page_Load for the user control so the code is called and runs first.  My first attempt was to use

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
End Sub

This of course did run the code of the user control before the code on the page, however, in the code for the user control I am creating many controls dynamically and adding them to panels.  It seems that everything that is supposed to be added dynamically is missing when the code executes in the Page_Init() method.

Doing a little more research, I found the methods Page_InitComplete() and Page_PreLoad.  But neither one of these seems to work for user controls.

Any suggestions as to how I might tackle this problem?
0
Comment
Question by:josephdaviskcrm
  • 2
3 Comments
 
LVL 8

Expert Comment

by:ppittle
ID: 24108525
Try overriding the CreateChildControls method on the UserControl.  This method is called by the Page Lifecycle.   If you need to perform work on the UserControl's child controls from a Parent Control or Parent Page early on in the Lifecycle (ie Page_Load), call the UserControl's EnsureChildControls() method first.

Hope that helps,
PJ
0
 

Author Comment

by:josephdaviskcrm
ID: 24108643
The EnsureChildControls() method looks interesting.  Can you tell me a little more about it and perhaps show me a code example of how it is used?

What I've tried so far is just to put EnsureChildControls() at the top of my pages page_Load() method.  But it isn't making any difference.

Maybe the better solution would be to override the CreateChildControls method on the UserControl as you mentioned first.  But I also need a little more direction on how that works as well if you can.

Thanks.
0
 
LVL 8

Accepted Solution

by:
ppittle earned 500 total points
ID: 24108923
josephdaviskcrm,

Take a look at the Code Snippet. The example only uses the code-behind, but it can be easily adapted if you are adding controls declaratively; instead of adding the Controls to this.Controls, they'd already be there and you can work with directly.

What the example is intended to illustrate is that the UserControl exposes a Property, TimeInLabel, that the Page needs to work with. Since MyUserControl doesn't know when in the LifeCycle the TimeInLabel control might be called, it first calls the EnsureChildControls() method to ensure everything is setup correctly. It also overrides the CreateChildControls method to make sure all child controls (in this case the Label myLabel) is initialized correctly.

Let me know if you have any questions. Additionally, if you can explain more about the "situation where I need the code in a user control to run before the page it is sitting in" you mentioned in your question post, I might be able to help adapt this pattern to your context, or provide a different mechanism to accomplish the same goal.
 public class MyUserControl : UserControl

    {

        Label myLabel;

        protected override void CreateChildControls()

        {

            //Create and Add Controls.

            myLabel = new Label();

            myLabel.Text = DateTime.Now.ToString();
 

            this.Controls.Add(myLabel);
 

            base.CreateChildControls();

        }
 

        public string TimeInLabel

        {

            get

            {

                EnsureChildControls();

                return myLabel.Text;

            }

        }

    }
 

    public class MyPage : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            MyUserControl myuserControl = new MyUserControl();

            this.Controls.Add(myuserControl);
 

            //Perform Custom Logic

            if (myuserControl.TimeInLabel.EndsWith("pm",StringComparison.InvariantCultureIgnoreCase))

            {

                Response.Write("MyUserControl thinks it's night time!");

            }

 else

            {

                Response.Write("MyUserControl thinks it's day time!");

            }

        }

    }

Open in new window

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now