Type casting of DateTime trouble. RRS feed

  • Question

  • I have an SQL Server database table, one field of which is defined as date (app_date), the other one as time(7) (app_time). In my C# Form I have two controls, both are DateTimePicker. The first one is supposed to show the date of an event. It is set with Format = Custom; ShowUpDown = false. It is further configured to show the date only. The second control is for the time only and it has Format = Time; ShowUpDown = false. (Per Viorel_(MCC, MVP)).

    I also have this code in C# program:

    using (SqlDataReader rdr = cmdm.ExecuteReader(CommandBehavior.CloseConnection)) { if (rdr.HasRows) { foreach (System.Data.Common.DbDataRecord row in rdr)

    { DatePicker_Apps_pg5.Value = (DateTime)row[2]; // app_date TimePicker_Apps_pg5.Value = Convert.ToDateTime (row[3]); //app_time <== Exception here DateAppSet_pg5.Value = (DateTime)row[4]; // dateAppSet tBoxMemoMultiUse_pg4.Rtf = (string)row[5]; rdr.Close(); break; } } }

    I get this exception:

    System.InvalidCastException occurred
      Message=Unable to cast object of type 'System.TimeSpan' to type 'System.IConvertible'.

    I tried various other options to no avail. I have another place in my code rather similar but that will come up later. I need help here.

    Thanks - MyCatAlex

    • Edited by MyCatAlex Sunday, August 12, 2018 4:21 PM
    Sunday, August 12, 2018 4:09 PM


  • You know what worked?

    TimePicker_Apps_pg5.Value = Convert.ToDateTime (Convert.ToString(row[3]));  // app_time

    • Marked as answer by MyCatAlex Sunday, August 12, 2018 4:41 PM
    Sunday, August 12, 2018 4:41 PM