Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting DBNull to boolean

Tags:

c#

Hello I can't seems to solve this cast operation. I get error:

String not recognized as a valid boolean

for the line

isKey = Convert.ToBoolean(row["IsKey"].ToString());

I'm using a DataReader to get my table Schema. IsKey is presently null everywhere in my DB. I basically want a true or false result.

tableSchema = myReader.GetSchemaTable();     

foreach (DataRow row in tableSchema.Rows)
{
    string columnName = row["ColumnName"].ToString();
    string columnType = row["DataTypeName"].ToString();               
    bool isKey = Convert.ToBoolean(row["IsKey"].ToString());
like image 260
eetawil Avatar asked Sep 04 '13 15:09

eetawil


1 Answers

First, use this format for getting values from a DataRow:

string columnName = row.Field<string>("ColumnName");
string columnType = row.Field<string>("DataTypeName"); 
//this uses your first and second variable call as an example

This strongly defines the returning value and does conversion for you.

Your problem is that you have a column that is a bit (or at least I hope it's a bit), but also allows nulls. This means that the datatype in c# is a bool?. Use this:

bool? isKey = row.Field<bool?>("IsKey");

Your second question (in the comments):

if bool? isKey return NULL how can I convert that to false?

The easiest way is to use a Null-Coalescing Operator

bool isKey = row.Field<bool?>("IsKey") ?? false;

This says: "give me first thing that is not null, either the column value or "false".

like image 181
gunr2171 Avatar answered Sep 30 '22 02:09

gunr2171