我想從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();
}
}
}
}
不要**先調用'.ExecuteNonQuery()'然後調用'.ExecuteReader()'!使用其中一個 - 因爲你想讀取數據,只使用'.ExecuteReader()'調用 - 刪除其他調用 –
你可以縮短while while(dr.Read())'while循環爲' '.Read()'返回一個bools – NoLifeKing