0

I need a custom NumericUpDown where the event ValueChanged should pass CancelEventArgs instead of EventArgs as I want to be able to cancel the editing when certain conditions are verified (e.g. I have two NumericUpDown that must have always different values). If I try to override OnValueChanged I obviously get an error.

protected override void OnValueChanged(CancelEventArgs e)
{
    if (e.Cancel)
        return;
    else
    {
        EventArgs args = (EventArgs)e;
        base.OnValueChanged(args);
    }
}

Is there a way to do this?

Agnel Amodia
  • 765
  • 8
  • 18
PrinceOfBorgo
  • 508
  • 5
  • 14
  • 3
    is it sufficient to simply *check* whether the args is a `CancelEventArgs`, but leave it alone? so `e` stays `EventArgs` and you just check whether `e is CancelEventArgs cea && cea.Cancel` ? – Marc Gravell Mar 20 '18 at 11:58
  • @MarcGravell : I believe that the condition "e is CancelEventArgs" will be always false, because in any case, the base NumericUpDown class will always pass an "EventArgs" object to the OnValuChanged method, since it's the default implementation. – Oxald Mar 20 '18 at 12:03
  • You can't change any method signature when overriding it. – Zohar Peled Mar 20 '18 at 12:05

1 Answers1

1

I would propose to change a little bit your implementation of the cancel behavior, instead of trying to pass the information of Cancellation through the event arguments, you can query it on demand by introducing a new event to your custom component. Here is a simple example:

  class CustomNumericUpDown : NumericUpDown
  {
    protected override void OnValueChanged(EventArgs e)
    {
        if (QueryCancelValueChanging != null && QueryCancelValueChanging())
            return;
        else
        {
            EventArgs args = (EventArgs)e;
            base.OnValueChanged(args);
        }
    }

    public event Func<bool> QueryCancelValueChanging;
}

In this situation, the host of your component can subscribe to the new event in order to decide to cancel or not the "ValueChanged" event.

EDIT: Usage example:

 public partial class Form1 : Form
 {
    public Form1()
    {
        InitializeComponent();

        CustomNumericUpDown nudTest = new CustomNumericUpDown();
        nudTest.QueryCancelValueChanging += NudTest_QueryCancelValueChanging;
    }

    private bool NudTest_QueryCancelValueChanging()
    {
        return true;/* Replace by custom condition here*/
    }
}

Perhaps you need to learn how to create and manage custom events if you have never done it before, it should be easy to find tutorials on this topic on the web (like this one )

Oxald
  • 837
  • 4
  • 10