ASP.NET : Run before Page_Load of parent page - c#

I have a piece of code in a User controls that normally should be put in the Page_Load (initializes other components such DropDowns etc.) but I need this to happen before the Page_Load of the page that hosts this control.
I tried to put this in Page_Init:
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
Methods.PopulateWhatList(cboWhatList0, cboWhatList1, fldWhat, Request["WhatId"], true);
Methods.PopulateWhereList(cboWhereList0, cboWhereList1, fldWhere, Request["WhereId"], true);
Methods.PopulateWhoList(cboWho, true, Request["WhoId"]);
Methods.PopulateWhenList(cboWhen, true, Request["WhenId"]);
Methods.PopulatePriceRangeList(cboPriceRange, true, Request["PriceRangeId"]);
}
}
...but have experienced some problems. So where is the best place to but this type of code?
The problem I'm having (and might be unrelated) is that my:
protected override void Render(HtmlTextWriter writer)
{
Methods.EnableValidationWhereList(cboWhereList1, this.Page);
Methods.EnableValidationWhatList(cboWhatList1, this.Page);
base.Render(writer);
}
Isn't called on certain postbacks? (When pressing a LinkButton?)

I'll try a wild guess to what you're trying to do and suggest a solution:
In your Page_Init you're populating the contents of various controls on the page. You're dependent on URL parameters, hence the if(!IsPostBack) clause.
After Page_Init, some of your controls are left in a disabled state, hence the need to enable them in your Render method.
When doing a postback on the LinkButton, you don't see your dropdowns populated on the next page rendering.
What you're experiencing is that disabled controls doesn't get persisted to the ViewState. Since the SaveViewState is called before Render, you're enabling the controls too late in the page lifecycle.
If you instead move your Methods.EnableValidation... calls to a Pre_Render method on your page, control state will get persisted to the ViewState.
After that fix, you should move your code in the Page_Init method to the Page_Load method, where it belongs. That way your controls data will have been loaded from the ViewState if you're on a postback.

The page lifecycle is such that the page_load of the page runs before the page_load of the controls.
If you need to initialise your data sources prior to page load then you can put that initialisation in OnInit provided you ensure the base.OnInit() is called first. Ideally, you should keep your databind calls to the page_load mechanism to ensure you don't have issues with viewstate.
Regarding your render method. What purpose do the 'enable' methods serve in the overall page lifecycle?

Related

"Extender controls may not be registered after PreRender" when dynamically creating controls in GridView

Here's some background to help better understand the problem:
The company I work for makes x-ray scanners for security purposes. We have a page in our web app for viewing current scan activity. Currently, it's set to refresh every minute. I've been tasked with reworking the page so that it's event driven, refreshing every time a scan is saved. The information is displayed in a GridView, which is inside an update panel. The first column contains a thumbnail image of the scan, and an Ajax HoverMenuExtender for the purpose of enlarging the thumbnail when the cursor hovers over it.
When the page loads, everything works fine. I assume this is because all the extenders are created before the OnPreRender event is handled. Upon my scan event being fired, however, it fails when the GridView.DataBind() method is called. I assume this is because the OnPreRender event already occurred when the page first loaded and, as the exception says, extender controls may not be registered after prerender.
I've done a lot of digging on this exception, but have yet to find a solution that works. I read that moving the ToolkitScriptManager to the master page can fix it, but it's already on the master page. I also tried overloading the OnInit and OnPreRender handlers as follows:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (this.DesignerMode)
{
this.EnsureChildControls();
}
this.Page.RegisterRequiresControlState(this);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
}
I tried putting that on the current activity page, the master page, and the base page, all to no avail.
I've come across slews of answers simply saying to register the controls before the prerender, which of course makes sense, but since new controls are being created dynamically upon event trigger after the initial page load, how can I accomplish that? Unfortunately, I just don't understand this well enough to know what else to try.

prevent the page to post back on button click while event will work

I have written a code in VB.NET in which there are around 300 asp controls and all of them are creating dynamically with more than 6 condition per control (like If control = dropdownlist then some code Elseif control = radiobuttonlist then some other code).
Now I want to write events for some controls but due to postback, when event is fired all of the controls are getting flushed.
When I set button1.onclientclick="return false" for button, the page stopped post back but the event also stopped working.
I have an option to save the values of controls in view state then recreating the controls and then refill the values to dynamic controls. This option will increase my line of execution.
Is there any other method though which I can prevent the page to post back on asp control event so that my asp control persists with entered values in it and also my event will work.
this is the Code1
this is the Code2
Create your dynamic controls OnPreInit Event of Page, Hope this solves your problem
override protected void OnPreInit(EventArgs e)
{
CreateDynamicControls();//Function which creates all dynamic controls
}
I have used JavaScript and Ajax to achieve my requirement.
I have called JS function for button's onclick and Textbox's onchange (like: btn1.Attribute.Add("onClick",JSFunction(); return false;) [return false is to prevent postback].
Then I used ajax post method to do my stuff on .vb page.

Login-check: Page_Load vs Page_PreRender? asp.net

I got a website where you must be logged in to access it, however, if the user lost the Session "loginID", the user should be kicked out immediately by a if(Session["LoginID"] == null) via MasterPage. But since im new to HTML/asp.net, Im not sure where I should actually have it, in Page_Load or Page_PreRender.
Does it even matter which one I have it in?
Using asp.net/c#
Thanks.
You can use Page_PreInIt event for your problem to check if session is live or ended
protected void Page_PreInIt(object sender,EventsArgs e)
{
if(Session["LoginID"] == null)
{
// redirect to login if session is null
Response.Redirect("Login.aspx");
}
}
Page Load:
The Page object calls the OnLoad method on the Page object, and then
recursively does the same for each child control until the page and
all controls are loaded. The Load event of individual controls occurs
after the Load event of the page
Page PreRender
Raised after the Page object has created all controls that are
required in order to render the page, including child controls of
composite controls. The Page object raises the PreRender event on the
Page object, and then recursively does the same for each child
control. The PreRender event of individual controls occurs after the
PreRender event of the page
Read More

On the same Page When I click Save_button, firstly Page_Load event should execute or btnSave_Click button?

In my Asp.Net Web Form,
Assuming that, I have Main_page and Save_button that it is on Main_page.
When I click Save_button, firstly Page_Load eventexecute and after this btnSave_Click button execute.
I thought that when I click button firstly and only button might execute.
Is it correct or my program doesn't work correctly ?
It is normal that Page_Load is executed first and event handlers afterwards. So your program behaves as designed.
Excerpt from MSDN on the page lifecycle:
Load
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.
Postback event handling
If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page. (There is an exception to this sequence: the handler for the event that caused validation is called after validation.)
If you are interested in details on the lifecycle of an ASP.NET Page, have a look at this link.
Resolution
If you need to perform certain steps in Page_Load (or any other method on your page) only when the page is requested first, you can check the IsPostBack property and thus make your program behave as you describe in your question:
public void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Steps are only run on initial GET, not when request is a PostBack.
}
}
It is correct that load event fires first then button event handler. If you want to execute code only at first, but not when any postback check IsPostBack property.

How can I use the PreLoad event from within a control?

I am trying to modify a control on a page to reduce session dependence. I currently do not have access to the page itself, only the control which primarily consists of a DataGrid. I am trying to retrieve the DataGrid information on postback so I can manipulate the data and rebind the grid.
The issue is that the page is calling a databind on the control before I can retrieve the data. (actually it is calling the databind on the tab control where my control is located.) This call is happening on the OnLoad event of the page, before the OnLoad of the control is called. I saw that the is a PreLoad event that occurs after the viewstate is loaded but before the OnLoad is called. However I am having issues accessing this event from my control. Is there anyway I can access this event so I can retrieve the data before the page overwrites it?
Add the following code to your control instead of the OnLoad. (from here)
protected override void OnInit(System.EventArgs e)
{
// this assigns Page_PreLoad as the event handler
// for the PreLoad event of the Control's Page property
this.Page.PreLoad += Page_PreLoad;
base.OnInit(e);
}
private void Page_PreLoad(object sender, System.EventArgs e)
{
// do something here
}
This might help: MSDN - ASP.NET Page Life Cycle Overview
The image 1/3 of the way down sums it up.

Categories

Resources