C# 使用bool for复选框进行强制转换时出现错误“;指定的强制转换无效"; 我有一个复选框,它从一个名为“免费”的bit列中获取数据。这里需要一个石膏:

C# 使用bool for复选框进行强制转换时出现错误“;指定的强制转换无效"; 我有一个复选框,它从一个名为“免费”的bit列中获取数据。这里需要一个石膏:,c#,asp.net,sql-server,C#,Asp.net,Sql Server,在这里,我添加bool的cast来解决这个问题 但是,它会产生一个错误。为什么?我一直在试图找出原因,但不明白为什么,因为我有其他复选框使用相同的代码并正常工作 它说: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it or

  • 在这里,我添加bool的cast来解决这个问题
  • 但是,它会产生一个错误。为什么?我一直在试图找出原因,但不明白为什么,因为我有其他复选框使用相同的代码并正常工作
  • 它说:

    An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
    
    Exception Details: System.InvalidCastException: Specified cast is not valid.
    

    不能使用“取消装箱”将字符串类型取消装箱到类型bool,我怀疑其中一个是另一个的子类,反之亦然。为此,必须使用预定义函数

    Convert.ToBoolean(reader["Complimentary"].ToString());
    
    试试这个:

    object value = reader["Complimentary"];
    
    if(value != null && value != DBNull.Value)
    {
        CbIsComplimentary.Checked = (bool)value;
    }
    else
    {
        //Optionally handle null value, e.g.:
        //CbIsComplimentary.Checked = false;
    }
    

    尝试强制转换为
    bool?
    ,因为它可能是您正在处理的空值。可能是它的字符串?然后您需要使用convert类。Convert.toboolean
    reader[“complemental”].GetType().Name
    ?@NikolaiDante我想可能是这样的,但Visual Studio无法识别
    bool?
    @YacoubMassad好的,我只是尝试了一下,然后说值为null,然后改为“DBNull”。我认为null应该意味着复选框将默认为false/未选中。就是这样。谢谢