How to create an event on property changing and changed event in C#
I created a property
public int PK_ButtonNo
{
get { return PK_ButtonNo; }
set { PK_ButtonNo = value; }
}
Now I want to add events to this property for value changing and changed.
I wrote two events. Here I want both the events to contain changing value as well as changed value.
i.e
When user implements the event. He must have e.OldValue
, e.NewValue
public event EventHandler ButtonNumberChanging;
public event EventHandler ButtonNumberC开发者_运维技巧hanged;
public int PK_ButtonNo
{
get { return PK_ButtonNo; }
private set
{
if (PK_ButtonNo == value)
return;
if (ButtonNumberChanging != null)
this.ButtonNumberChanging(this,null);
PK_ButtonNo = value;
if (ButtonNumberChanged != null)
this.ButtonNumberChanged(this,null);
}
}
How will I get the changing value and changed value when I implement this event.
Add the following class to your project:
public class ValueChangingEventArgs : EventArgs
{
public int OldValue{get;private set;}
public int NewValue{get;private set;}
public bool Cancel{get;set;}
public ValueChangingEventArgs(int OldValue, int NewValue)
{
this.OldValue = OldValue;
this.NewValue = NewValue;
this.Cancel = false;
}
}
Now, in your class add the changing event declaration:
public EventHandler<ValueChangingEventArgs> ButtonNumberChanging;
Add the following member (to prevent stackoverflow exception):
private int m_pkButtonNo;
and the property:
public int PK_ButtonNo
{
get{ return this.m_pkButtonNo; }
private set
{
if (ButtonNumberChanging != null)
ValueChangingEventArgs vcea = new ValueChangingEventArgs(PK_ButtonNo, value);
this.ButtonNumberChanging(this, vcea);
if (!vcea.Cancel)
{
this.m_pkButtonNo = value;
if (ButtonNumberChanged != null)
this.ButtonNumberChanged(this,EventArgs.Empty);
}
}
}
The "Cancel" property will allow the user to cancel the changing operation, this is a standard in a x-ing events, such as "FormClosing", "Validating", etc...
精彩评论