2013-07-30 1 views
-1
다음 코드는 오류 생성하는

:오류 메시지 : 개체 참조가 개체의 인스턴스로 설정되지 않았습니다

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(); 
     } 
    } 

오류 메시지 :

Object reference not set to an instance of an object. on myCommand5.Parameters.AddWithValue("@loanID", Session["@loanID"].ToString());

나에게 도와주세요 감사

+11

검사 할 경우 세션 여부 [ "@ loanID"] 귀하의 경우'세션 [ "@ loanID"]'널 않을 것입니다 가정하면 널 (null) – Karthik

+0

있는 DBNULL를 보낼 때 사용합니다 : 당신은 몇 가지가 'Session [ "@ loanID"] = null' 코드로 연결되는 오류가 있습니까? –

+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(); 
    } 
} 
0

세션 [ "@의 loanID은"] null의 경우, 드 세션에서 값을 확인 :

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

오류는 session는 예외가 생성되는 이유가 비어 있거나 null의 경우, 자체 설명이다. 당신이

myCommand5.Parameters.AddWithValue("@loanID", Session["@loanID"].ToString() ?? (object)DBNull.Value); 
관련 문제