Laurence
Laurence

Reputation: 7823

How to maintain the value of a variable VB.NET

I am a beginner developer .. I need help .. please see the following example .. sorry for poor english ...

I have a string variable called str assigned with "John". I changed it to "Dave" when the first button is clicked. When the second is clicked, I displayed the value to a label. I wanna see Dave but I just see John. Why is that?

There is nothing on page load and nothing else where. I know I can put into a session but this is on the same page. Can I not do without session or viewstate.

Thanks.

    Partial Class  _Default
        Inherits System.Web.UI.Page

        Private str As String = "John"

        Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
            str = "Dave"        
        End Sub

        Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click    
           Label1.Text = str
        End Sub
    End Class

Upvotes: 0

Views: 1360

Answers (1)

user804018
user804018

Reputation:

Welcome to the world of stateless programming; variables don't survive after a page is rendered; you need to use the Session object to save them.

In your button click, set Session("PersonName") = "Dave"

In Page_Load, have code such as:

str = Session("PersonName").ToString()

I would highly recommend working through a few tutorials in ASP.NET programming to familarize yourself with all the concepts you need.

Upvotes: 4

Related Questions