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());
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With