将DBNull转换为布尔值

eet*_*wil 7 c#

您好我似乎无法解决此强制转换操作.我收到错误:

字符串未被识别为有效的布尔值

为线

isKey = Convert.ToBoolean(row["IsKey"].ToString());
Run Code Online (Sandbox Code Playgroud)

我正在使用一个DataReader来获取我的表Schema.IsKey目前null在我的数据库中无处不在.我基本上想要一个true或一个false结果.

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());
Run Code Online (Sandbox Code Playgroud)

gun*_*171 21

首先,使用此格式从以下位置获取值DataRow:

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

这强烈定义了返回值并为您进行转换.

你的问题是你有一个列bit(或者至少我希望它有点),但也允许nulls.这意味着c#中的数据类型是a bool?.用这个:

bool? isKey = row.Field<bool?>("IsKey");
Run Code Online (Sandbox Code Playgroud)

你的第二个问题(在评论中):

如果布尔?isKey返回NULL如何将其转换为false?

最简单的方法是使用 Null-Coalescing Operator

bool isKey = row.Field<bool?>("IsKey") ?? false;
Run Code Online (Sandbox Code Playgroud)

这说:"首先给我的不是空的,无论是列值还是"假".