nullable type cast question

  • Thread starter Thread starter DMG
  • Start date Start date
D

DMG

Why does this fail with a cast exception? The field is coming in from
the data base as null due some bad design on my part but I thought this
would allow me to test and set to false.


DataTableReader dtr = ds.CreateDataReader();

bool? bTest = ((bool?)dtr["isTestField"]??false);


Thanks in advance for any help.
 
Hi,

dtr["isTestField"] is probably returning DBNull.

Try the following instead:

bool? bTest;
if (dtr["isTestField"] is DBNull)
bTest = null;
else
bTest = (bool) dtr["isTestField"];
 
DMG said:
Why does this fail with a cast exception? The field is coming in from
the data base as null due some bad design on my part but I thought this
would allow me to test and set to false.


DataTableReader dtr = ds.CreateDataReader();

bool? bTest = ((bool?)dtr["isTestField"]??false);

Because the type of the column in the dataset is not bool?, nor does it have
the value null. It's of type DBNull and has the value DBNull.Value.

Use something like:

DBNull.Value.Equals(dtr["isTestField"]) ? false : (bool)dtr["isTestField"];

Unfortunately, they remembered to provide a string overload of the indexer,
but not a string overload of DataTableReader.IsDBNull. If you know the
column ordinal, you can use that instead of the column name and write

dtr.IsDBNull(iOrdinal) ? false : (bool)dtr["iOrdinal];

-cd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top