How to create an event to change and change a property 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 to change and change the value.

I wrote two events. Here I want both events to contain a changing value as well as a changed value.

ie

When a user implements an event. It should have e.OldValue,e.NewValue

public event EventHandler ButtonNumberChanging;
public event EventHandler ButtonNumberChanged;

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 can I get a changing value and a changed value when I implement this event.

+5
source share
1 answer

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 a declaration of a changing event:

public EventHandler<ValueChangingEventArgs> ButtonNumberChanging;

Add the following element (to throw a stackoverflow exception):

private int m_pkButtonNo;

and 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);
        }
    }
}

"" , x-ing, "FormClosing", "Validating" ..

+6

All Articles