c# - How to make own event handler? -
i making windows forms project in c#, in made class labelx
inherits system.windows.forms.label
, added property mass
of float type
now, question how can handle, when value of mass
changed.
e.g.:
when user enter value zero
or less zero
want fire message "mass can't 0 or negative"
if interpreting correctly, there 2 parts this. first, need detect invalid values , throw exceptions. second, need raise event when property changes. can achieved follows.
private float mass; public float mass { { return this.mass; } set { if (value <= 0.0f) { throw new argumentoutofrangeexception("mass cannot 0 or negative."); } if (this.mass != value) { this.mass = value; onmasschanged(eventargs.empty); } } } public event eventhandler masschanged; protected virtual void onmasschanged(eventargs args) { var handler = this.masschanged; if (handler != null) { handler(this, args); } }
to show message if invalid entry made, should put try
\ catch
block around call set mass
, catch argumentoutofrangeexception
.
Comments
Post a Comment