ASP.NET 计时器事件

标签 asp.net timer

protected void SubmitButtonClicked(object sender, EventArgs e)
{
    System.Timers.Timer timer = new System.Timers.Timer();
        ---
        ---
    //line 1
    get_datasource();

    String message = "submitted.";
    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "popupAlert", "popupAlert(' " + message + " ');", true);

    timer.Interval = 30000;
    timer.Elapsed += new ElapsedEventHandler(timer_tick);

    // Only raise the event the first time Interval elapses.
    timer.AutoReset = false;
    timer.Enabled = true;
}

protected void timer_tick(object sender, EventArgs e)
{
//line 2
    get_datasource();
    GridView2.DataBind();
}

问题在于正在显示的 GridView 中的数据...因为当调用第 1 行之后的 get_datasource 时,更新的数据显示在 GridView 中,因为它是回发事件但是当计时器事件处理程序正在调用 timer_tick 事件,调用 get_datasource 函数,但之后更新的数据在 GridView 中不可见。它不会更新,因为 timer_tick 不是回发事件

最佳答案

您实现的服务器端计时器将无法实现您想要实现的目标。

如果您将计时器和 gridview 都包装在一个更新面板中,计时器将在每次 tick 事件触发时触发回发,并且您能够更新数据。

这是一篇很棒的博客文章,可以帮助您继续前进:http://mattberseth.com/blog/2007/08/using_the_ajax_timer_control_a.html

<asp:UpdatePanel runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:GridView ID="GridView2" runat="server">
        </asp:GridView>
        <asp:Timer id="Timer1" runat="server" Interval="30000" OnTick="Timer_Tick" Enabled="false" />  
        <asp:Button ID="Button1" runat="server" Text="Update" OnClick="SubmitButtonClicked" />              
    </ContentTemplate>
</asp:UpdatePanel>

服务器端代码:

    private void Timer_Tick(object sender, EventArgs args)
    {
        get_datasource();
        GridView2.DataBind();

        Timer1.Enabled = false; 
    }

    protected void SubmitButtonClicked(object sender, EventArgs e)
    {
        String message = "submitted.";
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "popupAlert", "popupAlert(' " + message + " ');", true);

        get_datasource();
        GridView2.DataBind();

        Timer1.Enabled = true;

    }

关于ASP.NET 计时器事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2800426/

相关文章:

javascript - 单元格表上的多个倒计时器

java - java swing中定时器与for循环之间的性能?

asp.net - ASP.NET WebForms 中 Html.Raw 的替代方案

Java Swing 计时器的速度不同

asp.net - 在 typeof 上使用 instanceof 时出现 "Too much recursion"错误?

php - 浏览器在 Paypal 网站上关闭

java - 等待倒计时结束

java - 要在 java 中设置按钮点击延迟?

带有子文件夹的 C# ASP.NET MVC Controller

jquery - asp.net mvc 4 使用ajax表单助手上传文件