错误消息:对象引用未设置为对象的实例

时间:2013-07-30 09:46:24

标签: c# asp.net

以下代码生成错误:

else if (period.ToString().Equals("3 years"))
    {
        for (int i = 0; i <= 36; i++)
        {
            string strCommandText5 = "INSERT INTO AutoTrans VALUES(@loanID,@transPeriod,null,@transStatus);";

            SqlCommand myCommand5 = new SqlCommand(strCommandText5, myConnection);
            myCommand5.Parameters.AddWithValue("@loanID", Session["@loanID"].ToString());
            myCommand5.Parameters.AddWithValue("@transPeriod", numPeriod);
            myCommand5.Parameters.AddWithValue("@transStatus", status);

            numPeriod++;
            myCommand5.ExecuteNonQuery();
        }
    }

错误讯息:

  

对象引用未设置为对象的实例。 on myCommand5.Parameters.AddWithValue(“@ loanID”,Session [“@ loanID”]。ToString());

请帮助我谢谢

3 个答案:

答案 0 :(得分:0)

按以下方式更改您的代码

else if (period.ToString().Equals("3 years")&&Session["@loanID"]!=null)
{
    for (int i = 0; i <= 36; i++)
    {
        string strCommandText5 = "INSERT INTO AutoTrans VALUES(@loanID,@transPeriod,null,@transStatus);";

        SqlCommand myCommand5 = new SqlCommand(strCommandText5, myConnection);
        myCommand5.Parameters.AddWithValue("@loanID", Session["@loanID"].ToString());
        myCommand5.Parameters.AddWithValue("@transPeriod", numPeriod);
        myCommand5.Parameters.AddWithValue("@transStatus", status);

        numPeriod++;
        myCommand5.ExecuteNonQuery();
    }
}

答案 1 :(得分:0)

Session [“@ loanID”]为空,检查de session中的值:

if (Session["@loanID"] == null) { throw new Exception("Session["@loanID"] is null"); } 
myCommand5.Parameters.AddWithValue("@loanID", Session["@loanID"].ToString());

答案 2 :(得分:0)

错误是自我解释的,您的session为空或为空,这就是生成异常的原因。如果你想

,用它来发送DbNull
myCommand5.Parameters.AddWithValue("@loanID", Session["@loanID"].ToString() ?? (object)DBNull.Value);