56
votes

I have to detect decimal separator in current windows setting. Im using visual studio 2010, windows form. In particular, if DecimalSeparator is comma, if user input dot in textbox1, I need show zero in textbox2.

I tryed with this code, but not works:

private void tbxDaConvertire_KeyPress(object sender, KeyPressEventArgs e)
    {
        string uiSep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;
        if (uiSep.Equals(","))
        {
            while (e.KeyChar == (char)46)
            {
                tbxConvertito.Text = "0";
            }
        } 
    }

I have tryed also this code, but not work:

private void tbxDaConvertire_KeyPress(object sender, KeyPressEventArgs e)
    {
        string uiSep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
        if (uiSep.Equals(","))
        {
            if (e.KeyChar == (char)46)
            {
                tbxConvertito.Text = "0";
            }
        } 
    }
3
"but not works" doesn't tell us what went wrong.Sam Axe
Since we can't read your mind or see your screen from here, it would be really useful if you included an explanation of what "not works" means.Ken White
Vincenzolopalo, for starters you do not need a while loop second you need to explain what you want better.. are you saying that you do not want to allow "," also when checking == vs .Equals you should know when to use one over the other normally when comparing Objects the .Equals would work.. either way.. your current logic is flawed why don't you use a Masked Edit instead..?MethodMan
to solve your issue just use a MaskedTextBox <==click here to learn more about itMethodMan
the number makes sense it's telling me 1500.00 are you trying to represent Currency..? you can get around that issue as wellMethodMan

3 Answers

81
votes

Solution:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    char a = Convert.ToChar(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
    if (e.KeyChar == a)
    {
        e.Handled = true;
        textBox1.Text = "0";
    }
}

That way, when you hit . or , you will have a 0 in your TextBox.

EDIT:

If you want to insert a 0 everytime you hit the decimal separator, this is the code:

char a = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (e.KeyChar == a)
{
    e.KeyChar = '0';
}
37
votes

Actually you should be using

CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator

instead of

CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator

Using the second one gives you the OS default settings, which might be different then user Regional Locales for particular user account logged to this PC.

Credits to berhir and Grimm for pointing out the [docs]

1
votes

You shouldn't use a while loop, I think it will freeze the application, use if instead, the problem might be here