Asp.net losing values of variables

I am trying to write my first WebApplication in ASP.NET. Here is my code:

Public Class WebForm2
Inherits System.Web.UI.Page
Public n As Integer
Public zetony As Integer
Public liczba As Boolean
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub
Private Function TextBox1_Validate(Cancel As Boolean)
    If Not IsNumeric(TextBox1.Text) Then
        MsgBox("Prosze podaj liczbe dobry uzytkowniku :)", vbInformation)
        Cancel = True
    Else : Cancel = False
    End If
    Return Cancel
End Function
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    liczba = TextBox1_Validate(liczba)
    If (liczba = False) Then
        n = Convert.ToInt32(TextBox1.Text)
        Label2.Text = n
    End If
End Sub
Protected Sub graj()
    Label2.Text = n
End Sub
Protected Sub Image1_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton1.Click
    If zetony < 2 Then
        n -= 1
        ImageButton1.ImageUrl = "red_coin.gif"
        zetony += 1
    End If
End Sub

Protected Sub Image2_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton2.Click
    If zetony < 2 Then
        n -= 1
        ImageButton2.ImageUrl = "red_coin.gif"
        zetony += 1
    End If
End Sub

Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    graj()
End Sub
End Class

My problem is that, only on Button1_Click I got proper value. When I try to call Sub graj() value of n is alwayes 0.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

HTTP is stateless. This means that for every request a new instance of the class WebForm2 gets created. So if you set the value of n inside Button1_Click it will not be preserverd when you access it from Button2_Click since it’s a different instance.

To save your data across requests there are several possibilities, to name a few:

  • Save it in a database
  • Save it in the Application-object (this is shared across all users:
    // setting the value
    HttpContext.Current.Application("n") = "somevalue";
    
    // Getting the value
    string test = HttpContext.Current.Application("n");
  • Save it in the session-state (this is shared across all requests for one user):
    // setting the value
    HttpContext.Current.Session("n") = "somevalue";
    
    // Getting the value
    string test = HttpContext.Current.Session("n");


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x