You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET DataTable查询报错(DBNull值):统计PreparedBy列非空记录数

解决方案

方法1:使用LINQ(类型安全,推荐)

通过AsEnumerable()将DataTable转为可枚举集合,拆分判断逻辑,同时处理DBNull和空字符串:

Dim iCountPrepared As Integer = dtLeft.AsEnumerable().Count(Function(row)
    row.Field(Of String)("Type") = "Dep" AndAlso
    Not row.IsNull("PreparedBy") AndAlso
    Not String.IsNullOrEmpty(row.Field(Of String)("PreparedBy"))
)

如果需要同时过滤纯空格的内容,可将最后一行改为:

Not String.IsNullOrEmpty(row.Field(Of String)("PreparedBy").Trim())

方法2:使用DataTable原生Select方法

直接用类SQL的过滤表达式,简洁处理两种空值情况:

' 过滤规则:Type为"Dep",PreparedBy既非DBNull也非空字符串
Dim filteredRows() As DataRow = dtLeft.Select("Type = 'Dep' AND PreparedBy IS NOT NULL AND PreparedBy <> ''")
Dim iCountPrepared As Integer = filteredRows.Length

原代码问题说明

你之前使用的IIf会返回Object类型,后续强制转换容易引发类型错误;改用VB.NET的If运算符(类型安全)可避免此类问题,同时拆分判断逻辑能让代码更清晰易维护。

内容的提问来源于stack exchange,提问作者smartini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 22:42:00