1

我想使用 Asp.net 在文本框下创建一个 2 分钟计时器,我希望计时器位于文本框下的标签中,所以我在双击计时器图标后在控制页面中编写了以下代码:

 int seconds = int.Parse(Label1.Text);
        if (seconds > 0)


            Label1.Text = (seconds - 1).ToString("mm:ss");

        else
            Timer1.Enabled = false;

而aspx文件中的这段代码:

<span "CodeAsk">ألم تتلقى الرمز ؟</span><asp:Label ID="Label1" runat="server" text="2"></asp:Label>
        <asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="120000"></asp:Timer>

但它不起作用,我的代码有什么问题?

4

1 回答 1

0

但它不起作用,我的代码有什么问题?

Timer 需要与UpdatePanel控件一起使用。可以通过updatepanel的AsyncPostBackTriggerontick方法触发定时器的事件。

而对于将Label的文本转换成定时器的形式,需要用到TimeSpan time = TimeSpan.FromSeconds(seconds);实现,可以参考this

 <form runat="server">
        <asp:ScriptManager runat="server" ID="ScriptManager1" />
        <asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="1000">
        </asp:Timer>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <span id="CodeAsk">ألم تتلقى الرمز ؟</span><br />
                <asp:Label ID="Label1" runat="server" Text="2"></asp:Label>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
            </Triggers>
        </asp:UpdatePanel>
    </form>

后面的代码:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                TimeSpan time = TimeSpan.FromSeconds(Convert.ToInt32(Label1.Text) * 60);
                string str = time.ToString(@"hh\:mm\:ss");
                Label1.Text = str;
            }
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            TimeSpan result = TimeSpan.FromSeconds(TimeSpan.Parse(Label1.Text).TotalSeconds - 1);
            string fromTimeString = result.ToString(@"hh\:mm\:ss");
            Label1.Text = fromTimeString;
        }

这是测试结果:

在此处输入图像描述

于 2020-08-24T03:26:00.727 回答