-1

Good day, everyone!

I would like to ask for any advice or suggestion..

I got this error: object cannot be cast from DBNull to other types, but the field that it access or referred to does not have null value. How can it be?

Here is the piece of code:

int pregnant = Convert.ToInt32((dtRw)["pregnant"]);

Thank you so much.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
newbie
  • 3
  • 1
  • 8

1 Answers1

2

DBNull and null are different. While null is not an instance of any type, System.DbNull.Value is an instance of System.DbNull. Read more at What is the difference between null and System.DBNull.Value?

Following code will fail

if ((dtRw)["pregnant"] != null)
   int pregnant = Convert.ToInt32((dtRw)["pregnant"]);

but this will work correct

if (!(dtRw)["pregnant"] is DBNull)
   int pregnant = Convert.ToInt32((dtRw)["pregnant"]);

If you use MySqlDataReader then there is the IsDBNull Method which can check whether the column contains non-existent or missing value.

if(dtRw.IsDBNull("pregnant")) {
   int pregnant = Convert.ToInt32((dtRw)["pregnant"]);
Community
  • 1
  • 1
user2316116
  • 6,726
  • 1
  • 21
  • 35