【问题标题】:Input string was in incorrect format error when saving to database保存到数据库时输入字符串格式错误
【发布时间】:2011-02-07 09:55:17
【问题描述】:

在 SQL Server 中,我有一个名为 AppZip 的 db 列,类型为 int。我有一个带有 5 位邮政编码的文本框。当我尝试保存时,出现错误“输入字符串的格式不正确。”我很困惑。我正在将“12345”的字符串表示形式转换为 int 类型,数据库的格式错误是怎么回事?这是我的代码。

q.AppZip =Convert.ToInt32(txtAppZip.Text);

(我正在使用 linq to sql...)

编辑:这是因为我没有停止在回发时执行填充页面加载字段的方法。

【问题讨论】:

    标签: c# asp.net linq-to-sql


    【解决方案1】:

    Convert.ToInt32() 引发了异常。在将其传递给Convert.ToInt32() 之前,请检查Text 属性的格式和Trim() 是否正确。

    string appZipText = txtAppZip.Text.Trim();
    if (!string.IsNullOrEmpty(appZipText))
    {
        q.AppZip = Convert.ToInt32(appZipText);
    }
    

    此外,您还可以在转换之前使用Int32.TryParse() 来检查字符串的有效性。

    int appZip;
    string appZipText = txtAppZip.Text.Trim();
    
    if(!string.IsNullOrEmpty(appZipText) &&
        Int32.TryParse(appZipText.Trim(),NumberStyles.Integer,CultureInfo.CurrentCulture, out appZip))
    {
       // Valid format
       // Use or assign converted value
       q.AppZip = appZip;
    }
    else 
    {
       // Cannot convert to Int32
    }
    


    更多信息

    【讨论】:

      【解决方案2】:

      检查表定义中所有列的映射。它可能是表中引发错误的其他列之一。运行 SQL Profiler 以检查生成的 SQL。

      【讨论】:

        【解决方案3】:

        引发 FormatException 的唯一方法是将一些不可转换的字符连接到原始字符串。

        确保你没有输入任何错误的字符,然后再试一次,这是我现在能看到的唯一合理的解释

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-04-24
          • 1970-01-01
          • 2012-06-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多