0

返回 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

4 回答 4

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);
}
于 2013-09-08T16:00:11.867 回答
0

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

检查NULL或使用如下所示的try-catchNullReferenceException

try
{
 return Convert.ToInt32(dataGridView1[0, Row].Value);
}
catch(NullReferenceException e)
{
return 0;//No such student ID when NULL is encountered.
}
于 2013-09-08T15:52:33.470 回答
0

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

if(DBNull.Value != dataGridView1[0, Row].Value)
{
    // do convertion, etc
}
else
{
    // handle null case
}
于 2013-09-08T16:01:03.030 回答
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);
于 2013-09-08T17:25:35.490 回答