c# - Casting DBNull to boolean -
hello can't seems solve cast operation. error:
string not recognized valid boolean
for line
iskey = convert.toboolean(row["iskey"].tostring()); i'm using datareader table schema. iskey presently null everywhere in db. want 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());
first, use format getting values datarow:
string columnname = row.field<string>("columnname"); string columntype = row.field<string>("datatypename"); //this uses first , second variable call example this defines returning value , conversion you.
your problem have column bit (or @ least hope it's bit), allows nulls. means datatype in c# bool?. use this:
bool? iskey = row.field<bool?>("iskey"); your second question (in comments):
if bool? iskey return null how can convert false?
the easiest way use null-coalescing operator
bool iskey = row.field<bool?>("iskey") ?? false; this says: "give me first thing not null, either column value or "false".
Comments
Post a Comment