2013-10-10 79 views
1

我想找到一种方法来将消息插入到文本框中,如果表中的项为空或空白。我试过下面的代码,但是文本框没有显示消息。我知道我错了,但看不到它。有人可以指出我的错误。由于检查数据库空值

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 

回答

3

你也需要测试一个空字符串,因为IsDBNull仅检查DBNull的值,而不是一个空字符串,如果数据

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

MSDN says

IsDBNull以便返回True表达式类型的计算结果为 DBNull类型;否则,IsDBNull返回False。

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

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

但是它首先对IsDBNull以便再进行试验,为IsNullOrEmpty因为通过DBNull.Value到string.IsNullOrEmpty抛出一个异常

+0

是很重要的你为什么不使用'string.IsNullOrEmpty()'?并重新将行分配给'如果string.IsNullOrEmpty(传真)OrElse IsDBNull(传真)然后' – Arion

+0

@Arion你是对的,但它是重要的测试顺序。如果传真中有一个DBNull.Value,则应该首先测试IsDBNull,然后再测试string.IsNullOrEmpty – Steve

+0

对于string.IsNullOrEmpty为+1。 – Neolisk