【问题标题】:FormatException was unhandled Input string was not in a correct formatFormatException 未处理 输入字符串的格式不正确
【发布时间】:2015-03-31 19:38:16
【问题描述】:

我想从我的数据库中获取int 值。我有错误FormatException was unhandled Input string was not in a correct format.

我的代码是

       string str = doc_cell.Text;
       ulong a = Convert.ToUInt64(str);

【问题讨论】:

  • str 的值是多少?例如,ulong a = Convert.ToUInt64("234"); 正在工作。 ulong a = Convert.ToUInt64("ab"); 正在按预期抛出 FormatException。您需要验证您的用户输入。
  • 试试这里提到的解决方案stackoverflow.com/questions/10715238/…

标签: c#


【解决方案1】:

问题来了,因为你转换的字符串不是 UInt64,因为这一行会抛出异常。

你应该这样写:

UInt64 a =0;
bool isSuccess = UInt64.TryParse(str, out a);

在这种情况下,如果解析成功,您将获得 a 中字符串的值。如果解析不正确,则 a 中将有 0。

【讨论】:

    【解决方案2】:
    try
    {
        string str = doc_cell.Text;
        ulong a = Convert.ToUInt64(str);
    }
    catch (FormatException)
    {
        MessageBox.Show("Error");
    }
    

    【讨论】:

    • 这太过分了,改用 TryParse。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多