Results 1 to 3 of 3

Thread: ViewState Question

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Aug 2000
    Location
    Birmingham, AL
    Posts
    1,276

    Question ViewState Question

    VB Code:
    1. Dim str As String
    2.  
    3.     Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    4.         'Put user code to initialize the page here
    5.  
    6.         If Page.IsPostBack Then
    7.             str = ViewState("str")
    8.         Else
    9.             str = "Init"
    10.         End If
    11.  
    12.         Response.Write(str)
    13.  
    14.     End Sub
    15.  
    16.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    17.         str = TextBox1.Text
    18.         ViewState("str") = str
    19.     End Sub
    When the page first loads, obviously "Init" prints. Then, I type in TextBox1 and click Button1. You would think that on the first PostBack, str would be printed but it isn't. It's not until the next Button1 click. So my question is, does the Page PostBack fire before the Button Click event fires? Seems to be backwards if that's the case...

  2. #2
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704

    Re: ViewState Question

    The page load occurs before the button_click event.

    So what's happening is:
    1) Its set to init
    2) You then type in something and click submit
    3) Page_Load fires, viewstate is empty
    4) The button click event fires, viewstate now contains the value
    5) The page renders, you click submit again
    6) The Page_Load fires again, and the value from viewstate is retrieved

    Its not backwards actually.
    Remove the response.write in the page load, and place it here instead:
    VB Code:
    1. Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
    2.        If Page.IsPostBack Then
    3.          str=viewstate("whatever")
    4.        End If
    5.           Response.Write(str)
    6.  End Sub

    That said, this not the best way to store values in viewstate and retrieve them, but for your example, its how to implement it fast.
    Last edited by nemaroller; Mar 9th, 2005 at 06:59 PM.

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    Aug 2000
    Location
    Birmingham, AL
    Posts
    1,276

    Re: ViewState Question

    Can you give me a solid example on ViewState?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width