I am trying to return a value from a SQL database. However everytime I execute the following method I get an error stating, “InvalidCastException was unhandled. Object cannot be cast from DBNull to other types.”
Any light you could shed on this would be greatly appreciated. The method I am using is as follows.
Thanks.
public static int ScrapTotal2(string prdTypeV, string startDateV, string prtCodeV)
{
int scrapTotal2;
SqlParameter prdType = new SqlParameter("@prdType", SqlDbType.VarChar);
prdType.Value = prdTypeV;
SqlParameter startDate = new SqlParameter("@startDate", SqlDbType.VarChar);
startDate.Value = startDateV;
SqlParameter prtCode = new SqlParameter("@prtCode", SqlDbType.VarChar);
prtCode.Value = prtCodeV;
SqlCommand scrapTotal2SC = new SqlCommand("SELECT SUM([QTY_SCRP]) FROM [TBL_PRDMST] WHERE [PRD_CODE] LIKE @prdType AND [PRD_DATE] = @startDate AND [PRT_CODE] LIKE @prtCode", DataAccess.myConnection);
scrapTotal2SC.Parameters.Add(prdType);
scrapTotal2SC.Parameters.Add(startDate);
scrapTotal2SC.Parameters.Add(prtCode);
DataAccess.myConnection.Open();
scrapTotal2 = Convert.ToInt32(scrapTotal2SC.ExecuteScalar());
DataAccess.myConnection.Close();
return scrapTotal2;
}
Your SELECT statement returns NULL value. You have to check if it is null first: