Vibin Jith
Vibin Jith

Reputation: 931

My Session Value is Not Changing

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If IsPostBack = True Then
            Session("x") = "ABC"
        End If
    End Sub

    Protected Sub btnABC_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnABC.Click
        Session("x") = "ABC"
    End Sub

    Protected Sub btnCBA_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCBA.Click
        Session("x") = "CBA"
    End Sub

    Protected Sub btnShow_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShow.Click
        TextBox1.Text = Session("x")
    End Sub
End Class

Three buttons-ABC,CBA and Show. if you click on ABC and then Click on Show button The textbox shows "ABC" but when I Clicking on CBA button And then Click on Show button The textbox shows again "ABC". IsPostback property will true on each time the page is posted to the server. So the session reset the value. how to overcome this issue ????

Upvotes: 0

Views: 1063

Answers (3)

Tarik
Tarik

Reputation: 81721

Besides what other people wrote above, I also recommend you to assign Session values during Page_InitComplete event. Because mostly developers work in Page_Load stage and some times assigning Session values as well may throw errors because of it. It is like which one is happening before or after. You can make mistakes and so on.

Upvotes: 0

lmsasu
lmsasu

Reputation: 7583

If you set the value in page_load(), this assignment occurs every time you load the page. Maybe you want to set this value only at the first call of the page:

If IsPostback = False Then
    Session("x") = "Something"
End If

The second load of the page will not overwrite the value you set in button1_click.

Upvotes: 3

plenderj
plenderj

Reputation: 573

When you press the show button it causes a postback to the server. The Page_Load method fires first, and you assign "ABC" into Session("x"). Then you're putting Session("x") into into the textbox. What you'd probably want is this instead:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Session("x") = "ABC"
    End If
End Sub

Upvotes: 2

Related Questions