Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumericUpDown: accept both comma and dot as decimal separator

There's a way to force c# NumericUpDown to accept both comma and dot, to separate decimal values?

I've customized a textbox to do it (practically replacing dots with commas), but I'm surprised that there isn't another way..

This question explains how to change the separator, but I would like to use both!

like image 671
T30 Avatar asked Jun 19 '14 15:06

T30


2 Answers

NumericUpDown control uses the culture of the operating system to use comma or dots as a decimal separator.

If you want to be able to handle both separators and consider them as a decimal separator (ie: not a thousand separator), you can use Validation or manual event treatment, for example:

private void numericUpDown1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar.Equals('.') || e.KeyChar.Equals(','))
        {
            e.KeyChar = ((System.Globalization.CultureInfo)System.Globalization.CultureInfo.CurrentCulture).NumberFormat.NumberDecimalSeparator.ToCharArray()[0];
        }
    }

In this example you will replace every dot and comma by the NumericDecimalSeparator of the current culture

like image 68
Nicolas R Avatar answered Oct 05 '22 13:10

Nicolas R


The solution provided by Nicolas R wouldn't work if you paste values into the NumericUpDown (via ClipBoard and Ctrl+V).

I suggest the following solution: The NumericUpDown Control has, like other Controls, a Text property. But, it is hidden from the designer and Intellisense. Using the Text property, you can write the ValueChanged event handler like this:

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    numericUpDown1.Text = numericUpDown1.Text.Replace(',', '.');
}

See also: https://msdn.microsoft.com/en-us/library/cs40s7ds.aspx

like image 45
Thomas Leopold Avatar answered Oct 05 '22 14:10

Thomas Leopold