2013-08-02 26 views
0

我想從SQL Server中檢索所有行並將其放在多行文本框中。查詢執行,但它加載最後一行可能是因爲它的最後一條記錄。我應該有「foreach」聲明嗎?從SQL Server中檢索所有行並放入多行文本框

private void LoadComments() 
{ 
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db_TestDBConnectionString"].ConnectionString)) 
    { 
     using (SqlCommand com = new SqlCommand("LoadNotes", con)) 
     { 
     com.CommandType = CommandType.StoredProcedure; 

     con.Open(); 

     com.ExecuteNonQuery(); 

     SqlDataReader dr = com.ExecuteReader(); 

     while (dr.Read() == true) 
     { 
      TextBox1.Text = dr.GetValue(0).ToString() + " " + dr.GetValue(1).ToString() + dr.GetValue(2).ToString(); 
     } 
     } 
    } 
} 
+0

不要**先調用'.ExecuteNonQuery()'然後調用'.ExecuteReader()'!使用其中一個 - 因爲你想讀取數據,只使用'.ExecuteReader()'調用 - 刪除其他調用 –

+0

你可以縮短while while(dr.Read())'while循環爲' '.Read()'返回一個bools – NoLifeKing

回答

0

之前While While設置TextBox1.Text=""; 然後試試這段代碼。

TextBox1.Text += dr.GetValue(0).ToString() + " " + dr.GetValue(1).ToString() + 
dr.GetValue(2).ToString()+Enviroment.NewLine; 

在你的代碼的每一行assingning到TextBox1的,但你concate下一行TextBox1的,所以我就把+面前人人平等,因此concate所有行。

+0

它的工作!但如何添加新行?我添加了Environment.newline,但它沒有奏效。 – user1954418

+0

@ user1954418嘗試更新代碼 –

+0

我這樣做了。但它沒有奏效。我也試過+「\ r \ n」 – user1954418

0
string str = ""; 

while (dr.Read() == true) 
     { 
      str+= dr.GetValue(0).ToString() + " " + dr.GetValue(1).ToString() + dr.GetValue(2).ToString(); 
     } 

TextBox1.Text = str; 
相關問題