[英]Im having an error Object cannot be cast from DBNull to other types
我在返回Convert.ToInt32(dataGridView1 [0,Row] .Value)时出错。 它说“对象不能从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();
}
这里有两个可能的问题:
对于问题1,请确保您正在执行的查询不允许使用空值。 也许您缺少过滤器...?
对于问题2,您需要检查null值:
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
或将try-catch
块与NullReferenceException
如下所示
try
{
return Convert.ToInt32(dataGridView1[0, Row].Value);
}
catch(NullReferenceException e)
{
return 0;//No such student ID when NULL is encountered.
}
您应该检查DBNull.Value。 它与null不同。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.