0

我有一个 asp.net 应用程序,它应该像秒表计时器一样工作。我已经尝试过如何让计时器使用秒来计算时间。我使用了一种效率很低的算法。然后我尝试使用日期时间数学来使用时间跨度对象,但由于这基本上是一个时钟,所以它是不可取的。现在我正在尝试实现 System.Diagnostics,以便可以使用 Stopwatch 对象。当我运行我的程序时,应该随时间更新的标签只显示全 0。

这是带有计时器和更新面板的 .aspx 页面中的代码:

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

这是我的开始按钮启动秒表和计时器的事件:

      protected void Start_Click(object sender, EventArgs e)
    {
        //Start the timer
        Timer1.Enabled = true;
        stopWatch.Start();
    }

这是 timer1 的事件(currentTime 是一个时间跨度对象):

      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());

老实说,我不知道我做错了什么。我认为这将是制作秒表计时器的最简单方法,但标签内没有任何变化。我将不胜感激任何帮助。如有必要,我将提供更多信息。

4

1 回答 1

1

试试下面的代码。这个对我有用。

在 web 源代码中添加以下代码:

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

在您的 cs 文件中添加以下源代码:

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");
        }
    }
} 
于 2013-03-06T09:01:34.297 回答