简体   繁体   中英

How to handle [NULL] values of datetime from SQL Server to a datetimepicker

SqlCommand cmd = new SqlCommand("SELECT dateReceived FROM table1", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();

if (dr.HasRows)
{
     while (dr.Read())
     {
          object sqlDateTime = dr[0];
          DateTime? dt = (sqlDateTime == System.DBNull.Value)
                         ? (DateTime?)null
                         : Convert.ToDateTime(sqlDateTime);

          dtDateReceived.Value = sqlDateTime;
     }
 }

 dr.Close();
 cmd.Dispose();
 conn.Close();

This is my code for getting the dateReceived in table1 considering that it might have a null value on the column dateReceived.

I would like to display it in a datetimepicker in windows form but I am getting an error :

Cannot implicitly convert type 'object' to System.DateTime

All I wanted is to display the value (if not null) onto the datetimepicker control. If null then nothing will happen.

you can use

var dateTime = dr[0] as DateTime;

it will either return null or datetime.

You can use this:

static async void Main(string[] args)
{
   SqlConnection connection = new SqlConnection();

   SqlCommand command = new SqlCommand("", connection);

   SqlDataReader reader = command.ExecuteReader();

   while (await reader.ReadAsync())
   {
      if (reader.IsDBNull("columnName"))
      {
         throw new SqlNullValueException("Value in columnName is null");
      }
      else { }
   }
}

instead of

object sqlDateTime = dr[0];
    DateTime? dt = (sqlDateTime == System.DBNull.Value)
    ? (DateTime?)null
    : Convert.ToDateTime(sqlDateTime);

use

var dateTime = dr[0] != System.DBNull.Value
  ? (DateTime?)dr.GetDateTime(0) // parse the sql datetime and returns CLR DateTime
  : (DateTime?)null;

You can use HasValue like

 while (dr.Read())
     {
          DateTime? sqlDateTime = dr[0];
          DateTime? dt = sqlDateTime.HasValue
                             ? sqlDateTime
                         :null;

          dtDateReceived.Value = dt;
     }

Make sure your dtDateReceived is nullable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM