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

时间:2013-09-08 15:49:23

标签: c# sql-server

我在返回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();
    }

4 个答案:

答案 0 :(得分:1)

这里有两个可能的问题:

  1. 您从数据库中获取空值但总是期望值
  2. 您从数据库中获取空值但未处理它们
  3. 对于问题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);
    }
    

答案 1 :(得分:0)

您的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.
}

答案 2 :(得分:0)

您应该检查DBNull.Value。它与null不同。

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

答案 3 :(得分:0)

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

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