【问题标题】:Im having an error Object cannot be cast from DBNull to other types我有一个错误 Object cannot be cast from DBNull to other types
【发布时间】:2013-09-08 15:49:23
【问题描述】:

返回 Convert.ToInt32(dataGridView1[0, Row].Value); 时出错它说“对象不能从 DBNull 转换为其他类型。”我在学生 ID 上的数据库字段是 int。这是我的代码:

 public int GetStudentID()
    {
        // The Student ID is the first cell of the current row
        int Row = dataGridView1.CurrentRow.Index;
        return Convert.ToInt32(dataGridView1[0, Row].Value);
    }

    public string GetISBN()
    {
        // The ISBN is the second cell of the current row
        int Row = dataGridView1.CurrentRow.Index;
        return dataGridView1[1, Row].Value.ToString();
    }

【问题讨论】:

  • 如果您的代码在数据库中找到空值,您希望您的代码做什么?

标签: c# sql-server


【解决方案1】:

这里有两个可能的问题:

  1. 您正在从数据库中获取空值,但始终需要一个值
  2. 您正在从数据库中获取空值,但未处理它们

对于问题 1,确保您正在执行的查询不允许空值。也许您缺少过滤器...?

对于问题2,需要检查空值:

public int GetStudentID()
{
    int Row = dataGridView1.CurrentRow.Index;
    var val = dataGridView1[0, Row].Value;

    if (object.Equals(val, DBNull.Value))
    {
        /* either throw a more appropriate exception or return a default value */
        // let's assume a default value is fine
        return -1;
    }

    return Convert.ToInt32(val);
}

【讨论】:

    【解决方案2】:

    您的dataGridView1[0, Row].Value 必须是NULL

    检查NULL 或使用try-catch 块和NullReferenceException,如下所示

    try
    {
     return Convert.ToInt32(dataGridView1[0, Row].Value);
    }
    catch(NullReferenceException e)
    {
    return 0;//No such student ID when NULL is encountered.
    }
    

    【讨论】:

    【解决方案3】:

    您应该检查 DBNull.Value。和null不一样。

    if(DBNull.Value != dataGridView1[0, Row].Value)
    {
        // do convertion, etc
    }
    else
    {
        // handle null case
    }
    

    【讨论】:

      【解决方案4】:

      有一个方法来管理这个小细节很方便,例如:

      email = Database.GetValueOrNull<string>(sqlCommand.Parameters["@Email"].Value);
      

      这样实现的:

      public static T GetValueOrNull<T>(Object column)
      {
          // Convert   DBNull   values to   null   values for nullable value types, e.g.   int? , and strings.
          //   NB: The default value for non-nullable value types is usually some form of zero.
          //       The default value for   string   is    null .
      
          // Sadly, there does not appear to be a suitable constraint ("where" clause) that will allow compile-time validation of the specified type <T>.
      
          Debug.Assert(Nullable.GetUnderlyingType(typeof(T)) != null || typeof(T) == typeof(string), "Nullable or string types should be used.");
      
          if (!column.Equals(DBNull.Value)) // Don't trust   ==   when the compiler cannot tell if type <T> is a class.
              return (T)column;
      
          return default(T); // The default value for a type may be   null .  It depends on the type.
      }
      

      通过空转换将数据从变量移动到数据库参数可以这样完成:

      sqlCommand.Parameters.AddWithValue("@Serial", serial ?? (object)DBNull.Value);
      

      【讨论】:

        猜你喜欢
        • 2022-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-15
        相关资源
        最近更新 更多