[英]Return multiple SQL query results to text boxes
我目前有3張桌子,學生,更少/學習,課程和課程
使用sql查詢,我設法使用組合框將類代碼返回到文本框。 現在,我創建了一個SELECT查詢,該查詢應返回與該Class代碼鏈接的Lessons中的值。 由於有六個與課程相關的課程,所以我希望這些行填充多個文本框。
課程代碼課程名稱課程學分...是課程表中的三列。 因此,應該有六行結果來填充文本框。 我目前的代碼
string conString = "DATA SOURCE HERE";
string query = @"SELECT [Lesson ID],[LessonName],[LessonCredits] from Lessons WHERE ClassID ='" + txtClassID.Text + "' ;";
SqlConnection conDateBase = new SqlConnection(conString);
SqlCommand cmdDatabase = new SqlCommand(query, conDateBase);
conDateBase.Open();
SqlDataReader myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
string sLessID = myReader.GetString(myReader.GetOrdinal("Lesson ID"));
string sLessNam = myReader.GetString(myReader.GetOrdinal("LessonName"));
string sLessCred = myReader.GetString(myReader.GetOrdinal("LessonCredits"));
txtLessId1.Text= sLessID;
txtLessName1.Text = sLessNam;
txtLessCred1.Text = sLessCred;
}
該代碼僅返回課程表中與類ID相關的最后一個值,我有一種感覺,我需要將查詢的結果放入循環中,然后存儲到數組中,然后將文本框分配給數組?
當然,它僅顯示表格的最后一行。 因為您正在經歷一個循環,所以循環在最后一行結束。 根據您的要求,我會給您兩個選擇。
1 。 創建兩個按鈕“上一課”和“下一課”,並在單擊此按鈕的同時在各行中移動
在表單類中添加兩個變量,以便可以在button_click事件中對其進行訪問
一個System.Data.DataTable變量,用於存儲課程數據和
用於存儲索引的int變量
DataTable Lessons;
int lessonIndex = 0;
private void combo_DropDown(object sender, EventArgs e)
{
SqlConnection conDateBase = new SqlConnection();
conDateBase.ConnectionString = connectionString;
conDateBase.Open();
string query = "SELECT [Lesson ID],[LessonName],[LessonCredits] from Lessons WHERE ClassID = @CLASS_ID";
SqlCommand cmdDatabase = new SqlCommand(query, conDateBase);
cmdDatabase.Parameters.Add("@CLASS_ID", System.Data.SqlDbType.VarChar).Value = txtClassID.Text;
SqlDataAdapter adapter = new SqlDataAdapter(cmdDatabase);
DataSet dSet = new System.Data.DataSet();
adapter.Fill(dSet, "Lessons");
Lessons = dSet.Tables["Lessons"];
lessonIndex = 0;
refreshValues();
}
private void btnPreviousLesson_Click(object sender, EventArgs e)
{
if (lessonIndex > 0 && Lessons != null && Lessons.Rows.Count > 0)
{
lessonIndex--;
refreshValues();
}
}
private void btnNextLesson_Click(object sender, EventArgs e)
{
if (Lessons != null && Lessons.Rows.Count > 0 && lessonIndex < Lessons.Rows.Count - 1)
{
lessonIndex++;
refreshValues();
}
}
private void refreshValues()
{
txtLessID1.Text = Lessons.Rows[lessonIndex]["Lesson ID"].ToString();
txtLessName1.Text = Lessons.Rows[lessonIndex]["LessonName"].ToString();
txtLessCred1.Text = Lessons.Rows[lessonIndex]["LessonCredits"].ToString();
}
。
2 。 在DataGridView上顯示課程數據
與上面的combo_DropDown事件代碼相同,跳過最后兩行和其他事件/函數並將其添加。
DataSet dSet = new System.Data.DataSet();
adapter.Fill(dSet, "Lessons");
Lessons = dSet.Tables["Lessons"];
dataGridView1.DataSource = Lessons;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.