PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 13, 2022

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

 August 13, 2022     c#, decimal, textbox, windows-forms-designer     No comments   

Issue

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.



Answered By - Access Denied
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing