1

I am trying to find a way to insert a message into a textbox if the entry in a table is null or blank. I have tried the following code, but the textbox is not displaying the message. I know I have coded wrong but cannot see it. Can someone please point out my error. Thanks

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
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
user1532468
  • 1,723
  • 8
  • 41
  • 80

1 Answers1

3

You need to test also for a blank string because IsDBNull checks only for DBNull values, not for a blank string

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

MSDN says

IsDBNull returns True if the data type of Expression evaluates to the DBNull type; otherwise, IsDBNull returns False.

Interesting comment below from @Arion, he suggests to use string.IsNullOrEmpty. So you could rewrite the test with only two calls

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

However it is important to test first for IsDBNull and then for IsNullOrEmpty because passing DBNull.Value to string.IsNullOrEmpty throws an exception

Steve
  • 213,761
  • 22
  • 232
  • 286
  • Why do you not use `string.IsNullOrEmpty()`? And re-factor the rows to `If string.IsNullOrEmpty(Fax) OrElse IsDBNull(Fax) Then` – Arion Oct 10 '13 at 14:16
  • @Arion you are right, but it is important the order of test. If you have a DBNull.Value in Fax, you should test first for IsDBNull and then for string.IsNullOrEmpty – Steve Oct 10 '13 at 14:38
  • @Steve : Yes I think that it is less work to use the built in function for checking both NULL and empty. Yes I had a brain fart on the order of the validation =).+1: Of course you have to check dbnull before null or empty – Arion Oct 11 '13 at 07:10