2020年3月17日 星期二

[研究][ASP.NET][WebForm] 倒數計時

[研究][ASP.NET][WebForm] 倒數計時

2020-03-17

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
Inherits="WebApplication1.Default" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager runat="server" />
        <asp:UpdatePanel runat="server">
            <ContentTemplate>
                <asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick"></asp:Timer>
                <asp:Label ID="timeLabel" runat="server"></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>


Default.aspx.cs
using System;
namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        private static int timeLeft = 100000;
        protected void Page_Load(object sender, EventArgs e)
        {
            Timer1.Interval = 1000;//設定每秒執行一次
            Timer1.Enabled = true;
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            if (timeLeft > 0)
            {
                timeLeft = timeLeft - 1;
                timeLabel.Text = timeLeft + " seconds";
            }
            else
            {
                Timer1.Enabled = false;
                timeLabel.Text = "Time's up!";
            }
        }
    }
}


(完)

沒有留言:

張貼留言