Reputation: 81
I have an asp.net application that is supposed to act like a stopwatch timer. I've tried variations on how to get the timer to count time using seconds. I used an algorithm that was largely inefficient. I then tried using timespan objects using datetime math, but since this basically made a clock it was undesireable. Now I'm trying to implement System.Diagnostics so I can use a Stopwatch object. When I run my program, the label that is supposed to update with the time just displays all 0's.
This is the code in the .aspx page with the the timer and update panel:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Enabled="false"
Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
<asp:Label ID="Label1" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
This is the event for my start button that starts the stopwatch and the timer:
protected void Start_Click(object sender, EventArgs e)
{
//Start the timer
Timer1.Enabled = true;
stopWatch.Start();
}
This is the event for the timer1 (currentTime is a timespan object):
protected void Timer1_Tick(object sender, EventArgs e)
{
currentTime = stopWatch.Elapsed;
Label1.Text = String.Format("{0:00}:{1:00}:{2:00}",
currentTime.Hours.ToString(), currentTime.Minutes.ToString(),
currentTime.Seconds.ToString());
I honestly don't know what I'm doing wrong. I figured this would be the easiest way to make a stopwatch timer, but nothing is changing within the label. I would appreciate any assistance. I will provide more information if necessary.
Upvotes: 0
Views: 4185
Reputation: 31
Try the below code. It works for me.
Add the below code in websource code:
<asp:scriptmanager ID="Scriptmanager1" runat="server"></asp:scriptmanager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Font-Size="XX-Large"></asp:Label>
<asp:Timer ID="tm1" Interval="1000" runat="server" ontick="tm1_Tick" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tm1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
Add following source code in your cs file:
using System.Diagnostics;
public partial class ExamPaper : System.Web.UI.Page
{
public static Stopwatch sw;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
sw = new Stopwatch();
sw.Start();
}
}
protected void tm1_Tick(object sender, EventArgs e)
{
long sec = sw.Elapsed.Seconds;
long min = sw.Elapsed.Minutes;
if (min < 60)
{
if (min < 10)
Label1.Text = "0" + min;
else
Label1.Text = min.ToString();
Label1.Text += " : ";
if (sec < 10)
Label1.Text += "0" + sec;
else
Label1.Text += sec.ToString();
}
else
{
sw.Stop();
Response.Redirect("Timeout.aspx");
}
}
}
Upvotes: 1