输入字符串格式不正确,出现错误

时间:2013-09-19 06:26:25

标签: c# asp.net

我收到错误:

  

输入字符串不是核心格式

在该行:

int amount = Convert.ToInt32(txtAmount.Text);

1 个答案:

答案 0 :(得分:3)

您只需确保在TextBox中仅键入数字,例如1 2 3。

如果你键入任何非数字字符,如字母等,那么它将无法转换为等效的整数。例如字符串:"234"可以转换为整数,但"23A4"不能。

以下是3种转换为整数的方法:

Int32.Parse()Convert.ToInt32()Int32.TryParse()

这3个Int32.TryParse()中的错误不会引发异常。相反,它会在转换中遇到的任何错误上返回0

Int32.TryParse(string s, out int) 
When s is a null reference, it will return 0 rather than throw 
ArgumentNullException. If s is other than an integer value, the out 
variable will have 0 rather than FormatException. When s represents
a number less than MinValue or greater than MaxValue, the out variable 
will have 0 rather than OverflowException

检查 this link ,以全面了解这3种方法。

相关问题