2016-06-13 22 views
-2

我想在asp.net web中實現一個計時器,在這段時間之後,按鈕的文本被改變。我在gridview中動態地創建了按鈕,並試着使用下面的代碼:如何在asp.net c#中實現計時器?

protected void Timer2_Tick(object sender, EventArgs e) 
{ 
    Label2.Text = "Panel refreshed at: " + 
    DateTime.Now.ToLongTimeString(); 

    for(int i = 0; i< rowcount; i++) 
    { 
     Button button = new Button(); 
     if (button.Text == "requested") 
     { 
      button.Text = "available"; 
     } 
    } 
} 

但它不起作用。我怎麼解決這個問題?

+4

要更改在GridView中創建的按鈕的文本,需要對該Button對象的引用,Button button = new Button()只是創建一個新的Button對象,該對象與GridView中先前創建的Button無關.. – Kevin

回答

2

這需要在加載頁面後在瀏覽器上執行的客戶端代碼(JavaScript)。 ASP.NET生成頁面,將其發送到瀏覽器,然後服務器完成它,直到它獲得另一個請求。即使您在代碼隱藏中創建了一個計時器,該代碼隱藏類也會超出範圍,並在服務器處理完請求後消失。

最簡單的形式,它會是這個樣子:

<script> 
    window.setTimeout(function() 
    { 
     //do something 
    }, 10000); //interval in milliseconds - this is 10 seconds. 
<script> 

爲了能夠更改文本,你需要確保你的控制有一個ID,你可以找到使用JavaScript的。通常,無論您用於服務器控件的什麼ID,ASP.NET都會稍微修改它。我在這過於簡單化,但通常你可以這樣做:

<asp:Label ID="myLabelId" ClientIDMode="Static" Text="The label text"></asp:Label> 

<div runat="Server" ID="MyLabelId" ClientIDMode="Static">The label text</div> 

ClientIdMode="Static"意味着當控件呈現頁面也不會修改ID。

則腳本可能是這樣的:

<script> 
    window.setTimeout(function() 
    { 
     var label = document.getElementById("MyLabelId"); 
     label.textContent = "The new value"; 
    }, 10000); 
<script> 

或代替使用ClientIDMode="Static"你可以試試這個在您的腳本:

var label = document.getElementById("<%= MyLabelId.ClientID %>"); 

.ClientID是什麼ID的頁面分配給控制。這告訴它,無論它分配給該控件的ID如何,都直接寫入腳本。