Unable to cast object of type 'System.DateTime' to type 'System.String' RRS feed

  • Question

  • User-702265176 posted

    I want to retrieve data(date) from my database through my linqdatasource, but it seems point out 

    Unable to cast object of type 'System.DateTime' to type 'System.String'

    My Code Sample:

    protected void Button4_Click(object sender, EventArgs e)
    String ID = TextBox1.Text;
    Reservation rs = db.Reservations.SingleOrDefault(o => o.reserveID.ToString == ID);

    if (rs != null)
    lblreserveID.Text = rs.reserveID;
    lblpName.Text = rs.foodPackage;
    lblnoOfTable.Text = rs.noOfTable.ToString();
    lbldate.Text = rs.reserveDate.ToString();

    Error Warning:

    Unable to cast object of type 'System.DateTime' to type 'System.String'.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

    Exception Details: System.InvalidCastException: Unable to cast object of type 'System.DateTime' to type 'System.String'.

    Source Error: 

    Line 19:     {
    Line 20:         String ID = TextBox1.Text;
    Line 21:         Reservation rs = db.Reservations.SingleOrDefault(o => o.reserveID.ToString() == ID);
    Line 22: 
    Line 23:         if (rs != null)
    Sunday, March 27, 2016 6:07 AM


  • User36583972 posted

    Hi limchiawei1,

    From your error message, this is a type conversion error.  I suggest you check your code as the following options.

    *Reservation class is match the database table.

    *reserveID value and ID value are correct.

    You could also share us more relevant code to help us reproduce the problem.

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 28, 2016 7:01 AM