---deleted-- and recommend SAKryukov's solution.
And my updated answer here is an example how the
e.cancel
works with a custom example.
Here is a class with a custom event which has the
CancelEventArgs
type of argument.
When this event fires you can set its
cancel
property which signals the object about further action.
public class PersonWithEvent
{
public event CancelEventHandler NameAcceptanceEvent;
private string _name;
public string ErrMessage{get;set;}
public string Name
{
get { return _name; }
set
{
CancelEventArgs cancelParams = new CancelEventArgs();
NameAcceptanceEvent.DynamicInvoke(new object[] { this, cancelParams });
if (cancelParams.Cancel != true)
{
_name = value;
ErrMessage = "";
}
else
{
ErrMessage = "This name not allowed";
}
}
}
}
Now the acceptance of a name is not encapsulated in this object, but delegated to the user who can implement his own logic for that.
private string personName;
private void button1_Click(object sender, EventArgs e)
{
PersonWithEvent person = new PersonWithEvent();
person.NameAcceptanceEvent+=new CancelEventHandler(person_NameAcceptanceEvent);
personName = "Monster";
person.Name = personName;
MessageBox.Show(person.Name);
MessageBox.Show(person.ErrMessage);
personName = "Angel";
person.Name = personName;
MessageBox.Show(person.Name);
MessageBox.Show(person.ErrMessage);
}
private void person_NameAcceptanceEvent(object sender, CancelEventArgs e)
{
if (personName == "Monster")
{
e.Cancel = true;
}
}
Good luck