C# Access OleDb Data type mismatch in criteria expression

MooMooCoding picture MooMooCoding · Sep 9, 2014 · Viewed 17.3k times · Source

Would you please kindly check the following code for errors that give me a 'Data type mismatch in criteria expression' exception? I just can't seem to find the source of the problem...

enter image description here

*record.Date of nullable DateTime? type is explicitly casted to DateTime

*record.Date is set as nullable for other uses in the program. But the record.Date set for the INSERT operation is retrieved from a DateTimePicker, so a record.Date value for this method should never be null.

WHERE

enter image description here

AND (in case you're wondering)

enter image description here


From my Access file (Design View):

enter image description here


Thank you!


Here's the AddRecord method. Thanks!

public static int AddRecord(Record record)
{
    OleDbConnection connection = LABMeetingRecordsDB.GetConnection();
    string insertStatement = "INSERT INTO DocumentInfo " +
                             "([FileName], [Date], [Subject], [Type]) " +
                             "VALUES (?, ?, ?, ?)";
    try {
        OleDbCommand insertCommand = new OleDbCommand(insertStatement, connection);
        insertCommand.Parameters.AddWithValue("@FileName", record.FileName);
        insertCommand.Parameters.AddWithValue("@Date", (DateTime)record.Date);
        insertCommand.Parameters.AddWithValue("@Subject", record.Subject);
        insertCommand.Parameters.AddWithValue("@Type", record.getDBType());

        connection.Open();
        insertCommand.ExecuteNonQuery();

        string selectStatement = "SELECT IDENT_CURRENT('DocumentInfo') FROM DocumentInfo";
        OleDbCommand selectCommand = new OleDbCommand(selectStatement, connection);
        int recordID = Convert.ToInt32(selectCommand.ExecuteScalar());

        AddCategory(connection, recordID, record.Category);

        return recordID;

        } catch (OleDbException ex) {
            throw ex;
        } finally {
            connection.Close();
        }
    }

Answer

MooMooCoding picture MooMooCoding · Sep 9, 2014

So...[PROBLEM SOLVED] :D

From HERE I learnt that

The problem of the mismatch in criteria expression is due to the OleDbType assigned to the parameter used to represent the DateTime.Now value when you call AddWithValue.

The OleDbType choosen by AddWithValue is DBTimeStamp, but Access wants a OleDbType.Date.

Meaning that the convenient AddWithValue pulled a fast one on me...

Thank you @LarsTech and @DJKraze for helping me out despite the confusion of the presentation!