Cannot implicitly convert type 'int?' to 'int'.

MaylorTaylor picture MaylorTaylor · May 28, 2013 · Viewed 128.1k times · Source

I'm getting the error "Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)" on my OrdersPerHour at the return line. I'm not sure why because my C# skills are not that advanced. Any help would be appreciated.

static int OrdersPerHour(string User)
{
    int? OrdersPerHour;
    OleDbConnection conn = new OleDbConnection(strAccessConn);
    DateTime curTime = DateTime.Now;        

    try
    {
        string query = "SELECT COUNT(ControlNumber) FROM Log WHERE DateChanged > #" + curTime.AddHours(-1) + "# AND User = '" + User + "' AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered');";
        OleDbCommand dbcommand = new OleDbCommand(query, conn);
        dbcommand.Connection.Open();
        dbcommand.CommandType = CommandType.Text;
        OrdersPerHour = (int?)dbcommand.ExecuteScalar();

        Console.WriteLine("Orders per hour for " + User + " is " + OrdersPerHour);            
    }
    catch (OleDbException ex)
    {

    }
    finally
    {
        conn.Close();
    }
    return OrdersPerHour;
}

Answer

Dimitar Dimitrov picture Dimitar Dimitrov · May 28, 2013

Well you're casting OrdersPerHour to an int?

OrdersPerHour = (int?)dbcommand.ExecuteScalar();

Yet your method signature is int:

static int OrdersPerHour(string User)

The two have to match.


Also a quick suggestion -> Use parameters in your query, something like:

string query = "SELECT COUNT(ControlNumber) FROM Log WHERE DateChanged > ? AND User = ? AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered')";
OleDbCommand dbcommand = new OleDbCommand(query, conn);
dbcommand.Parameters.Add(curTime.AddHours(-1));
dbcommand.Parameters.Add(User);