我有一个错误 对象不能从 DBNull 转换为其他类型的对象

本文关键字:对象 其他 类型 转换 有一个 错误 不能 DBNull | 更新日期: 2023-09-27 18:30:45

我在返回 Convert.ToInt32(dataGridView1[0, Row] 时出错。值);它说"对象不能从DBNull转换为其他类型。我的学生证数据库字段是 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();
    }

我有一个错误 对象不能从 DBNull 转换为其他类型的对象

这里有两个可能的问题:

  1. 您从数据库中获取空值,但始终期望一个值
  2. 您从数据库中获取空值,但没有处理它们

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

对于问题 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);
}

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

检查NULL或使用如下所示NullReferenceExceptiontry-catch

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

你应该检查DBNull.Value。它与空不同。

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

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

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);