【问题标题】:Checking db for null values检查数据库的空值
【发布时间】:2013-10-10 11:58:33
【问题描述】:

如果表中的条目为空或空白,我正在尝试找到一种将消息插入文本框的方法。我尝试了以下代码,但文本框未显示该消息。我知道我编码错误但看不到它。有人可以指出我的错误。谢谢

Private Sub UserDataGridView_CellContentClick(ByVal sender As System.Object,
                  ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _
                                   Handles UserDataGridView.CellContentClick
  Dim value As Object = UserDataGridView.Rows(e.RowIndex).Cells(0).Value
  Dim NoEdit As Object = UserDataGridView.Rows(e.RowIndex).Cells(1).Value
  Dim InvCnt As Object = UserDataGridView.Rows(e.RowIndex).Cells(2).Value
  Dim InvAddress As Object = UserDataGridView.Rows(e.RowIndex).Cells(3).Value
  Dim Email As Object = UserDataGridView.Rows(e.RowIndex).Cells(4).Value
  Dim Tel As Object = UserDataGridView.Rows(e.RowIndex).Cells(5).Value
  Dim Fax As Object = UserDataGridView.Rows(e.RowIndex).Cells(6).Value

  txtCustomerActive.Text = CType(value, String)
  txtCustomerNoedit.Text = CType(NoEdit, String)
  txtInvoiceContact.Text = CType(InvCnt, String)
  txtInvoiceAddress.Text = CType(InvAddress, String)
  txtEmail.Text = CType(Email, String)
  txtCustomerTelephone.Text = CType(Tel, String)

  If Fax Is Nothing OrElse IsDBNull(Fax) Then
    txtCustomerFax.Text = "No Number on record" ' Display if no record
  Else
    txtCustomerFax.Text = CType(Fax, String)
  End If

  ' txtCustomerFax.Text = CType(Fax, String)
End Sub

【问题讨论】:

    标签: vb.net visual-studio-2010


    【解决方案1】:

    您还需要测试空白字符串,因为IsDBNull 仅检查 DBNull 值,而不检查空白字符串

     If Fax Is Nothing OrElse IsDBNull(Fax) OrElse Fax = string.Empty Then
        .....   
    

    MSDN says

    如果 Expression 的数据类型计算结果为 DBNull 类型;否则,IsDBNull 返回 False。

    @Arion 下面的有趣评论,他建议使用 string.IsNullOrEmpty。 所以你可以只用两次调用来重写测试

     If IsDBNull(Fax) OrElse string.IsNullOrEmpty(Fax) then 
    

    但是,首先测试 IsDBNull 然后再测试 IsNullOrEmpty 很重要,因为将 DBNull.Value 传递给 string.IsNullOrEmpty 会引发异常

    【讨论】:

    • 为什么不使用string.IsNullOrEmpty()?并将行重构为If string.IsNullOrEmpty(Fax) OrElse IsDBNull(Fax) Then
    • @Arion 你是对的,但测试的顺序很重要。如果您在传真中有 DBNull.Value,则应先测试 IsDBNull,然后测试 string.IsNullOrEmpty
    • @Steve :是的,我认为使用内置函数检查 NULL 和空值的工作量更少。是的,我在验证的顺序上放了个屁 =).+1:当然你必须在 null 或 empty 之前检查 dbnull
    猜你喜欢
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多