Search code examples
c#textboxdecimalwindows-forms-designer

How to Convert TextBox string with decimal to decimal in c# Windows form.


I have column in my database with decimal(18, 0) Data type. When I try to insert then I get "Wrong format". I do like this...:

decimal amountToWithdraw = Convert.ToDecimal(txtAmountToTransfer.Text);

Letsay if I write 25.89 then this givs me error message "wrong format" It's working with hole numbers, like 25 but not with dot 25.89

I use this eventHandler on Textbox:

private void txtAmountToTransfer_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;
            if(ch == 46 && txtAmountToTransfer.Text.IndexOf('.') != -1)
            {
                e.Handled = true;
                return;
            }

            if(!Char.IsDigit(ch) && ch != 8 && ch != 46)
            {
                e.Handled = true;
            }
        }

It should be easy but I have tried with many methods but stil I dont get it to work. Thank you in advance


Solution

  • Try the following approach:

    private void txtAmountToTransfer_KeyPress(object sender, KeyPressEventArgs e)
    {
      char ch = e.KeyChar;
      char decimalSeparatorChar = Convert.ToChar(Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberDecimalSeparator);
      if(ch == decimalSeparatorChar && txtAmountToTransfer.Text.IndexOf(decimalSeparatorChar) != -1)
      {
         e.Handled = true;
         return;
      }
    
      if(!Char.IsDigit(ch) && ch != 8 && ch != decimalSeparatorChar)
      {
         e.Handled = true;
      }
    }
    

    Then decimal.Parse(txtAmountToTransfer.Text) will work fine. And make sure you are using correct decimal separator when you type in numbers.