izzykk
izzykk

Reputation: 31

Handling null values in C# - uploaded excel data sheet to database

I'm trying to read in items from a spread sheet into a data table, which can then be uploaded to a database.

The column I'm having issues with has to read in values that are boolean values. However, sometimes the field is empty. Instead of 0's and 1's, I need to store null into this boolean value when the field is empty.

Here is the original line of code:

  bool bool2 = Convert.ToBoolean(row["Bool_02"]);

This works well when the field isn't empty. But I can't check if the field is empty first because you can't store null as a boolean value. I tried making it a nullable value like so:

   bool? bool2 = Convert.ToBoolean(row["Bool_02"]);
     if(bool2 != true || false)
       {
          bool2 = null;
       }

But I get an error - object cannot be cast from DBNull to other types.

I have to take the input of the column, check if its empty - if its empty then save null in the bool variable.

How can I do this?

Upvotes: 0

Views: 1094

Answers (1)

Klaycon
Klaycon

Reputation: 11080

But I can't check if the field is empty first because you can't store null as a boolean value.

Sure you can, just check if the field is DBNull before trying to convert it.

if(row["Bool_02"] is DBNull) return;
bool bool2 = Convert.ToBoolean(row["Bool_02"]);

If you'd like to stuff it in a nullable boolean, you need a ternary.

bool? bool2 = row["Bool_02"] is DBNull ? null : Convert.ToBoolean(row["Bool_02"]);

Untested, you might need a typecast to (bool?) in that ternary for it to compile.

Upvotes: 3

Related Questions