C # Object null check

I read my database using DataReader.

and some line doesn't matter fdate.

so when I convert the null date to DateTime, an error occurs.

How can I check an empty field 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 using Equals, but it does not work.

Does anyone know how to check a null object to avoid a conversion error?

Thanks!

+8
c # sql datareader
source share
6 answers

As everyone has shown you how to solve the problem, I am trying to give you information about the difference between NULL and DBNull.

  • null and DBNull are different.

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

  • null represents an invalid reference, where DBNull.Value represents a nonexistent value in the database.

  • DBNull.Value is that db providers provide a non-steric value in a table.

With this background (reader["fdate"].Equals(null)) is incorrect to use here. You should check this with DBNull.Value . If it is of type DBNull , or if it is equal to DBNull.Value , then assign any value that you like.

+11
source share
+5
source share

In this situation, I like to represent columns of a null database with a reference type (row for varchar) or Nullable wrapped value type (DateTime?). Thus, you more accurately represent the database schema in your program.

It also allows you to more clearly write the conversion logic in the format:

 DateTime? fdate = datareader["fdate"] as DateTime?; 

This action will not be performed if the result of the datareader is DbNull, and fdate will be set by default (DateTime?), Which is null. At this point, you can get your real desired value by checking if the value is nullable or not (fdate.HasValue), and if not, use your default DateTime.Today.

+4
source share
 DateTime flsdate = reader["fdate"].Equals(DBNull.Value) ? Convert.ToDateTime(reader["fdate"]) : DateTime.Today; 

But it seems dangerous to use the Today date by default. I would do this instead:

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

Also, if the base tpe of the fdate column fdate already a DateTime, do not use System.Convert:

 DateTime? flsdate = reader["fdate"].Equals(DBNull.Value) ? (DateTime?)reader["fdate"]) : null; 
+2
source share

Try the following:

 DateTime flsdate = reader["fdate"] != null && reader["fdate"] != System.DbNull.Value ? DateTime.ParseExact(reader["fdate"]) : DateTime.Today; 
+1
source share
 DateTime flsdate = DateTime.Today; if(reader["fdate"] != null) flsdate = Convert.ToDateTime(reader["fdate"]) 
+1
source share

All Articles