我有一個文本框,用戶可以把號碼,有沒有辦法把它轉換爲int?因爲我想將它插入只接受int的數據庫字段中。
tryParse方法似乎不起作用,仍然引發異常。
我有一個文本框,用戶可以把號碼,有沒有辦法把它轉換爲int?因爲我想將它插入只接受int的數據庫字段中。
tryParse方法似乎不起作用,仍然引發異常。
要麼使用Int32.Parse或Int32.TryParse,或者您可以使用System.Convert.ToInt32
int intValue = 0;
if(!Int32.TryParse(yourTextBox.Text, out intValue))
{
// handle the situation when the value in the text box couldn't be converted to int
}
解析和的TryParse之間的差異是很明顯的。如果後者無法將字符串解析爲整數,那麼後者會優雅地失敗,而另一方會拋出異常。但是Int32.Parse和System.Convert.ToInt32之間的差異更加微妙,通常與文化特定的解析問題有關。基本上如何解釋負數和小數以及數千分隔符。
您可以使用Int32.Parse(myTextBox.text)
int temp;
if (int.TryParse(TextBox1.Text, out temp))
// Good to go
else
// display an error
如果是這樣的WinForms,你可以使用一個NumericUpDown控件。如果這是webforms,我會使用Int32.TryParse方法以及輸入框上的客戶端數字過濾器。
int orderID = 0;
orderID = Int32.Parse(txtOrderID.Text);
private void txtAnswer_KeyPress(object sender, KeyPressEventArgs e)
{
if (bNumeric && e.KeyChar > 31 && (e.KeyChar < '0' || e.KeyChar > '9'))
{
e.Handled = true;
}
}
來源:http://www.monkeycancode.com/c-force-textbox-to-only-enter-number