g_shockTan
g_shockTan

Reputation: 355

ASP.Net VB Check if datas exist in database

How do I check if data existing in the database or is NULL. I'm getting the following error Object cannot be cast from DBNull to other types . Do I need to add IsDBNULL to the code?

SignedOn.Text = Convert.ToDateTime(reader("SignedOn")).ToShortDateString()

Upvotes: 0

Views: 470

Answers (1)

Damith
Damith

Reputation: 63105

you can check like below

If NOT IsDbNull(reader("SignedOn")) Then
   SignedOn.Text = Convert.ToDateTime(reader("SignedOn")).ToShortDateString()
End If

Edit based on comments:

  • When you know the exact type of the column you can call method relevant to that type like reader.GetDateTime, reader.GetString etc
  • After conversion if there is a possibility of result can be null then you better check for null before calling ToShortDateString
  • You can use DateTime.TryParse method if you have store date time in varchar column

Upvotes: 3

Related Questions