检查db是否为空值

时间:2013-10-10 11:58:33

标签: vb.net visual-studio-2010

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

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

1 个答案:

答案 0 :(得分:3)

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

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

MSDN says

  

如果Expression的数据类型求值为,则IsDBNull返回True   DBNull类型;否则,IsDBNull返回False。

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

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

然而,首先测试IsDBNull然后测试IsNullOrEmpty是很重要的,因为将DBNull.Value传递给string.IsNullOrEmpty会抛出异常