2016-01-05 53 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; 

     }