2013-08-26 52 views
1

我的目標:我想讓文本框接受像123.45或0.45或1004.72這樣的十進制數。如果用戶輸入字母a或b或c,程序應該顯示一條消息,提醒用戶只輸入數字。檢查文本框輸入是否是十進制數 - C#

我的問題:我的代碼只檢查像1003或567或1這樣的數字。它不檢查十進制數字,如123.45或0.45。如何讓我的文本框檢查十進制數字?以下是我的代碼:

namespace Error_Testing 
{ 

    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void textBox1_TextChanged(object sender, EventArgs e) 
     { 
      string tString = textBox1.Text; 
      if (tString.Trim() == "") return; 
      for (int i = 0; i < tString.Length; i++) 
      { 
       if (!char.IsNumber(tString[i])) 
       { 
        MessageBox.Show("Please enter a valid number"); 
        return; 
       } 
      } 
      //If it get's here it's a valid number 
     } 
    } 
} 

我是一個新手,並感謝您的幫助提前。 :)

+0

對於一個..你沒有處理'。'字符。當他們進入文本框時會發生什麼? –

+0

你是想給自己寫一張支票,還是使用內置支票?這在.NET中使用'decimal.TryParse'或'double.TryParse'很簡單。 – cadrell0

+0

@JonLaMarr:如果我在文本框中輸入123,屏幕上會出現一個對話框:「請輸入一個有效的號碼」。這意味着文本框不檢查十進制數字。 – Smith

回答

14

使用Decimal.TryParse來檢查輸入的字符串是否爲十進制。

decimal d; 
if(decimal.TryParse(textBox1.Text, out d)) 
{ 
    //valid 
} 
else 
{ 
    //invalid 
    MessageBox.Show("Please enter a valid number"); 
    return; 
} 
+0

對於整數,使用int.TryParse() –

+0

@NewHire:它的工作原理!感謝您的幫助。我會馬上回答。再次感謝。 – Smith

+0

@史密斯,不客氣,爲了解析任何數字,應該總是尋找'TryParse'家族方法,提供不同類型。例如int.TryParse,DateTime.TryParse等 – user2711965

0

decimal.Tryparse對包含「,」字符的字符串返回true,例如像「0,12」這樣的字符串返回true。

+0

一些國家使用「。」作爲小數點分隔符和其他國家使用「,」作爲小數點分隔符。你可以通過改變你的文化來改變這一點。看到這個答案的更多信息[stackoverflow answer](http://stackoverflow.com/questions/9160059/set-up-dot-instead-of-comma-in-numeric-values) – Erik

0
private void txtrate_TextChanged_1(object sender, EventArgs e) 
     { 
      double parsedValue; 
      decimal d; 
      // That Check the Value Double or Not 
      if (!double.TryParse(txtrate.Text, out parsedValue)) 
      { 
       //Then Check The Value Decimal or double Becouse The Retailler Software Tack A decimal or double value 
       if (decimal.TryParse(txtrate.Text, out d) || double.TryParse(txtrate.Text, out parsedValue)) 
       { 
        purchase(); 
       } 
       else 
       { 
        //otherwise focus on agin TextBox With Value 0 
        txtrate.Focus();     
        txtrate.Text = "0";     
       } 


      } 
      else 
      { 
       // that function will be used for calculation Like 
       purchase(); 
       /* if (txtqty.Text != "" && txtrate.Text != "") 
        { 
         double rate = Convert.ToDouble(txtrate.Text); 
         double Qty = Convert.ToDouble(txtqty.Text); 
         amt = rate * Qty; 
        }*/ 

      }`enter code here` 
     }