2016-01-05 54 views
0

我創造了這個委託,這樣每次我點擊按鈕標籤的文本內的文本應該改變,但出於某種原因,這並不工作和標籤的文本不會改變。C#委託,標籤文本不改變

這是我的aspx頁面:

<body> 
    <form id="form1" runat="server"> 
    <div> 
     <asp:Button ID="btnFeed" OnClick="btnFeed_Click" runat="server" Text="Button" /> 
     <asp:Label ID="lblRaceResults" runat="server" Text="Label"></asp:Label> 
    </div> 
    </form> 
</body> 

這是我的aspx.cs頁面

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace WebProgramming3.Week_3 
{ 
    public partial class Exercise1 : System.Web.UI.Page 
    { 
     //only for testing 
     static Person test_person; 
     static Person person2; 
     static Person person3; 

     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!IsPostBack) 
      { 
       test_person = new Person("Neil"); 
       person2 = new Person("2"); 
       person3 = new Person("3"); 
       test_person.OnFullyFed += Test_person_OnFullyFed; 
       person2.OnFullyFed += Test_person_OnFullyFed; 
       person3.OnFullyFed += Test_person_OnFullyFed; 
      } 
     } 

     private void Test_person_OnFullyFed(string message) 
     { 
      // HttpContext.Current.Response.Write(message + " is full"); 
      lblRaceResults.Text = message; //<--This is the label where text will not change 
     } 

     protected void btnFeed_Click(object sender, EventArgs e) 
     { 
      test_person.Feed(1); 
      person2.Feed(2); 
      person3.Feed(3); 
     } 
    } 

    public delegate void StringDelegate(string message); 

    public class Person 
    { 
     public string Name { get; set; } 
     public int Hunger { get; set; } 

     public event StringDelegate OnFullyFed; 

     public Person(string name) 
     { 
      Name = name; 
      Hunger = 3; 
     } 

     public void Feed(int amount) 
     { 
      if(Hunger > 0) 
      { 
       Hunger -= amount; 
       if(Hunger <= 0) 
       { 
        Hunger = 0; 

        //this person is full, raise an event 
        if (OnFullyFed != null) 
         OnFullyFed(Name); 
       } 
      } 
     } 

    } 
} 

我相當肯定,我的委託正確編碼,當我取消對該行

HttpContext.Current.Response.Write(message + " is full"); 

我得到一個消息回來我每次點擊按鈕

+1

你可以閱讀[這裏](http://stackoverflow.com/questions/3464898/difference-between-page-load-and-onload])。 Page_load是一個事件處理程序,它在加載事件啓動後執行。但在這個階段,所有的控件已經被加載併發送了。所以你的標籤不會改變。 相反的Page_Load的,你可以把他們的OnLoad,並刪除!IsPostPack,那麼它會工作。 – Jonathon

回答

0

這是因爲在線程完成更新其 控件之前,頁面生命週期已完成並且頁面已呈現 /發送給瀏覽器。調試過程中,你可以看到線程完成自己的工作 但改變已經被髮送到瀏覽器的標籤。

從您加載事件中刪除!IsPostBack應該做的訣竅和重新加載控件。當然,還有其他的選擇可以用來解決這個問題,比如有更新面板和自動刷新。

protected void Page_Load(object sender, EventArgs e) 
     { 
       test_person = new Person("Neil"); 
       person2 = new Person("2"); 
       person3 = new Person("3"); 
       test_person.OnFullyFed += Test_person_OnFullyFed; 
       person2.OnFullyFed += Test_person_OnFullyFed; 
       person3.OnFullyFed += Test_person_OnFullyFed; 

     }