Search code examples
c#asp.net.netsqldatareader

C# Object null check


I read my database using DataReader.

and some row does not have fdate value.

so when I Convert the null date to DateTime then Error occurs.

How can I check the field empty or not?

AdsCommand cmd = conn.CreateCommand();
cmd.CommandText = "select name,fdate from abc";

AdsDataReader reader = cmd.ExecuteReader();

DateTime flsdate = (reader["fdate"].Equals(null))? Convert.ToDateTime(reader["fdate"]) : DateTime.Today;

I tried with Equals, but it does not work.

anybody know how to check the null object to avoid convert error?

Thank you!


Solution

  • As everyone pointed you how to solve the issue, I am trying to give you the info regarding what is the difference between NULL and DBNull.

    • null and DBNull are different.

    • null is not an instance of any type. DBNull is a singleton class with one instance: DBNull.Value.

    • null represents an invalid reference where as DBNull.Value represents a nonexistent value in DB.

    • DBNull.Value is what db providers provide for a nonexistant value in a table.

    With that background (reader["fdate"].Equals(null)) is not correct to use here. You have to check it with DBNull.Value. If it is of type DBNull, or if it is equal to DBNull.Value, then assign what ever value you like.