System.InvalidCastException when a field is blank in the Dataset VB.Net

FRANCES MACKENZIE 1 Reputation point
2020-11-09T10:41:29.64+00:00

I can’t seem to resolve this: I’ve got a dataset holding address records from an Access database. I’ve set up navigation buttons to scroll through the records (first, last, next, previous) and all is well until I hit a record that has a blank field and then I get:

System.InvalidCastException ‘Conversion from type ‘DBNull’ to type ‘String’ is not valid

I realise that I need to test the value of the dataset field and bypass it if it is empty but I can’t find the syntax to do this, can you help?

This is the Sub that is erroring:
Private Sub NavigateRecords()
txtFirstName.Text = ds.Tables(“AddressBook”).Rows(inc).Item(1)
txtLastName.Text = ds.Tables(“AddressBook”).Rows(inc).Item(2)
txtAddress1.Text = ds.Tables(“AddressBook”).Rows(inc).Item(3)
txtAddress2.Text = ds.Tables(“AddressBook”).Rows(inc).Item(4)
txtAddress3.Text = ds.Tables(“AddressBook”).Rows(inc).Item(5)
txtPostCode.Text = ds.Tables(“AddressBook”).Rows(inc).Item(6)
txtPhone.Text = ds.Tables(“AddressBook”).Rows(inc).Item(7)
txtEMail.Text = ds.Tables(“AddressBook”).Rows(inc).Item(8)
txtNotes.Text = ds.Tables("AddressBook").Rows(inc).Item(9)

End Sub

Developer technologies Visual Studio Debugging
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Xingyu Zhao-MSFT 5,381 Reputation points
    2020-11-10T02:27:39.213+00:00

    Hi FRANCESMACKENZIE-1253,
    Thank you for posting here.

    In order to detect a field is blank in the Dataset , you use the following code to do it.
    For example.

    If Not IsDBNull(ds.Tables("AddressBook").Rows(inc).Item(1)) Then  
        txtFirstName.Text = ds.Tables("AddressBook").Rows(inc).Item(1)  
    End If  
    

    Or

    txtFirstName.Text = If(IsDbNull(ds.Tables("AddressBook").Rows(inc).Item(1)), String.Empty, ds.Tables("AddressBook").Rows(inc).Item(1).ToString)  
    

    Another quick way to fix it : just add 'ToString()' method at the end.

    txtFirstName.Text = ds.Tables("AddressBook").Rows(inc).Item(1).ToString()  
    

    Hope them could be helpful.

    Best Regards,
    Xingyu Zhao

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.