Solved

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

Posted on 2009-04-09
3
2,727 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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Signal R -send data to client: only if they are allowed to see it ? 1 49
Web site error 3 36
How can my static class become undefined?? 8 47
List<PaisEntity> - show some 1 23
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…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…

813 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

10 Experts available now in Live!

Get 1:1 Help Now