dtmnn
dtmnn

Reputation: 243

How to attach Timer to a button using C#

I'm having a timer(with label) and a button on one of my pages. The timer is using a simple onTickEvent.

  protected void Timer1_Tick(object sender, EventArgs e)
    {
        int seconds = int.Parse(Label1.Text);

        if (seconds > 0)

            Label1.Text = (seconds - 1).ToString();
        else
            Timer1.Enabled = false;
    }

all the extensions are grouped together in an UpdatePanel

 <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate>
                        <asp:Button ID="schlbtn1" runat="server" Text="Go To Lectures" CssClass="btn btn-lg btn-success btn-block" OnClick="schlbtn1_Click" Visible="true" ForeColor="Black" ViewStateMode="Enabled" ClientIDMode="Static" />
                        <asp:Label ID="Label1" runat="server">60</asp:Label>
                        <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick">
                        </asp:Timer>
                    </ContentTemplate>
                </asp:UpdatePanel>

The logic is simple. The timer uses the label which is defaultly set to 60 and decrese it by 1 on every tick which has interval of 1000 miliseconds.Everything works perfectly but unfortunately the timer starts to count down right after I load the page. I want somehow to attach the timer to start when I click the button with ID "schlbtn1".

Upvotes: 0

Views: 1812

Answers (1)

Brian S
Brian S

Reputation: 5785

The timer is enabled by default when created, so you'll need to create it disabled, then manually enable it. You can do that as follows:

In your UpdatePanel (note Enabled is set to false):

<asp:Timer ID="Timer1" runat="server" Enabled="false" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>

Then enable the timer in the click event of your button (schlbtn1_Click):

Timer1.Enabled = true;

This will cause the timer to start disabled, then start when the button is pressed.

Upvotes: 2

Related Questions