爲什麼我得到這個錯誤?不能將DBNULL值插入到sql server中
Object cannot be cast from DBNull to other types.
當我插入空值在SQL Server 2005
這裏是我的代碼數字類型,
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轉換爲Int64。您首先需要驗證對象值不是DBNull! – 2010-01-26 05:20:58
這是'else'塊,這是問題所在。我確定'if'塊沒問題('ToString'永遠不會返回'DBNull.Value')。正如我所說 - 在DataRow上使用'SetNull'或'SetmeasurementIdNull'方法,如果是這樣的話,或者如果它是不可空的,只是將其設置爲'null'或'default(Int64)'。 – Aaronaught 2010-01-26 05:29:50
@Aaronaught我錯過了其他部分......你正確和+1。 – 2010-01-26 05:44:00