2015-11-01 56 views
-2

我有一個新學生的註冊表單,我需要有一個datagridview,上面有一個文本框和一個datagridview上方的按鈕,用於通過studentID來搜索學生。我試過這個代碼,但它沒有工作帶數據庫的C#搜索表單

private void txtsearch_Click(object sender, EventArgs e) 
    { 
     SqlConnection conn = new SqlConnection(); 
     DataTable dt = new DataTable(); 
     SqlDataAdapter SDA = new SqlDataAdapter(); 
     SDA.Fill(dt); 
     dataGridView1.DataSource = dt; 

    } 
+1

什麼不工作? – dbugger

+2

您還沒有提供連接字符串或SQL ...重新讀取一些示例並將它們跟在信件上。 –

+0

正是這樣說的:在調用'Fill'之前,SelectCommand屬性還沒有被初始化。 @dbugger –

回答

0

您錯過了幾件事情:連接字符串到數據庫和Select語句。您應該在按鈕單擊事件中執行此代碼,而不是文本框上的單擊事件。這裏有一個更好的方法:

private void btnSearch_Click(object sender, EventArgs e) 
    { 
     var conn = new SqlConnection(); 
     var dt = new DataTable(); 
     var SDA = new SqlDataAdapter("Select * from students where 
      studentId = " + txtSearch.Text, "Your connection string here"); 
     SDA.Fill(dt); 
     dataGridView1.DataSource = dt;    
    }