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");
我得到一个消息回来我每次点击按钮
你可以阅读[这里](http://stackoverflow.com/questions/3464898/difference-between-page-load-and-onload])。 Page_load是一个事件处理程序,它在加载事件启动后执行。但在这个阶段,所有的控件已经被加载并发送了。所以你的标签不会改变。 相反的Page_Load的,你可以把他们的OnLoad,并删除!IsPostPack,那么它会工作。 – Jonathon