Pergunta

I'm inserting record into the DB after the button has been clicked then on page load I'm checking if the user attended today and display the right label. Problem is it keeps displaying the wrong label after postback, but if I do one refresh i get the correct label displayed.

 Protected Sub AttendBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles AttendBtn.Click
        Dim con As New SqlConnection
        Dim conString As String
        conString = ConfigurationManager.ConnectionStrings("attConnection").ConnectionString
        con = New SqlConnection(conString)

        con.Open()

        Dim cmd As New SqlCommand("INSERT INTO Attendance (UserID, Date, Attendance_Cycle, Comments)VALUES (@UserID, @Date, @Attendance_Cycle, @Comments)", con)

        cmd.Parameters.AddWithValue("@Date", DateTime.Now)
        cmd.Parameters.AddWithValue("@Attendance_Cycle", GlobalVarAndFunc.CurrentCycle(2))
        cmd.Parameters.AddWithValue("@Comments", "")
        cmd.Parameters.AddWithValue("@UserID", GlobalVarAndFunc.UserID)
        cmd.ExecuteNonQuery()
        con.Close()
 End Sub

and on page load

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If GlobalVarAndFunc.HasAttended Then
            attend_LB.Text = "You already attended today"
        Else
            attend_LB.Text = "Attend now"
        End If
 End Sub

GlobalVarAndFunc.HasAttended function checks if the User has pressed on the attended button today or not

Foi útil?

Solução

Please understand the flow of asp page. System will execute your page load before the button click event. So in your case, the moment page_load was called at that time you get the value that is already there in DB because system hasn't executed click event yet. When click event gets execute then your value gets into DB (before this event your DB wasn't updated). So on next refresh you gets the correct value.

Solution : Place page_load code in btn_click event to get the result in one go.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top