简体   繁体   中英

How do I cancel numericupdown_valuechanged event?

Here is my code. I am trying to create DateTime using numeric up-down. I get exception

System.ArgumentOutOfRangeException: 'Value of '1/3/0001 12:00:00 AM' is not valid for 'Value'. 'Value' should be between 'MinDate' and 'MaxDate'. Parameter name: Value'

I tried using the validating event for numeric-up-down, but then it is not firing.

 public DateTime ToDateTime(DateTime referencetime = default(DateTime))
    {
        if (referencetime == default(DateTime)) referencetime = DateTime.Now;
        DateTime returntime = referencetime;
        try
        {
            returntime = new DateTime(
                !Year.IsRelative ? Year.Value : referencetime.Year,
                !Month.IsRelative ? Month.Value : referencetime.Month,
                !Day.IsRelative ? Day.Value : referencetime.Day,
                !Hour.IsRelative ? Hour.Value : referencetime.Hour,
                !Minute.IsRelative ? Minute.Value : referencetime.Minute,
                !Second.IsRelative ? Second.Value : referencetime.Second
            );

            if (Year.IsRelative)
                returntime = returntime.AddYears(Year.Value);
            if (Month.IsRelative)
                returntime = returntime.AddMonths(Month.Value);
            if (Day.IsRelative)
                returntime = returntime.AddDays(Day.Value);
            if (Hour.IsRelative)
                returntime = returntime.AddHours(Hour.Value);
            if (Minute.IsRelative)
                returntime = returntime.AddMinutes(Minute.Value);
            if (Second.IsRelative)
                returntime = returntime.AddSeconds(Second.Value);
        }
        catch (Exception e) { }

DateTime.cs Design

I want to cancel the value_changed event for outofRange exception results. How do I do it?

You can set Mininum and Maximum properties of NumericUpDown control, on properties window as well as programmatically to avoid unwanted range.

Also you can use Validating event to cancel or set any other value to the control. I used this event to convert decimal value to int (user can enter any decimal value within the range). See the complete working project here .

Please let me know if you have further query on this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM