Help in Execute Scalar

hi i creating a form in VS 2005. I want to have this error at execute scalar(). Invalid casting. Can someone please help

SqlConnection conn = new SqlConnection(this.ConnectionString);

try

{

conn.Open();

SqlCommand cmd = new SqlCommand("Select sum(qty) from Inventory where prodNo = @prodNo AND qty <> @qty", conn);

cmd.Parameters.Add("@prodNo", SqlDbType.VarChar);

cmd.Parameters["@prodNo"].Value = prodNo;

cmd.Parameters.Add("@qty", SqlDbType.Int);

cmd.Parameters["@qty"].Value = 0;

int qty = 0;

qty = (int)cmd.ExecuteScalar();

return qty;

}

finally

{

conn.Close();

}



Answer this question

Help in Execute Scalar

  • lsantos

    hi,

    Please Try this:

    object obj = cmd.ExecuteScalar();
    If (! Convert.IsDBNull ( obj ) )
    {
    int qty = Int32.Parse(obj.ToString());
    return qty;
    }
    else
    {
    return 0;
    }

    cheers,

    soemoe..



  • p0lar_bear

    Most probably you have error on this line

    qty = (int)cmd.ExecuteScalar();

    to identify problem execute SQL statement in some SQL editor (e.g SQL Management Studio) and see what is result. In this way you will detect if result of sum(qty) is not NULL which is most probable reason for exception

    hope this helps


  • HMote

    ya i try, it get the totoal qty..... but in my execute scalar cannot execute


  • Christian Hund

    hi soe moe,

    yes,... i did it.. Coool........ THis is the solution..:) it works...


  • Jason227

    could you isolate the line where exception occur so we could analyze the line

    Other way is to assign result of ExceuteScalar to var such string or object and see with DebugVisualizer what type is result



  • Help in Execute Scalar