atrljoe
atrljoe

Reputation: 8151

Page Reload - Keeping Variables

How do I go about when page is reloaded that I make sure the variables I have declared at the top o my class do not get reset. IE I have a counter that is originally set at 0 if I use a postback control it resets that variable how do i go about not having this happen in C#?

Upvotes: 0

Views: 5228

Answers (5)

contactmatt
contactmatt

Reputation: 18600

That data is not persisted on HTTP Requests; you need to persist it in a cookie, hidden control, or manually store it in view state.

If you're manually doing a page counter, consider storing it in session state.

Upvotes: 0

gor
gor

Reputation: 11658

Use ASP.Net Session or Cookies. Or you can store their values in hidden fields. You can read about theese and outher option in following article.

Upvotes: 1

Luke
Luke

Reputation: 8407

if you´re using a postback, not a link, you should save your data into viewstate.

vb

Public Property MyValue() As String
            Get
                Dim _mv As Object = ViewState("MyValue")
                If Not _mv Is Nothing Then
                    Return _mv.ToString
                End If
                Return String.Empty
            End Get
            Set(ByVal value As String)
                ViewState("MyValue") = value
            End Set
End Property

C#

public string MyValue {
    get {
        object _mv = ViewState("MyValue");
        if ((_mv != null)) {
            return _mv.ToString();
        }
        return string.Empty;
    }
    set { ViewState("MyValue") = value; }
}

ViewState is saved along PostBacks, if you stay on the current page. For Example if you are on page.aspx and using a <asp:button> that is clicked each time, you can use Viewstate as a place for saving some of your data, it looks in the page source code like this

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE4Mzg3MjEyMzdkZNNlI9zvMeIGeUB4MZbJA2gmsHns9IsmAy/c4dQMybXD" />

the viewstate is generated automatically

Upvotes: 0

Michael Merrell
Michael Merrell

Reputation: 1006

Are you looking for a value specific to the client or to the server?

If you want something specific to the client use a cookie or session value.

If you are looking something specific to the server use a static class, application or cache value.

Upvotes: 5

RQDQ
RQDQ

Reputation: 15569

Put the value you want to save in a cookie.

Upvotes: 0

Related Questions