2011-03-22 37 views
1

我有一個datagridview對象,顯示它顯示來自SQL數據庫的數據。當用戶通過客戶ID進行搜索時,我希望datagridview顯示正確的記錄。到目前爲止,我有下面的代碼,但它不起作用,我不確定我是否在正確的道路上,有什麼想法?Visual Studio 2008 - 用於更新datagridview的SQL語句

private void btnCustomerID_Click(object sender, EventArgs e) 
    { 
     if (txtCustomerID.TextLength == 0) 
     { 
      MessageBox.Show("Please enter a Customer ID to search by Customer ID"); 
      txtCustomerID.Focus(); 
     } 
     else 
     { 

      String ID = txtCustomerID.Text; 
      String sqlQuery = (sqlCommandCustomer.CommandText = ("SELECT * FROM Customers WHERE [CustomerID] LIKE ID")); 
      dgCustomers.DataSource = sqlQuery; 

     } 

    } 
+0

我建議是這樣的:http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx,因爲你需要使用的參數與查詢,但我不知道是什麼「sqlCommandCustomer」對象是,我不知道你如何計劃編譯器將字符串ID傳遞給查詢... – jcolebrand 2011-03-22 15:39:33

+0

請在照顧sql注入,同時直接將輸入值傳遞到您的查詢。 – WorldIsRound 2011-03-22 15:44:10

回答

1

忽略SQL注入,甚至通過查詢參數。

你的基本問題是你知道你想做什麼,但不知道如何用代碼表達它。

Pseudo Code: 
    1. Get the ID you want to filter for. 
    2. Pass the ID to a SQL statement. 
    3. Open a connection to the database. 
    4. Execute the SQL via a SQL command. 
    5. Store the result. 
    5. Close the open connection. 
    6. Databind the results to your datagrid. 
1

一件事,你需要改變

WHERE [CustomerID] LIKE ID 

要麼

WHERE [CustomerID] = ID 

WHERE [CustomerID] LIKE %ID%