NumericUpDownWithUnitParsing - default value '0' / '<null>'

Hi everyone,

as of a private discussion with @dale and @curtisw I would like to post the solution we came up with to present a DBNull or null value in a NumericUpDownWithUnitParsing. When using the NumericUpDownWithUnitParsing the default value is set to ‘0’ even thougt you want to display no value (DBNull or null). @dale and @curtisw suggested to use:

NumericUpDownWithUnitParsing.IsAlternateTextVisible
NumericUpDownWithUnitParsing.AlternateText

as a work arround. Here is a code snippet:

NumericUpDownWithUnitParsing stepper = new NumericUpDownWithUnitParsing
{
    BackgroundColor = Colors.Transparent,
    Increment = 1.0,
    MaximumDecimalPlaces = 100,
    TextAlignment = TextAlignment.Right,
    Tag = false,
    ShowStepper = false,
    AlternateText = "<null>",
    AlternateTextColor = Colors.DimGray,
    ShowBorder = false,
};

object value = null;

if (tuple.Item2 != null && tuple.Item2 != DBNull.Value && !string.IsNullOrEmpty(tuple.Item2.ToString()))
{
    double d = Convert.ToDouble(tuple.Item2);
    stepper.Value = d;
    value = d;
}

stepper.IsAlternateTextVisible = Equals(value, null) || value is DBNull;
stepper.ValueChanged += new EventHandler<EventArgs>(this.OnValueChanged);
stepper.KeyUp += new EventHandler<KeyEventArgs>(this.OnKeyUp);

The events handle some special key events like Escape, Delete, Backspace, D0 and Keypad0. A short gif animation of the final UI behaviour.

22-04-2022_19-46-48

Many thanks to @dale and @curtisw.

Kindest
Christian

1 Like