Afaf mubarak
Afaf mubarak

Reputation: 21

how to create 2 minute countdown timer using asp.net

i want to create a 2 minute timer under text box using Asp.net, i wanted the timer to be in a label under the text box, so i wrote this code in the control page after double click in the timer icon:

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


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

        else
            Timer1.Enabled = false;

And this code in the aspx file:

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

but it's not working, what is the problem with my code?

Upvotes: 1

Views: 8369

Answers (1)

LouraQ
LouraQ

Reputation: 6891

but it's not working, what is the problem with my code?

Timer needs to be used in conjunction with the UpdatePanel control. You can trigger the ontick event of the timer through the AsyncPostBackTrigger method of the updatepanel.

And for converting the text of the Label into the form of a timer, you need to use TimeSpan time = TimeSpan.FromSeconds(seconds); to achieve, you can refer to 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>

Code behind:

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

Here is the test result:

enter image description here

Upvotes: 1

Related Questions