3

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;
bala3569
  • 10,832
  • 28
  • 102
  • 146
  • No. you cannot convert DBNull to Int64. You need to validate first that the object value isn't DBNull! – Fitzchak Yitzchaki Jan 26 '10 at 05:20
  • 1
    It's the `else` block that's the problem. I'm sure that the `if` block is fine (`ToString` can never return `DBNull.Value`). As I said - use the `SetNull` or `SetmeasurementIdNull` method on the `DataRow`, if that's what it is, or just set it to `null` or `default(Int64)` if it's non-nullable. – Aaronaught Jan 26 '10 at 05:29
  • @Aaronaught I missed the else part... you right and +1. – Fitzchak Yitzchaki Jan 26 '10 at 05:44

3 Answers3

5

You cannot convert DBNull.Value to Int64 as your code attempts to do in Convert.ToInt64. DBNull.Value means "unknown" or "nonexistent" and therefore there is no logical conversion to any other data type.

If the materialIn instance is some form of strongly-typed DataRow, it will have a SetMeasurementIdNull method, which is what you need to use. If you're using Linq to SQL or EF, you shouldn't need to deal with DBNull at all, you would instead just write materialIn.measurementId = null.

Aaronaught
  • 120,909
  • 25
  • 266
  • 342
1

Because that Object cannot be cast from DBNull to other types.

So what you need to do is to check the value for DBNull.

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

Fitzchak Yitzchaki
  • 9,095
  • 12
  • 56
  • 96
0

DBNull doesn't convert to an Int64. You will need to use a nullable int and then store null in the value or do something with the value to represent null such as 0 that can be stored in your property.

Kelsey
  • 47,246
  • 16
  • 124
  • 162