Timer Control in ASP.NET

 

Timer control in Asp.Net is used to refresh the entire page or it can refresh the specific update panel for every so many milliseconds mentioned for Interval property. If you placed the Timer control without Update Panel it refreshes the entire page. If you want to refresh only update panel we have to configure the Timer Control for AsyncPostBackTrigger of Update Panel. Today we discuss about how to refresh the Update Panel automatically by using Timer Control.

 

Open Microsoft Visual Studio => Create New Asp.Net Web Application => Add Timer Control and Update Panel as shown below.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AspNetTimerControl._Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Timer Control Example</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:ScriptManager ID="script1" runat="server"></asp:ScriptManager>

        <asp:Timer ID="timer1" runat="server" Interval="2000"></asp:Timer>

 

        <asp:UpdatePanel ID="up1" runat="server">

            <ContentTemplate>

                Now the time is <b><%=DateTime.Now.ToString()%></b>

            </ContentTemplate>

            <Triggers>

                <asp:AsyncPostBackTrigger ControlID="timer1" EventName="Tick" />

            </Triggers>

        </asp:UpdatePanel>

    </div>

    </form>

</body>

</html>

 

As shown above Timer Control is configured for Update Panel AsyncPostBackTrigger. So the Timer Control refreshes the Update Panel for every 2 seconds because we provided 2000 milliseconds for Timer Control Interval property. In the Update Panel we are displaying the current date and time.

 

If you run the application, it displays the current date & time and time will change for every 2 seconds because Timer will refresh the Update Panel for every 2 seconds.