Page_Load in C# - c#

I am working with C# web application. I want to know deeply about the page events. Because I thought that the page load event happens first (when a page is requested in browser). But when I tried with commenting the method protected void Page_Load(object sender, EventArgs e) the page get loaded without error.

off-course your webpage will work even if there is no Page_Load() method.
Before a Page_Load() events like PreInit, Init() etc are called. Refer to page life cycle.
Page_Load() method is called after a preLoad event. With Page_Load() you can set default values or check for postBacks etc.
protected void Page_Load(object sender, EventArgs e)
{
int x = 10;
}
write this and put a break-point on int x = 10; watch sender and e.

Every Page object has nine events, most of which you will not have to worry about in your day to day dealings with ASP.NET. The three that you will deal with the most are:
Page_Init
Page_Load
Page_PreRender
They do execute in the order given above so make sure to take that into consideration, especially when building custom controls. The reason you have to keep this in mind is because information might not be available when you expect if you do not deal with it appropriately.
Refer: Life Cycle

1.Page request
2.Start
3.Initialize
4.Load
5.Postback Event Handling
6.Rendering
7.Unload
This is the page life cycle.
Load event comes at 4th position.
You can check details over here:
http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.100%29.aspx

Related

Invoking a method from the parent page after user control has been loaded?

May I know if there is any way to invoke a method from the child page(.aspx) after the page load of the user control is finished?
Right now I have an issue of being unable to retrieve the value from the child page because the variables from the user control has not been assigned the value yet.
To put it simply
FROM MY .ASPX FILE
Page_Load(object sender, EventArgs e)
{
x = getValueFromUserControl();
}
FROM MY USER CONTROL
Page_Load(object sender, EventArgs e)
{
int x = getvalueFromDatabase();
}
getValueFromuserControl()
{
return x;
}
Since the ASP.NET Life Cycle goes from the child page(.aspx) page_load -> user control page_load, I am unable to retrieve the value of x.
That said, ideally I would not like to put the function in the child page and call it from the user control as the user control is being used in other pages.
In short, I would like to invoke a method from my .aspx page after the page_load in my user control ends, Thank you!
Get the value at a later page event:
protected override void OnLoadComplete(EventArgs e) {
x = getValueFromUserControl();
}
Unless, of course, there is a specific reason why you must get the value on Page_Load. There are other, probably more appropriate ways to handle this, but without knowing what x is and what you need to do with it, it is hard to give any other advice. For example, maybe the UserControl should fire an event that is handled by the page.

DropDownList stuck after using .SelectedValue on him ASP.NET

I'm new with asp.net and i think this is really easy question, but i can't find the answer. I have a DropDownList on my page (that will be page A), one of the ways to go to that page is follow the link on the other page (page B). By this link i deliver some parameters, so i use them in the Page_load of page A:
protected void Page_Load(object sender, EventArgs e)
{
string strStatus = Request.QueryString["status"];
DListStatus.SelectedValue = strStatus;
}
But after it i couldn't choose something else exept this value, sometimes i saw that for a second new item is selected, but then in a blink of an eye it turns back to that preloaded one. I thought that .ClearSelection() will hepl, but it isn't (or maybe i use it in a wrong place). So i really wonder what to do and will really appreciate your help
One of the most important things you need to know about ASP.NET is the page life-cycle. There is plenty of help on the internet for this. Here is a quick link: http://blogs.msdn.com/b/aspnetue/archive/2010/01/14/asp-net-page-life-cycle-diagram.aspx.
Notice that the Page_Load event is fire before any event handling. This means that if you are using an event handler to catch changes in the dropdown your current code will reset it to the query string value first.
Of course that is a very big problem so ASP.NET has added a Page.IsPostBack property to help. This will be true only one the first load of the page and false for all event handling postbacks. Using this information you can tweak your routine to only apply the value when IsPostBack is false.
if (!Page.IsPostBack)
{
string strStatus = Request.QueryString["status"];
DListStatus.SelectedValue = strStatus;
}
Check if is it is a post back
if (!Page.IsPostBack)
{
string strStatus = Request.QueryString["status"];
DListStatus.SelectedValue = strStatus;
}
When you select a new item, does it invoke a post-back to the server? Possibly for a SelectedIndexChanged event?
If so, you're clobbering the selected value on each post-back. Page_Load gets invoked a lot. Any time the page does anything server-side, basically. It's part of the page lifecycle for everything the page does. So every event on the page (button click, selected index changed, etc.) is going to run the code in Page_Load before it runs any event handler code.
To avoid clobbering this value, you can wrap this code in a conditional to check if this is an initial page load vs. a triggered post-back:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strStatus = Request.QueryString["status"];
DListStatus.SelectedValue = strStatus;
}
}

textbox does not accept a value in asp.net

This code a have written for an asp.net website, v2005
System.Web.UI.WebControls.TextBox txtEFName = new System.Web.UI.WebControls.TextBox();
phFname.Controls.Add(txtEFName);
placeHolder1.Controls.Add(TextBox1);
This code when executed, always shows the value of the textbox "" even if I enter some string.
Please help.
Dynamic controls need to be re-created each time the page loads. So you need to have that code execute during the Page_Init event. Note: You need to assign a unique ID for this control that stays the same each time the page loads.
Why all this?
Because the control is not contained in the markup (the .aspx file), you need to add it again every time the page loads. So how does it retain its value? The value will be stored in the ViewState, and as long as the control has the same ID it will be repopulated with the correct value.
To keep things running smoothly, let's put the code for adding the control in a separate function.
Private void AddMyControl()
{
System.Web.UI.WebControls.TextBox txtEFName = new System.Web.UI.WebControls.TextBox();
txtEFName.ID = something unique;
phFname.Controls.Add(txtEFName);
}
So we can call it from both the click handler and the Page_Init handler, but we only need to call it in the Page_Init if we have already clicked. So let's store that as a flag inside a Session variable (you can also store it in the ViewState if you like, but let's keep it that way for now). So our click handler will now look something like this:
void ButtonSomething_Click(Object Sender, EventArgs e)
{
AddMyControl();
Session["MyControlFlag"] == true;
}
Now we need our Page_Init handler:
Public void Page_Init(Object Sender, EventArgs e)
{
if(Session["MyControlFlag"]!=null && (bool)Session["MyControlFlag"])
AddMyControl();
}

Do we have any event in asp.net where controls are not initialized

I want to redirect to a page without performing any task on the present page. I think it would be good, if I redirect without loading any control on the page. So I need an event, where controls have not been initialized yet.
I think you might be looking for PreInit event, Please have a look at
Life-Cycle Events
You might try one of the application-level events in Global.asax - for example Application_BeginRequest. Something like
void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Url.AbsolutePath.Contains(...))
{
Response.Redirect("SomePage.aspx");
}
}

c# updatepanel with timer page_load

I'm experimenting with some AJAX now. I have a custom control which appears on my masterpage in which there is an update panel and a timer. The timer fires and the panel updates and everything is dandy. Except that there are some operations that I don't want it to perform on every refresh. It seems like the entire page lifecycle happens with each refresh. There are variables I want to set, and keep their value on the refresh. Is there a way to make it perform ONLY what's in the timer_tick call?
You could take a look at Request["__EVENTTARGET"] in the page load event to see what control caused the postback. If it's the timer control, jump out of the function.
Assuming your timer is called "refreshtimer":
protected void Page_Load(object sender, EventArgs e)
{
if (Request["__EVENTTARGET"] == "refreshtimer")
{
return;
}
// etc
Not sure what what an AJAX.Net post back looks like to, But I usually protect my other controls and content by checking for post back;
protected void Page_Load(object sender, EventArgs e)
{
// if its a post back then my controls should already be setup...
if (!Page.IsPostBack)
{
InitControlData();
}
}
and then it should fall thru to your event handling?
protected void timer_tick(object sender, EventArgs e)
{
// Do my Ajaxy work~
}
UpdatePanels always force the entire page to refresh. If you want only a certain portion of the page to be processed (and it's a fixed size) then you could try using an iframe.
Alternatively, if you want to save the variables you can either put them in ViewState or SessionState so that they are persisted between postbacks
This is not possible with UpdatePanels... the entire page will go through the entire lifecycle. As others mentioned, you can limit the processing that happens by using IsPostBack or ScriptManager's IsInAsyncPostBack, but ultimately this is not going to be a great solution for complex pages.
However, you can use Page Methods to execute just one static method in your page, but you'll have to make the Javascript call yourself and update the UI. Here are some examples:
http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
http://encosia.com/2009/07/21/simplify-calling-asp-net-ajax-services-from-jquery/
http://weblogs.asp.net/craigshoemaker/archive/2008/09/29/using-jquery-to-call-asp-net-ajax-page-methods.aspx

Categories