使用bool为复选框进行强制转换会出现错误“指定的强制转换无效”

时间:2016-01-19 21:36:02

标签: c# asp.net sql-server

  1. 我有这个复选框,从名为Complimentary的位列获取数据。这需要演员:
  2. enter image description here

    1. 这里我添加bool的演员来解决问题。
    2. enter image description here

      1. 然而它会产生错误。为什么?我一直试图找出它并且看不清楚原因,因为我有其他复选框使用相同的代码并正常工作。
      2. enter image description here

        它说:

        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.
        

2 个答案:

答案 0 :(得分:1)

你不能使用拆箱将字符串类型拆箱到类型bool我怀疑一个是另一个的子类,反之亦然。你必须使用预定义的功能。

Convert.ToBoolean(reader["Complimentary"].ToString());

Convert.ToBoolean Method (String)

答案 1 :(得分:1)

试试这个:

object value = reader["Complimentary"];

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