Question Change Label on Page_Load, Not After Action

VentureFree

Well-known member
Joined
Jan 9, 2008
Messages
54
Programming Experience
5-10
I'm trying to figure out if it's possible to get user input and update the display not when the data is entered, but when the page is loaded. For example, say I want the user to enter their name into a TextBox, which I will then display back to them on a Label. Usually I would do something like:
VB.NET:
Protected Sub txtName_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtName.TextChanged
    lblName.Text = txtName.Text
End Sub
And then when the page reloads the label now displays the name. What I want to do instead is put the text into a session variable and change the label in Page_Load.
VB.NET:
Protected Sub txtName_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtName.TextChanged
    Session("txtNameText") = txtName.Text
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    lblName.Text = Session("txtNameText")
End Sub
The problem is when I try this it doesn't update the display until the page is reloaded again. Is there a way to change the Label in Page_Load and have it show that change right away? Or do all changes of this sort have to be done before the page loads or reloads as the case may be? Note: this needs to be doable via Session variables if possible.

I know that this seems somewhat pointless, but this is really just a trivial example of something far more complex which would definitely benefit from such a thing if it is possible. Thanks for any help that you can offer (I probably won't get back until tomorrow to check on answers, though...sorry).
 
The problem is that the control postback events happens after page load event. ASP.NET Page Life Cycle Overview
If you need to set the label according to TextChanged you have to do it with that event handler, you can in addition set the session variable for other uses.
 
Looking at the life cycle of a web page, I think that perhaps setting the display on Page_PreRender might be what I'm looking for. It seems to work like I want it to. That is to say regardless of how or when the underlying data has changed, once the page is about to be painted (or rather rendered), I first set everything based on the session variable(s). This means after events have triggered, or after the "Back" button has been pressed (assuming that I've turned off caching for the page...which I have).

Is there any reason why I should not do this, or perhaps some reason why it only appears to work, when in fact something else might actually be happening? Thanks again.

Oh, and Happy Solstice everyone.
 
Back
Top