Hello I'm trying to raise an event when the Birthdate of a person is greater then the actual date.
I'm new with events and it doesn't seem to work.
Code is beneath,
namespace LibClassLuchthaven
{
public class Person
{
public DateTime Birthdate { get; set; }
public string Firstname { get; set; }
public Gender Gender { get; set; }
public string Name { get; set; }
public event EventHandler BirthdateInFuture;
public Person()
{
this.Birthdate = DateTime.Now;
this.Firstname = string.Empty;
this.Gender = Gender.unknown;
this.Name = string.Empty;
}
public Person(DateTime birthdate, string firstname, Gender gender, string name)
{
this.Birthdate = birthdate;
this.Firstname = firstname;
this.Gender = gender;
this.Name = name;
}
public void OnBirthdateInFuture()
{
if (BirthdateInFuture!=null)
{
if (this.Birthdate > DateTime.Now)
{
BirthdateInFuture(this, EventArgs.Empty);
}
}
}
public override string ToString()
{
return this.Name + ", " + this.Firstname + " - " + this.Birthdate + " ( +" + this.Gender + ")";
}
}
}
public partial class FormCrewManagement : Form
{
public Person person = new Person();
public FormCrewManagement()
{
InitializeComponent();
person.BirthdateInFuture += Person_BirthdateInFuture;
}
private void Person_BirthdateInFuture(object sender, EventArgs e)
{
MessageBox.Show("Birthdate is in the future");
}
Try Changing the Property
public DateTime Birthdate { get; set; }
to
private DateTime _birthDate;
public DateTime Birthdate
{
get {return _birthDate;}
set
{
_birthDate=value;
if(value > DateTime.Now)
BirthdateInFuture?.Invoke(this, EventArgs.Empty);
}
}
This will raise the event when Birthdate value is in future.
It looks like the problem may be a logical one, rather than anything to do with events. You are setting the birthday to today's date... then checking if it's later. It never will be.
public Person()
{
this.Birthdate = DateTime.Now;
if (BirthdateInFuture!=null)
{
if (this.Birthdate > DateTime.Now)
{
BirthdateInFuture(this, EventArgs.Empty);
}
}
Philip, there is no place in your code where the event is raised. You could create a property called BirthDate and in the setter part, raise the event. When the birthdate is changed to a future date, it would/could raise the event.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.