提问人:Nnek Lecxe 提问时间:9/21/2023 最后编辑:Nnek Lecxe 更新时间:9/21/2023 访问量:31
vb.net 如何使用 DatePicker 忽略数据库中的空数据
vb.net how to ignore empty data from database with datepicker
问:
我需要有关如何在单元格为空时跳过数据的帮助。因为并非所有数据都有日期。
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
答:
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 选项,编译器会标记你写过这样糟糕代码的许多地方。OrElse
Or
Is
=
Value
Object
Option Strict On
也就是说,它可能仍然是错误的。这是因为,如果您使用 ADO.NET 进行数据访问,则 NULL 字段将包含 ,而不是 ,因此您应该检查以下内容:DBNull.Value
Nothing
If DataGridView1.CurrentRow.Cells(7).Value Is DBNull.Value OrElse
DataGridView1.CurrentRow.Cells(8).Value Is DBNull.Value Then
最后,测试一个阳性条件,有一个空的块,然后把你的代码放在这个块中,这是很糟糕的做法。如果您只对阴性条件感兴趣,那么首先要测试阴性条件:If
Else
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
谢谢,经过多次试验和错误。这个似乎对我的问题有帮助
评论
ToString
Date
ToString
Strings
Strings