Insert null value in whole column

Through the front end, I want to insert a NULL value into a column whose DataType is Int.

I used like this:

POP.JobOrderID = Convert.ToInt32(DBNull.Value); 

But I can’t insert a Null value, it throws an error such as "Object cannot be cast from DBNull to other types":

How to insert null values?

+7
source share
5 answers

if you want to do this POP.JobOrderID must be an int? type int? ( nullable int) not int

+7
source

kleinohad is right. In addition, you should assign null , not DBNull.Value

+5
source

Use Nullable<Int32> or just an alias: int? .

 POP.JobOrderID = 5; // or POP.JobOrderID = null; 

Usage in ADO.NET:

 command.Parameters.AddWithValue("@JobOrderId", POP.JobOrderID ?? DBNull.Value); 

which is equal to:

 POP.JobOrderID.HasValue ? POP.JobOrderID.Value : DBNull.Value; 
+4
source

it

  POP.JobOrderID = new Nullable<Int32>(); 

should also work if JobOrderID is a type with a null value ( int? ).

Greetings

+2
source

Like this:

  POP.JobOrderID = null; // JobOrderID should be of type int? which is a nullable-int 

Hope this helps.

0
source

All Articles