2014-06-18 42 views
4

如何來驗證數字不使用的按鍵選項 爲什麼心不是Char.IsNumber.IsDigit工作 或者我應該使用正則表達式的表達式驗證如何驗證winform中的唯一號碼?

private bool ValidateContact() 
{ 
    if (Char.IsNumber(textBox4.Text)){ 
     return true; 
} 
+2

因爲'字符。IsDigit'需要char而不是字符串 –

+1

return Int.TryParse(textbox4.Text,out t) – VisualBean

回答

6

你可以簡單地解析數:

private bool ValidateContact() 
{ 
    int val; 
    if (int.TryParse(textBox4.Text, out val)) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 

你是試圖調用stringchar編寫的方法。你必須單獨完成它們,或者使用一個更容易使用的方法,就像上面的代碼一樣。

+0

您的解決方案會給出錯誤。 '不是所有的代碼路徑都返回一個值' – Ricky

+0

@Ricky:那太愚蠢了。現在它是正確的。 –

+0

但是如果用戶想輸入一個十進制數字呢? –

3

爲什麼心不是Char.IsNumber或.IsDigit工作

因爲Char.IsDigit想要一個char不是string。所以,你可以檢查所有文字:

private bool ValidateContact() 
{ 
    return textBox4.Text.All(Char.IsDigit); 
} 

或 - 更好,因爲IsDigitincludes unicode characters - 使用int.TryParse

private bool ValidateContact() 
{ 
    int i; 
    return int.TryParse(textBox4.Text, out i); 
} 
+2

我個人不會依賴這個解決方案。 'char.IsDigit'對所有的Unicode數字都返回true。在這裏'int.TryParse'似乎更合適。 –

+1

@ Selman22:好點。我相應地編輯了我的答案,並將[與我自己的問題鏈接](http://stackoverflow.com/q/22063436/284240)與此相關。 –

0

因爲這裏記錄http://codepoint.wordpress.com/2011/07/18/numeric-only-text-box-in-net-winforms/: -

我們可以創建數字僅文本框。 Net Windows通過在Key Press Event中添加以下代碼來形成應用程序。

僅爲數字文本框

private void txtBox_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') 
    { 
     e.Handled = true; 
    } 

    // only allow one decimal point 
    if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 
    { 
     e.Handled = true; 
    } 
} 
0

您應該使用

int n; 
bool isNumeric = int.TryParse("123", out n); 

Char.IsNumber()爲只測試一個字符。

1

解析字符串:

private bool ValidateContact() 
{ 
    int n; 
    return int.TryParse(textbox4.Text, out n); 
} 
0

嘗試剿上textbox.KeyPress

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') 
    { 
    e.Handled = true; 
    } 

    // only allow one decimal point 
    if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 
    { 
    e.Handled = true; 
    } 
} 

每一個關鍵,但數字或小數點爲什麼在按鍵控制?

因爲在用戶輸入值後提醒用戶不是從用戶處獲得輸入的有效方法。 而不是這樣做,您可以防止用戶輸入時輸入非有效值。

基於馬特漢密爾頓Ansver上this問題

+0

您能否請您說出您的代碼的來源? –

+0

@PatrickHofman感謝提醒。 –

+0

問題狀態'不使用按鍵選項'。 –

0

您可以使用正則表達式了。

if (System.Text.RegularExpressions.Regex.IsMatch("[^0-9]", textBox1.Text)) 
     { 
      MessageBox.Show("Please enter only numbers."); 
      textBox1.Text.Remove(textBox1.Text.Length - 1); 
     } 

你也可以檢查,文本框只允許數值:

How do I make a textbox that only accepts numbers?