[英]How to Convert TextBox string with decimal to decimal in c# Windows form.
我的數據庫中的列具有十進制(18,0)數據類型。 當我嘗試插入時,出現“格式錯誤”。 我喜歡這樣...:
decimal amountToWithdraw = Convert.ToDecimal(txtAmountToTransfer.Text);
Letsay,如果我寫25.89,那么這會給我錯誤消息“格式錯誤”,它適用於孔號,例如25,但不適用於點號25.89
我在Textbox上使用此eventHandler:
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)
將正常工作。 並確保在鍵入數字時使用正確的小數點分隔符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.