Search code examples
asp.netvb.nettimer

Using a Timer to Update a Label in an ASP.Net Web Application


I have a label on my master page that I would like to see update every second, keeping track of the seconds elapsed. I have revised my question and have seen some progress but have a new problem.

I have restructured my code to include an ASP:Timer, Trigger, and AsyncPostBackTrigger (all wrapped within an UpdatePanel) but the update only seems to happen once... The default label text appears, is updated to "1" and then stays that way even though the back-end code continues to count upwards.

Back End:

Public intCounter As Integer = 0

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    getUserAccess()
    manageAccess()

End Sub

Protected Sub testTimer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles testTimer.Tick

    intCounter += 1
    lblTestTimer.Text = intCounter

End Sub

HTML:

        <div>
            <asp:Timer ID="testTimer" OnTick="testTimer_Tick" runat="server" Interval="1000"></asp:Timer>
        </div>
        <asp:UpdatePanel runat="server">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="testTimer" EventName="Tick"/>
            </Triggers>
            <ContentTemplate>
                <asp:Label ID="lblTestTimer" CssClass="ticketLabel" Text="Ticket Alert!" runat="server"></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>  

Final Issue (Fixed): My interval was being reset on each page load, I changed the declaration to Shared and all is well. Thank you to @the_lotus for the help!


Solution

  • You should really read about page life cycle. The server can't connect to the client like that. Usually, the timer is done on the client using javascript and call the server for the updated value. It's not like a winform where everything is run on the client.

    Since you are using an UpdatePanel, you could probably use the asp:Timer to run a timer on the client.

    Your variable also gets reset on every page load. Save the value in a session or make it shared.