I have created this delegate so that each time I click the button the text within the label's text should change but for some reason this does not work and the label's text does not change.
This is my aspx page:
<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>
This is my aspx.cs page
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);
}
}
}
}
}
I am fairly sure that my delegate is coded correctly as when I uncomment the line
HttpContext.Current.Response.Write(message + " is full");
I get a message back each time I click the button