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

VB.NET:点击DataGridView时如何忽略空数据赋值给DatePicker

修正DataGridView单元格空值判断与DateTimePicker赋值问题

原代码存在的问题

  1. 条件判断逻辑错误:

    • 误用Or而非OrElse,会强制求值两个条件,效率低且易引发异常
    • 仅判断= Nothing不完整,DataGridView单元格的空值通常以DBNull.Value形式存在,需同时覆盖这两种情况
    • 原条件写法不规范,DataGridView1.CurrentRow.Cells(7).Value单独放在条件中会被当作布尔值判断,而非空值检查
  2. 赋值类型不匹配:

    • Guna2DateTimePicker.Value是DateTime类型,直接赋值ToString()生成的字符串会触发类型转换错误,需将单元格值转为DateTime类型再赋值

修正后的代码

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
    ' 获取当前行目标单元格的值
    Dim cell7Value = DataGridView1.CurrentRow.Cells(7).Value
    Dim cell8Value = DataGridView1.CurrentRow.Cells(8).Value

    ' 仅当两个单元格都不为空时执行赋值
    If Not (cell7Value Is Nothing OrElse cell7Value Is DBNull.Value) AndAlso 
       Not (cell8Value Is Nothing OrElse cell8Value Is DBNull.Value) Then
        Guna2DateTimePicker1.Value = Convert.ToDateTime(cell7Value)
        Guna2DateTimePicker3.Value = Convert.ToDateTime(cell8Value)
    Else
        ' 若任一单元格为空,可选择重置DateTimePicker或保留原有值(按需调整)
        ' 示例:重置为当前时间
        Guna2DateTimePicker1.Value = DateTime.Now
        Guna2DateTimePicker3.Value = DateTime.Now
        ' 若只需跳过赋值不修改原有值,可删除Else块内容
    End If
End Sub

可选:对应列独立处理方案

如果需求是某列空则不赋值对应DateTimePicker,非空则赋值(而非任一空就都不赋值),可使用以下代码:

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
    ' 处理第7列对应控件
    Dim cell7Value = DataGridView1.CurrentRow.Cells(7).Value
    If Not (cell7Value Is Nothing OrElse cell7Value Is DBNull.Value) Then
        Guna2DateTimePicker1.Value = Convert.ToDateTime(cell7Value)
    End If

    ' 处理第8列对应控件
    Dim cell8Value = DataGridView1.CurrentRow.Cells(8).Value
    If Not (cell8Value Is Nothing OrElse cell8Value Is DBNull.Value) Then
        Guna2DateTimePicker3.Value = Convert.ToDateTime(cell8Value)
    End If
End Sub

关键说明

  • 使用OrElse和AndAlso实现短路求值,避免不必要的判断,提升代码效率
  • 同时检查Is Nothing和Is DBNull.Value,覆盖DataGridView单元格空值的两种常见场景
  • 用Convert.ToDateTime()安全转换类型,避免类型不匹配错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 06:22:32