0

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()
g_shockTan
  • 325
  • 2
  • 8
  • 15

1 Answers1

3

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
Damith
  • 62,401
  • 13
  • 102
  • 153
  • 1
    You should look at the .GetDateTime (.GetString, GetInt32 ) methods instead of using the "GetValue" (which is used as the default I believe). – granadaCoder May 01 '13 at 18:44
  • @granadaCoder can you please add MSDN reference to this method? it will helpful for all. and normally [SqlDataReader.GetDateTime](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getdatetime.aspx) required to check for dbnull before calling. – Damith May 01 '13 at 18:53
  • 1
    The "check" is correct. I'm not arguing that. But I think you have a default to "GetValue" with this code : reader("SignedOn") – granadaCoder May 01 '13 at 18:55
  • 1
    Here is my C# converted code to VB.NET that I think is correct. – granadaCoder May 01 '13 at 19:08
  • @granadaCoder can you get date time by column name? and you assign date time to a string! – Damith May 01 '13 at 19:12
  • 1
    If Not (dataReader.IsDBNull(0)) Then dim d1 As DateTime = dataReader.GetDateTime(0) End If – granadaCoder May 01 '13 at 19:15
  • 1
    I don't know about the by "column name". That will have to be attempted. But the rule of thumb is that "GetString" "GetDateTime" are preferred over the "GetValue" when the type is known. – granadaCoder May 01 '13 at 19:16
  • 1
    I always code to the interface, not the concrete. My "converter" code uses IDataReader, not any of the concretes. – granadaCoder May 01 '13 at 19:16
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/29265/discussion-between-damith-and-granadacoder) – Damith May 01 '13 at 19:18