如何來驗證數字不使用的按鍵選項 爲什麼心不是Char.IsNumber
或.IsDigit
工作 或者我應該使用正則表達式的表達式驗證如何驗證winform中的唯一號碼?
private bool ValidateContact()
{
if (Char.IsNumber(textBox4.Text)){
return true;
}
如何來驗證數字不使用的按鍵選項 爲什麼心不是Char.IsNumber
或.IsDigit
工作 或者我應該使用正則表達式的表達式驗證如何驗證winform中的唯一號碼?
private bool ValidateContact()
{
if (Char.IsNumber(textBox4.Text)){
return true;
}
你可以簡單地解析數:
private bool ValidateContact()
{
int val;
if (int.TryParse(textBox4.Text, out val))
{
return true;
}
else
{
return false;
}
}
你是試圖調用string
爲char
編寫的方法。你必須單獨完成它們,或者使用一個更容易使用的方法,就像上面的代碼一樣。
爲什麼心不是Char.IsNumber或.IsDigit工作
因爲Char.IsDigit
想要一個char
不是string
。所以,你可以檢查所有文字:
private bool ValidateContact()
{
return textBox4.Text.All(Char.IsDigit);
}
或 - 更好,因爲IsDigit
includes unicode characters - 使用int.TryParse
:
private bool ValidateContact()
{
int i;
return int.TryParse(textBox4.Text, out i);
}
我個人不會依賴這個解決方案。 'char.IsDigit'對所有的Unicode數字都返回true。在這裏'int.TryParse'似乎更合適。 –
@ Selman22:好點。我相應地編輯了我的答案,並將[與我自己的問題鏈接](http://stackoverflow.com/q/22063436/284240)與此相關。 –
因爲這裏記錄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;
}
}
您應該使用
int n;
bool isNumeric = int.TryParse("123", out n);
不Char.IsNumber()
爲只測試一個字符。
解析字符串:
private bool ValidateContact()
{
int n;
return int.TryParse(textbox4.Text, out n);
}
嘗試剿上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問題
您能否請您說出您的代碼的來源? –
@PatrickHofman感謝提醒。 –
問題狀態'不使用按鍵選項'。 –
您可以使用正則表達式了。
if (System.Text.RegularExpressions.Regex.IsMatch("[^0-9]", textBox1.Text))
{
MessageBox.Show("Please enter only numbers.");
textBox1.Text.Remove(textBox1.Text.Length - 1);
}
你也可以檢查,文本框只允許數值:
因爲'字符。IsDigit'需要char而不是字符串 –
return Int.TryParse(textbox4.Text,out t) – VisualBean