2010-05-10 71 views
1
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(); 
} 

问题是与正在显示...当get_datasource这是1号线后调用,因为它是更新后的数据显示在网格视图因为在网格视图中的数据回发事件,但是当计时器事件处理程序正在调用timer_tick事件时,会调用get_datasource函数,但在此之后,更新后的数据在网格视图中不可见。由于timer_tick不是回发事件,因此它没有得到更新ASP.NET计时器事件

+0

唷,这是一个令人困惑的望着消息 - Ratnajyothi先生,你能不能再 - 格式化它看起来可读? 此外,您将无法在ASP.NET应用程序中使用“Timer”来导致回发,因为它只在服务器上运行。您需要改用JavaScript客户端脚本。 – 2010-05-10 05:08:25

回答

1

您不能使用这样的计时器。虽然ASP.NET试图隐藏HTTP的请求/响应循环,但循环仍然存在,因此您不能在回发中执行任何您喜欢的操作:您仍需要了解响应HTTP时正在发送HTML响应请求。

有什么特别的原因为什么你要使用这样的计时器?这对我来说似乎没有意义。你试图达到什么目标?

+0

单击按钮后,我们将发送特定数据以检查其状态。那么在提交之后,数据将不会出现在网格视图中。但是,如果检查没有再次正确完成,那么需要在30秒后显示特定数据,以便在时间流逝之后再次调用数据源。 – 2010-05-10 05:14:17

+0

可以请你帮我写一个JavaScript的定时器在客户端...所以一个特殊的事件应该在15分钟后调用按钮被点击.. – 2010-05-10 05:18:56

+0

@KRatnajyothi这是你要求的一个例子: http://www.w3schools.com/js/js_timing.asp – 2015-11-26 14:39:07

4

服务器端计时器,因为你已经实现它,不会为你想要实现的。

如果您将计时器和gridview都包装到updatepanel中,则每当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; 

    } 
+0

但是,事件将在计时器过期后触发一次,而不是每次计时器到期时为止。 – 2010-05-10 05:28:13

+0

我已经更新了解决方案的答案。只需在第一次点击按钮时启用定时器,并在第一次定时器运行时将其取消(注意:您还需要在updatepanel中包含submitbutton) – 2010-05-10 05:34:14

+0

再次更新以在updatepanel内显示按钮 – 2010-05-10 05:46:51