locked
Specified cast is not valid RRS feed

  • Question

  • Hi,

     

    When i run this code i get the error "Specified cast is  not valid" around the code where I add the date to the list(according to intellitrace). Never encountered this error before, can anyone help me out?

     

    Thanks

    public static List<DateTime> GetDates(String connectionString, String division, String subDivision)
        {
          try
          {
            List<DateTime> datesList = new List<DateTime>();
            DatabaseConnector dbHandle = new DatabaseConnector();
            dbHandle.OpenConnection(connectionString);
    
            string sSQL = SQLReadCommands.GetDates(division, subDivision);
            System.Data.SqlClient.SqlDataReader loadedDates = dbHandle.ExecuteQuery(sSQL);
    
          
            while (loadedDates.Read())
            {
    
              DateTime _dates = (DateTime)loadedDates["imageDate"];
              datesList.Add(_dates);
              
            }
    
            loadedDates.Close();
            dbHandle.CloseConnection();
    
            return datesList;
    
          }
          catch
          {
    
            return new List<DateTime>();
          }
    
    
        }
    Sunday, February 20, 2011 5:15 PM

Answers

  • Looks like some items have null instead of date value. So, Check whether the retrieved value is null or not, before casting. See below,

    ....
    
    while (loadedDates.Read)
    {
     DateTime _dates = loadedDates["imageDate"] as DateTime;
     if( _dates != null)
     {
      datesList.Add(_dates);  
     }
     else
     {
      //You may want to add some logic here.
     }
    }
    
    ...

    Hope this helps. 

     


     

    Please mark this post as answer if it solved your problem. Happy Programming !!!

    • Marked as answer by geraintf Sunday, February 20, 2011 11:41 PM
    Sunday, February 20, 2011 6:33 PM
  • Actually, DateTime.ParseExact maybe what you need as your T-SQL will return a Date in US format of "MM/dd/yyyy"

    Something like...

    DateTime _dates = DateTime.ParseExact(loadedDates["imageDate"].ToString(), "MM/dd/yyyy", System.Globalization.CultureInfo.CurrentCulture);

    • Edited by mrkevlar Sunday, February 20, 2011 10:58 PM Forgot the "ToString"
    • Marked as answer by geraintf Sunday, February 20, 2011 11:41 PM
    Sunday, February 20, 2011 10:50 PM

All replies

  • Do you get the actual date into _date variable?

    If so, it should work.

    Here is my example of adding dates into list:

      public partial class Form1 : Form
      {
        public Form1()
        {
          InitializeComponent();
          List<DateTime> myList = GetDates();
        }
    
        public List<DateTime> GetDates()
        {
          List<DateTime> list = new List<DateTime>();
          DateTime date1 = DateTime.Now;
          DateTime date2 = new DateTime(2011, 2, 19);
          DateTime date3 = Convert.ToDateTime("18.2.2011 9:23:32");
          list.AddRange(new DateTime[] { date1, date2, date3 });
          
          return list;
        }
      }

    PS: code works.

    Mitja

    Sunday, February 20, 2011 6:14 PM
  • Looks like some items have null instead of date value. So, Check whether the retrieved value is null or not, before casting. See below,

    ....
    
    while (loadedDates.Read)
    {
     DateTime _dates = loadedDates["imageDate"] as DateTime;
     if( _dates != null)
     {
      datesList.Add(_dates);  
     }
     else
     {
      //You may want to add some logic here.
     }
    }
    
    ...

    Hope this helps. 

     


     

    Please mark this post as answer if it solved your problem. Happy Programming !!!

    • Marked as answer by geraintf Sunday, February 20, 2011 11:41 PM
    Sunday, February 20, 2011 6:33 PM
  • @Adavesh: I tried that but still have the error, thanks for your input though.

    @Mitja: The date is held in a DateTime field of the database and am using the following SQL code:

    public static String GetDates(string division, string subdivision)
        {
    
          String sqlString = String.Format(@" SELECT DISTINCT
                           CONVERT(varchar,[images].[image_date],101) AS imageDate
                           FROM [ProjectDetails] INNER JOIN [images]
                           ON [ProjectDetails].[ID] = [images].[project_details_id]
                           WHERE (ProjectDetails.division = '{0}')
                           AND (ProjectDetails.sub_division = '{1}')",
                           division , subdivision );
    
    
          return sqlString;
    
    
        }

    The SQL itself works in SQL server management studio so I don't think this is the problem.

    Geraint

    Sunday, February 20, 2011 6:57 PM
  • If you tried Adavesh's code, your error will surely have been different. Since his code avoids a cast. If so, what's the new error you get?
    http://blog.voidnish.com
    Sunday, February 20, 2011 7:37 PM
  • Using Original code,  error is:

    "Specified cast is not valid"

    With new updated code I get the error "Specific cast is not valid"

    But not intelli trace highlights the 'catch' part of the try-catch part of the code.

     

    Any ideas?

     

    Sunday, February 20, 2011 9:42 PM
  • Can you copy/paste your changed code (in its entirety)?
    http://blog.voidnish.com
    Sunday, February 20, 2011 10:22 PM
  • Have you tried using DateTime.TryParse/Parse rather than casting?
    Sunday, February 20, 2011 10:39 PM
  • Actually, DateTime.ParseExact maybe what you need as your T-SQL will return a Date in US format of "MM/dd/yyyy"

    Something like...

    DateTime _dates = DateTime.ParseExact(loadedDates["imageDate"].ToString(), "MM/dd/yyyy", System.Globalization.CultureInfo.CurrentCulture);

    • Edited by mrkevlar Sunday, February 20, 2011 10:58 PM Forgot the "ToString"
    • Marked as answer by geraintf Sunday, February 20, 2011 11:41 PM
    Sunday, February 20, 2011 10:50 PM
  • specialk83 you are a star, that got it working perfectly thanks (also thanks to everyone else for their input!)

     

    Geraint

    Sunday, February 20, 2011 11:41 PM