2017-02-13 40 views
0

我無法從下面的查詢中提取我需要的SQL數據。我查看了MSDN並遵循了他們的例子,但出於某種原因,執行讀取器沒有讀取數據並將其返回到文本框,點擊按鈕後。我添加了一個響應來確保連接已打開,並且每次都按下。這是代碼的提取物,我從此處省略的唯一事情就是在SqlConnection的細節:C#ExecuteReader不返回ASP.Net中的SQL查詢數據

protected void Button1_Click(object sender, EventArgs e) 
{ 
     using (SqlConnection conn = new SqlConnection(ConnectionString)) 
     { 

      //set up the SQL command  
      SqlCommand command = new SqlCommand("Use Waste_Test; select * from Bidston_HWRC where MCN_No = @MCN", conn); 

      //open the server connection 
      conn.Open(); 

      //define parameter for SQL query 
      command.Parameters.Add("@MCN", SqlDbType.Int); 
      command.Parameters["@MCN"].Value = TextBox17.Text; 

      Response.Write("<script>alert('You are connected')</script>"); 


      //Execute the query on the server 
      SqlDataReader rdr = command.ExecuteReader(); 

      Response.Write("<script>alert('It's worked')</script>"); 

      while (rdr.Read()) 
      { 
       TextBox6.Text = rdr["Waste_Description"].ToString(); 
      } 
     } 
    } 
+1

你說的參數是int類型,然後給它一個字符串,也許這與它有什麼關係? –

+0

嘗試使用command.Parameters.AddWithValue(「MCN」,TextBox17.Text);如Lasse V. Karlsen所述,考慮鑄造類型爲int。如果需要,參數類型爲整數。 – MMK

+1

爲什麼* while(rdr.Read())'只爲* 1 *值* loop *'? 'if(rdr.Read())TextBox6.Text = rdr [「Waste_Description」]。ToString();' –

回答

0

首先,你需要使用HasRows,以確保該查詢返回了一些成績,如果沒有記錄那麼你可以在標籤中顯示一條消息。由於您從文本框中獲得MCN值,因此您需要將其解析爲int。嘗試下面的代碼。

protected void Button1_Click(object sender, EventArgs e) 
{ 
    using (SqlConnection conn = new SqlConnection(ConnectionString)) 
    {  
      SqlCommand command = new SqlCommand("select * from Bidston_HWRC where MCN_No = @MCN", conn); 
      conn.Open(); 
      Command.Parameters.AddWithValue("@MCN", Int32.Parse(TextBox17.Text)); 
      //Execute the query on the server 
      SqlDataReader rdr = command.ExecuteReader(); 



     if(rdr.HasRows) 
     { 
      while (rdr.Read()) 
      { 
       TextBox6.Text = rdr["Waste_Description"].ToString(); 
      } 

     } 
     else 
     { 
      // show 'no records found' 
     } 
     rdr.Close(); 
     conn.Close(); 
    } 
} 
+0

您確定此代碼有效嗎?我想它會在這一行 - >'command.Parameters [「@ MCN」]中拋出一個'IndexOutOfRangeException'。Value = Int32.Parse(TextBox17.Text);' – Pikoh

+0

剛剛改成'Command.Parameters.AddWithValue(「 @MCN「,Int32.Parse(TextBox17.Text);'我試圖解析文本到int由於值需要在int ... – Saif

+0

嗨@Pikoh,你是正確的,它確實拋出了錯誤。你會如何糾正這種情況?謝謝 – kehoewex86