单步执行过去行后的System.InvalidCastException

时间:2017-10-27 12:57:53

标签: c# datagridview ienumerable

我收到以下错误: mscorlib.dll

中发生了未处理的“System.InvalidCastException”类型异常

附加信息:无法将对象从DBNull强制转换为其他类型。

单步执行时会出现此错误,但仅在运行其后的行后才会显示。 (视觉工作室然后指向错误的前一行)。

IEnumerable<DataGridViewRow> CheckedRows = from DataGridViewRow r in dgv_PermitInfo.Rows where Convert.ToBoolean(r.Cells["Use"].Value) == true select r; //Line that error points to, specifically the Convert.ToBoolean section

if (CheckedRows.Count() > 0) //Line when error triggers

此外,在我的项目的另一部分,我有以下几行:

IEnumerable<DataGridViewRow> CheckedRows = from DataGridViewRow r in dgv_VersionInformation.Rows where Convert.ToBoolean(r.Cells["dgvckbcl_VersionInformation_Use"].Value) == true select r;

if (CheckedRows.Count() > 0)

这些行有效。

唯一的区别是,在dgv_VersionInformation中,所有列都是硬编码的,在dgv_PermitInfo中,我在DataTable中以编程方式创建“使用”列,如下所示:

DT.Columns.Add(new DataColumn("Use", typeof(bool)));

然后将DT绑定为数据源。我假设这是导致我的问题的硬编码与绑定,但我不知道为什么或如何解决它。

1 个答案:

答案 0 :(得分:1)

您需要通过将AllowDBNull设置为Use来指定false DataColumn不允许空值。