System.InvalidCastException 越线后上线

System.InvalidCastException on line after stepping past line

我收到以下错误: 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 中以编程方式创建列 "Use",如下所示:

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

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

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