2013-04-23 236 views
0
protected void Page_Load(object sender, EventArgs e) 
    { 
     string query = "SELECT Posts.*, Import_Export.* FROM Import_Export INNER JOIN Posts ON Import_Export.CatID = Posts.CatID where [email protected] "; 
     if (Request.QueryString["CID"] != null) 
     { 
      query += " and [email protected]"; 
      SqlDataSource2.SelectCommand = query; 
      SqlDataSource2.SelectParameters["Parent"].DefaultValue = Request.QueryString["Type"].ToString(); 
      SqlDataSource2.SelectParameters["CatID"].DefaultValue = Request.QueryString["CID"].ToString(); 
     } 
     else 
     { 
      SqlDataSource2.SelectCommand = query; 
      SqlDataSource2.SelectParameters["Parent"].DefaultValue = Request.QueryString["Type"].ToString(); 
     } 
    } 


我寫這篇文章的代碼,當我運行下面錯誤的代碼中出現了:
對象引用不設置到對象的實例。錯誤「對象引用未設置爲對象的實例」。

爲什麼?

+0

哪裏是你的SqlDataSource2 instatiated?它是否意味着是一個SqlDataAdapter? – Constanta 2013-04-23 11:35:13

+0

@Constanta:在我寫我的代碼的同一頁。 – 2013-04-23 11:38:41

+0

好吧,你跳過那一點。它看起來像這樣SqlDataAdapter SqlDataSource2 = new SqlDataAdapter(); – Constanta 2013-04-23 11:40:05

回答

2

要在這裏總結一下就是它應該是什麼樣子

SqlDataSource2.SelectCommand.Parameters.Add("Parent", System.Data.SqlDbType.NVarChar); 
SqlDataSource2.SelectCommand.Parameters["Parent"].Value = Request.QueryString["Type"].ToString(); 

OR

SqlDataSource2.SelectCommand.Parameters.AddWithValue("Parent",Request.QueryString["Type"].ToString()); 
+1

我寫了這段代碼,它的工作原理如下:\t \t \t'SqlDataSource2.SelectParameters.Add(「Parent」,Request.QueryString [「Type」]。ToString());'' – 2013-04-23 12:40:54

0

試試這個

protected void Page_Load(object sender, EventArgs e) 
    { 
     string query = "SELECT Posts.*, Import_Export.* FROM Import_Export INNER JOIN Posts ON Import_Export.CatID = Posts.CatID where [email protected] "; 
     if (Request.QueryString != null) 
     { 
      Parameter par = new Parameter("@Parent", DbType.String, Request.QueryString["Type"].ToString()); 
      SqlDataSource2.SelectParameters.Add(par); 


      if (Request.QueryString["CID"] != null) 
      { 
       query += " and [email protected]"; 
       SqlDataSource2.SelectCommand = query; 
       Parameter par2 = new Parameter("@CatID", DbType.String, Request.QueryString["CID"].ToString()); 
       SqlDataSource2.SelectParameters.Add(par2); 
      } 
      else 
      { 
       SqlDataSource2.SelectCommand = query; 
      } 
     } 
    } 
相關問題