【发布时间】:2016-04-09 20:21:28
【问题描述】:
我创建了这个委托,因此每次单击按钮时,标签文本中的文本都会发生变化,但由于某种原因,这不起作用并且标签的文本不会改变。
这是我的 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");
每次点击按钮都会收到一条消息
【问题讨论】:
-
您可以阅读here。 Page_load 是一个事件处理程序,它在加载事件触发后执行。但是在这个阶段,所有的控件都已经加载并发送了。所以你的标签不会改变。不用Page_load,你可以把它们放在OnLoad里,去掉!IsPostPack,就可以了。