Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法将DBNULL值插入sql server_C#_Sql Server 2005_Dbnull - Fatal编程技术网

C# 无法将DBNULL值插入sql server

C# 无法将DBNULL值插入sql server,c#,sql-server-2005,dbnull,C#,Sql Server 2005,Dbnull,为什么我会犯这个错误 Object cannot be cast from DBNull to other types. 当我在SQLServer2005中为数字数据类型插入空值时 这是我的密码 if (MeasurementTr.Visible == true) { materialIn.measurementId = Convert.ToInt64(DlMeasurement.SelectedValue.ToString()); } else

为什么我会犯这个错误

Object cannot be cast from DBNull to other types.
当我在SQLServer2005中为数字数据类型插入空值时

这是我的密码

 if (MeasurementTr.Visible == true)
    {
        materialIn.measurementId = Convert.ToInt64(DlMeasurement.SelectedValue.ToString());
    }
    else
    {
        materialIn.measurementId = Convert.ToInt64(DBNull.Value);
    }
编辑

是这样吗

 materialIn.measurementId = (Convert.ToInt64(DlMeasurement.SelectedValue.ToString()) != 0) ? Convert.ToInt64(DlMeasurement.SelectedValue.ToString()) : 0;

因为该
对象不能从DBNull转换为其他类型。

因此,您需要做的是检查
DBNull
的值

materialIn.measurementId=DlMeasurement.SelectedValue==DBNull.Value?0:Convert.ToInt64(DlMeasurement.SelectedValue.ToString())


您无法将
DBNull.Value
转换为
Int64
,因为您的代码试图在
convert.ToInt64
中进行转换
DBNull.Value
表示“未知”或“不存在”,因此不存在到任何其他数据类型的逻辑转换


如果
materialIn
实例是某种形式的强类型
DataRow
,它将有一个
setmeasurementnull
方法,这就是您需要使用的方法。如果您使用的是Linq to SQL或EF,则根本不需要处理
DBNull
,而是只需编写
materialIn.measurementId=null

DBNull不会转换为Int64。您需要使用可为null的int,然后将null存储在值中,或者对该值执行一些操作以表示null,例如可以存储在属性中的0。

@Mendy Operator'=='不能应用于'string'和'System.DBNull'类型的操作数,但SelectedValue是object,不是吗?不。您不能将DBNull转换为Int64。您需要首先验证对象值不是DBNull!问题出在
else
块上。我确信
if
块很好(
ToString
永远不能返回
DBNull.Value
)。正如我所说的-使用
DataRow
上的
SetNull
setmeasurementnull
方法,如果是这样的话,或者将其设置为
null
default(Int64)
,如果它不可为空。@a尽管我错过了其他部分。。。你说得对,而且+1。