Why i get this error?
Object cannot be cast from DBNull to other types.
when i inserted null value for a numeric datatype in sql server 2005
Here is my code,
if (MeasurementTr.Visible == true)
{
materialIn.measurementId = Convert.ToInt64(DlMeasurement.SelectedValue.ToString());
}
else
{
materialIn.measurementId = Convert.ToInt64(DBNull.Value);
}
EDIT :
Is this right??
materialIn.measurementId = (Convert.ToInt64(DlMeasurement.SelectedValue.ToString()) != 0) ? Convert.ToInt64(DlMeasurement.SelectedValue.ToString()) : 0;
You cannot convert
DBNull.ValuetoInt64as your code attempts to do inConvert.ToInt64.DBNull.Valuemeans “unknown” or “nonexistent” and therefore there is no logical conversion to any other data type.If the
materialIninstance is some form of strongly-typedDataRow, it will have aSetMeasurementIdNullmethod, which is what you need to use. If you’re using Linq to SQL or EF, you shouldn’t need to deal withDBNullat all, you would instead just writematerialIn.measurementId = null.