【发布时间】:2011-07-23 05:17:08
【问题描述】:
我有一个用户可以输入数字的文本框,有没有办法将它转换为 int?因为我想将它插入到只接受 int 的数据库字段中。
tryParse 方法似乎不起作用,仍然抛出异常。
【问题讨论】:
我有一个用户可以输入数字的文本框,有没有办法将它转换为 int?因为我想将它插入到只接受 int 的数据库字段中。
tryParse 方法似乎不起作用,仍然抛出异常。
【问题讨论】:
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
【讨论】:
int orderID = 0;
orderID = Int32.Parse(txtOrderID.Text);
【讨论】:
使用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
}
Parse 和 TryParse 之间的区别非常明显。后者优雅地失败,而另一个如果无法将字符串解析为整数则会抛出异常。但是 Int32.Parse 和 System.Convert.ToInt32 之间的差异更加微妙,并且通常与特定于文化的解析问题有关。基本上是如何解释负数、小数和千位分隔符。
【讨论】:
如果这是 WinForms,您可以使用 NumericUpDown 控件。如果这是网络表单,我会使用 Int32.TryParse 方法以及输入框上的客户端数字过滤器。
【讨论】:
int temp;
if (int.TryParse(TextBox1.Text, out temp))
// Good to go
else
// display an error
【讨论】:
您可以使用Int32.Parse(myTextBox.text)
【讨论】: