【问题标题】:How ignore NULL entries on a datagridview如何忽略 datagridview 上的 NULL 条目
【发布时间】:2016-12-12 12:20:12
【问题描述】:

我有一段代码从datagridview 中读取整数和日期值。一些k 值中有空条目,我试图让应用程序忽略这些单元格,但我没有任何运气。在线弹出错误 j = datediff....

我尝试过使用 if 语句

If DataGridView1.Rows(e.RowIndex).Cells(k).Value IsNot Nothing Then 但它仍然会产生一个错误,告诉我它无法将DBNull 条目转换为date

我看不出我做错了什么,因此我们将不胜感激。

    For k = 8 To 52 Step 2

        Dim j As Integer

        If DataGridView1.Rows(e.RowIndex).Cells(k).Value IsNot Nothing Then

            j = DateDiff(DateInterval.Day, DataGridView1.Rows(e.RowIndex).Cells(k).Value, DataGridView1.Rows(e.RowIndex).Cells(k - 2).Value)

            If DataGridView1.Rows(e.RowIndex).Cells(k + 1).Value = 0 Then

                If j > 7 Then
                    DataGridView1.Rows(e.RowIndex).Cells(k - 1).Value = 6
                Else
                End If
            Else
            End If
        End If

    Next k

【问题讨论】:

  • 因为Nothing 不是DbNull。将DbNull.Value 的比较添加到条件
  • If Not IsDBNull(k) then... 这样的 if 语句是否有效?

标签: .net vb.net datagridview null


【解决方案1】:

如果您想在识别编译时可能出现的错误方面获得更多帮助,请在您的项目或文件中设置Option Strict On

  • NothingDbNull 不一样。
  • Nothing 是类型的默认值
  • DbNullus 类型,代表数据库NULL 值。
  • 只有 DbNull.Value 具有可比性。
For k = 8 To 52 Step 2
    Dim row As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
    If row.Cells(k).Value Is DBNull.Value Or row.Cells(k).Value Is Nothing Then Continue For

    Dim firstDate As Date = DirectCast(row.Cells(k).Value, Date)
    Dim secondDate As Date = DirectCast(row.Cells(k - 2).Value, Date)
    Dim difference As TimeSpan = firstDate - secondData

    If difference.Days > 7 AndAlso row.Cells(k + 1).Value = 0 Then
        row.Cells(k - 1).Value = 6
    End If

Next

【讨论】:

  • 感谢您的回复!我现在明白 nothing 和 DBNull 之间的区别了。我试过把你的代码放进去,但在If Row.Cells(k).Value = DBNull.value Then Continue For 行弹出一个错误说:运算符'=' 没有为'Date' 类型和'DBNull' 类型定义。有什么建议吗?
  • DataGridVIewCell.Value 返回object 类型的值,所以使用Is 关键字而不是=
  • 感谢该部分现在正在工作。现在弹出dim firstdate as date... 行的错误并说:对象引用未设置为对象的实例。我将代码改回原来的j = ...,应用程序接受了它,但代码没有做任何事情
  • 别担心@Fabio 我已经通过将If Row.Cells(k).Value s DBNull.value Then Continue For 换成If row.Cells(k).Value Is DBNull.Value Or row.Cells(k).Value Is Nothing Then Continue For 来修复它。感谢您的帮助,我会接受您的回答
猜你喜欢
  • 2011-04-24
  • 1970-01-01
  • 2018-12-05
  • 1970-01-01
  • 2021-03-07
  • 2018-04-10
  • 1970-01-01
  • 1970-01-01
  • 2018-09-06
相关资源
最近更新 更多