2014-01-20 32 views
1

我想選擇一個GridView上的單行,並有選擇帶我到一個單獨的編輯頁面的數據填充。我有使用會話變量來保存行ID,然後檢索頁面加載和填充文本框中的數據的想法。我的問題是這是否是最好的方法去做這件事?我寧願不使用gridview中的內聯編輯選項,因爲我有太多需要水平滾動的列。以下是使用會話變量網頁的加載方法:填充Web窗體編輯頁面C#ASP.NET

if (Session["editID"] != null) 
     { 
      dbCRUD db = new dbCRUD(); 
      Recipe editRecipe = new Recipe(); 

      var id = Convert.ToInt32(Session["editID"]); 
      Session.Remove("editID"); 


      editRecipe = db.SelectRecord(id); 
      addName.Text = editRecipe.Name; 
     } 

這裏是用來檢索該行的SelectRecord方法:

public Recipe SelectRecord(int id) 
    { 
     Recipe returnedResult = new Recipe(); 

      var dbConn = new SqlConnection(connString); 
      var dbCommand = new SqlCommand("dbo.selectRecipe", dbConn); 


      dbCommand.CommandType = CommandType.StoredProcedure; 
      dbCommand.Parameters.Add("@ID", SqlDbType.Int).Value = id; 


      dbConn.Open(); 
      SqlDataReader reader = dbCommand.ExecuteReader(); 
      while (reader.HasRows) 
      { 
       while (reader.Read()) 
        { 
         returnedResult.Name = reader["Name"].ToString(); 
        } 
      } 

      dbConn.Close(); 

      return returnedResult; 
     } 

我可能不恰當地使用SqlDataReader的,但我的結果是閱讀器中沒有數據,因此調用該方法時沒有返回數據。任何幫助表示讚賞 - 在此先感謝!

+0

返回的記錄確實有多個列,但我只分配名稱值來測試功能。 –

+0

你是否在'while(reader.Read())'部分?換句話說,你是否返回任何行? – sr28

+0

是的,至少我知道雖然(reader.HasRows)是真的,所以我假設我至少在那個循環中,但程序實際上掛起,不會進一步處理。它是一個遠程連接到SQL數據庫,但我已驗證連接。 –

回答

2

一些事情你應該知道這裏:

你應該在你的存儲過程返回多個結果的情況下使用while (reader.HasRows)。在這種情況下,您必須通過結果集迭代。請參閱Retrieving Data Using a DataReader。所以,如果selectRecipe返回多個結果(我假設這種情況並非如此),你的代碼改成這樣:

while (reader.HasRows) 
{ 
    while (reader.Read()) 
    { 
     returnedResult.Name = reader["Name"].ToString(); 
    } 

    reader.NextResult(); 
} 


2.
如果selectRecipe返回一個結果集,改變while循環if(){}

if(reader.HasRows) 
{ 
    while (reader.Read()) 
    { 
     returnedResult.Name = reader["Name"].ToString(); 
    } 

} 



我可能會使用using來更好地管理連接(using Statement):

public Recipe SelectRecord(int id) 
{ 
    Recipe returnedResult = new Recipe(); 

    using (SqlConnection dbConn = new SqlConnection(connString)) 
    { 
     var dbCommand = new SqlCommand("dbo.selectRecipe", dbConn); 

     dbCommand.CommandType = CommandType.StoredProcedure; 
     dbCommand.Parameters.AddWithValue("@ID", id); 

     dbConn.Open(); 

     SqlDataReader reader = dbCommand.ExecuteReader(); 
     if (reader.HasRows) 
     { 
      while (reader.Read()) 
      { 
       returnedResult.Name = reader["Name"].ToString(); 
      } 
     } 
     reader.Close(); 
    } 

    return returnedResult; 
} 
+0

非常感謝,afzalulh!我的應用程序懸掛起來非常有意義。我假設如果我要返回多個結果集,while語句將繼續迭代,直到reader.NextResult()沒有找到任何行。再次感謝澄清和鏈接! –

+0

@Busch_League =很高興它有幫助! – afzalulh

相關問題