vb.net 如何使用 DatePicker 忽略数据库中的空数据

vb.net how to ignore empty data from database with datepicker

提问人:Nnek Lecxe 提问时间:9/21/2023 最后编辑:Nnek Lecxe 更新时间:9/21/2023 访问量:31

问:

我需要有关如何在单元格为空时跳过数据的帮助。因为并非所有数据都有日期。

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick


    If DataGridView1.CurrentRow.Cells(7).Value Or DataGridView1.CurrentRow.Cells(8).Value = Nothing Then

    Else
        Guna2DateTimePicker1.Value = DataGridView1.CurrentRow.Cells(7).Value.ToString
        Guna2DateTimePicker3.Value = DataGridView1.CurrentRow.Cells(8).Value.ToString
    End If
MySQL .NET vb.net

评论

0赞 jmcilhinney 9/21/2023
首先,为什么要调用单元格值,然后将结果分配给类型的属性?不要调用,除非你特别想要一个字符串表示形式。它不是在任何地方都可以使用的通用工具。不是的东西不应该被任意转换为 .ToStringDateToStringStringsStrings
0赞 jmcilhinney 9/21/2023
该问题中绝对没有与MySQL相关的内容,因此您不应该应用MySQL标签。我已经删除了它。仅添加与问题相关的标签。数据首先来自哪个数据库,与你正在做的事情没有任何关系。我还添加了相关的标签。将来对你的标签多花一点心思。如果你不知道哪些标签是相关的,那么你可能还没有充分分析问题,所以一开始就要提出问题。

答:

2赞 jmcilhinney 9/21/2023 #1

此代码是错误的:

If DataGridView1.CurrentRow.Cells(7).Value Or
   DataGridView1.CurrentRow.Cells(8).Value = Nothing Then

该代码实际执行的是:

If (DataGridView1.CurrentRow.Cells(7).Value = True) Or
   (DataGridView1.CurrentRow.Cells(8).Value = Nothing) Then

这显然不是你的本意。根据您的意图编写代码的正确方法是:

If DataGridView1.CurrentRow.Cells(7).Value Is Nothing OrElse
   DataGridView1.CurrentRow.Cells(8).Value Is Nothing Then

请注意那里的多个更改。它正在比较两个单元格值而不是一个单元格值,它是短路使用而不是使用而不是因为是类型。你应该上交你的项目属性和你的 VS 选项,编译器会标记你写过这样糟糕代码的许多地方。OrElseOrIs=ValueObjectOption Strict On

也就是说,它可能仍然是错误的。这是因为,如果您使用 ADO.NET 进行数据访问,则 NULL 字段将包含 ,而不是 ,因此您应该检查以下内容:DBNull.ValueNothing

If DataGridView1.CurrentRow.Cells(7).Value Is DBNull.Value OrElse
   DataGridView1.CurrentRow.Cells(8).Value Is DBNull.Value Then

最后,测试一个阳性条件,有一个空的块,然后把你的代码放在这个块中,这是很糟糕的做法。如果您只对阴性条件感兴趣,那么首先要测试阴性条件:IfElse

If DataGridView1.CurrentRow.Cells(7).Value IsNot DBNull.Value AndAlso
   DataGridView1.CurrentRow.Cells(8).Value IsNot DBNull.Value Then
    '...
End If

请注意比较运算符和布尔运算符的翻转。

评论

0赞 Nnek Lecxe 9/21/2023
谢谢,经过多次试验和错误。这个似乎对我的问题有帮助