views:

63

answers:

3

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 ????

+3  A: 

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.

lmsasu
Changed your code to VB.Net, as the starting post is also VB.Net
Jan Jongboom
But it's not working , i modified the question.
Vibin Jith
@Jan Jongboom - Thanks. Not very sure on VB.Net syntax.
lmsasu
lmsasu
Please check , I Modified again.
Vibin Jith
@Vibin: the condition for postback should be: "If IsPostback = False Then ..." - as I in my above code (corrected).
lmsasu
+2  A: 

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
plenderj
A: 

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.

Braveyard
May I check. --Aaron
Vibin Jith