如何在 c# Windows 形式中将带有小数点的 TextBox 字符串转换为小数点。

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

我的数据库中有 decimal(18, 0) 数据类型的列。 当我尝试插入时,我得到 "Wrong format"。我喜欢这个...:[=​​13=]

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

假设我写 25.89 那么这会给我错误消息 "wrong format" 它适用于孔号,例如 25 但不适用于点 25.89

我在文本框上使用这个事件处理程序:

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;
            }
        }

这应该很容易,但我尝试了很多方法,但仍然无法正常工作。提前谢谢你

尝试使用

decimal amountToWithdraw = Convert.ToDecimal(txtAmountToTransfer.Text, CultureInfo.InvariantCulture);

尝试以下方法:

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;
  }
}

那么decimal.Parse(txtAmountToTransfer.Text)就可以了。并确保在输入数字时使用正确的小数点分隔符。