Brian Boatright
Brian Boatright

Reputation: 36754

How to Persist Variable on Postback

I created a single page (with code behind .vb) and created Public intFileID As Integer

in the Page load I check for the querystring and assign it if available or set intFileID = 0.

Public intFileID As Integer = 0

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        If Not Request.QueryString("fileid") Is Nothing Then
            intFileID = CInt(Request.QueryString("fileid"))
        End If

        If intFileID > 0 Then
            GetFile(intFileID)
        End If
    End If
End Sub

Private Sub GetFile()
    'uses intFileID to retrieve the specific record from database and set's the various textbox.text
End Sub

There is a click event for the Submit button that inserts or updates a record based on the value of the intFileID variable. I need to be able to persist that value on postback for it all to work.

The page simply inserts or updates a record in a SQL database. I'm not using a gridview,formview,detailsview, or any other rad type object which persists the key value by itself and I don't want to use any of them.

How can I persist the value set in intFileID without creating something in the HTML which could possibly be changed.

[EDIT] Changed Page_Load to use ViewState to persist the intFileID value

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        If Not Request.QueryString("fileid") Is Nothing Then
            intFileID = CInt(Request.QueryString("fileid"))
        End If

        If intFileID > 0 Then
            GetFile(intFileID)
        End If

        ViewState("intFileID") = intFileID
    Else
        intFileID = ViewState("intFileID")
    End If
End Sub

Upvotes: 25

Views: 80795

Answers (9)

Sahil Saini
Sahil Saini

Reputation: 250

Session["KeyName"] = your value;

  1. Type cast to the type to retrieve and store the data from session like given below :

Datatable dt = (DataTable)(Session["KeyName"]);

or

ViewState["KEY"]= value;

  1. Type cast to the type to retrieve and store the data from session like given below :

String str = (String)ViewState["KEY"];

Upvotes: 1

jerhinesmith
jerhinesmith

Reputation: 15492

As others have pointed out, you can store it in the Session or the ViewState. If it's page specific, I like to store it in the ViewState as opposed to the Session, but I don't know if one method is generally preferred over the other.

In VB, you would store an item in the ViewState like:

ViewState(key) = value

And retrieve it like:

value = ViewState(key)

Upvotes: 44

Sen Jacob
Sen Jacob

Reputation: 3442

I'll use Session as suggested by tvanfosson. ViewState and HiddenField might be too heavy if you want to keep large data like a dataset for comments in a forum's topic pages..

Upvotes: 0

Chad
Chad

Reputation:

I personally would choose to store the value in control state instead of viewstate as viewstate can easily be switched off. ControlState will persist even if viewstate is switched off for any reason. I have included an example on how this may be done.

Private intFileId As Integer = 0

Public Property FileID() As Integer
    Get
        Return intFileId
    End Get
    Set(ByVal value As Integer)
        intFileId = value
    End Set
End Property


Protected Overrides Function SaveControlState() As Object
    Dim objState(2) As Object
    objState(0) = MyBase.SaveControlState()
    objState(1) = Me.FileID
    Return objState
End Function


Protected Overrides Sub LoadControlState(ByVal savedState As Object)
    Dim objState() As Object
    objState = savedState
    MyBase.LoadControlState(objState(0))
    Me.FileID = CInt(objState(1))
End Sub




Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    Me.Page.RegisterRequiresControlState(Me)
End Sub


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not Page.IsPostBack Then
        If Not String.IsNullOrEmpty(Request.QueryString("fileid")) Then
            Me.FileID = CInt(Request.QueryString("fileid"))
        End If
    End If

    Response.Write(Me.FileID.ToString())
End Sub

Upvotes: 1

Mark Brackett
Mark Brackett

Reputation: 85655

Actually, since an ASP.NET page postbacks to itself - including the query string - you could just remove the If Not Page.IsPostBack condition. Then it'd set itself on each postback.

Upvotes: 1

Mitchel Sellers
Mitchel Sellers

Reputation: 63126

Just to summarize what is said above.

You can use Session, Viewstate, or a hidden field.

I personally prefer viewstate as it will work in web farm environments, Session does not, it does not store it on the server waiting for the user, for up to 20 minutes to be removed, and in general viewstate is the place to be for page level data.

You can use a hidden field, but then a user could more easily modify it.

Upvotes: 5

Joel Coehoorn
Joel Coehoorn

Reputation: 415765

Remember:

Each time your server code runs, it's in a brand new instance of your page class. That's for every postback.

Upvotes: 2

Kon
Kon

Reputation: 27441

Store in:

  • Session
  • ViewState
  • Hidden input

Upvotes: 5

tvanfosson
tvanfosson

Reputation: 532465

Store it in the Session.

Page.Session["MyPage_FileID"] = intFileID

You'll need to have logic that manages it as the user navigates around, but if it is always set when the page loads from a GET (or you clear it, if not available on GET) then you should be ok using it later from the Session on your submit PostBack.

Upvotes: 4

Related Questions