将DBNull转换为布尔值

时间:2013-09-04 15:29:59

标签: c#

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

  

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

为行

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

我正在使用DataReader来获取我的表Schema。我的数据库中IsKey目前只有null。我基本上想要truefalse结果。

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());

1 个答案:

答案 0 :(得分: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

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

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

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

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

  

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

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

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

这说:“首先给我的不是空的,无论是列值还是”假“。

相关问题