2014-02-14 28 views
0

我在c#中使用下面的代碼,它試圖通過兩個給定的參數過濾數據。但是,它不起作用。你有什麼建議嗎?c#中的SQL參數不工作

感謝, Vancho

下面是代碼

public void TestQuery() 
    { 
     SqlCommand sqlCommand = new SqlCommand(GetQuery()); 
     //sqlCommand.Parameters.Add("@SKU", SqlDbType.VarChar).Value = txtSKU.Text; 
     //sqlCommand.Parameters.Add("@ProductName", SqlDbType.NVarChar).Value = txtProductName.Text; 

     sqlCommand.Parameters.AddWithValue("@SKU", txtSKU.Text); 
     sqlCommand.Parameters.AddWithValue("@ProWductName", txtProductName.Text); 

     //sqlCommand.Parameters.Add("@SKU", System.Data.SqlDbType.NVarChar).Value = txtSKU.Text; 
     //sqlCommand.Parameters.Add("@ProductName", System.Data.SqlDbType.NVarChar).Value = txtProductName.Text; 

     //sqlCommand.Parameters["@SKU"].Value = txtSKU.Text; 
     //sqlCommand.Parameters["@ProductName"].Value = txtProductName.Text; 

     //execute query and other stuff 

     conn.Open(); 

     SqlDataAdapter da = new SqlDataAdapter(GetQuery(), conn); 
     DataTable dt = new DataTable(); 
     da.Fill(dt); 

     dt.TableName = "Product Setup"; 
     dataGridView1.DataSource = dt; 

     conn.Close(); 
    } 
    private string GetQuery() 
    { 
     System.Text.StringBuilder sb = 
      new System.Text.StringBuilder(@"SELECT ProductID, BarCode, SKU, ProductName, SecondaryIDNumber, ModelIDNumber, ProductDescription 
     FROM Products WHERE ProductId is not null "); 



     if (txtSKU.Text != null) 
      sb.Append("AND SKU = @SKU "); 

     if (txtProductName.Text != null) 
      sb.Append("AND ProductName = @ProductName"); 
     return sb.ToString(); 
    } 
+1

_not working_意味着前通過該查詢DataAdapter

你也可以檢查你的參數? –

+2

您創建了sqlCommand,但沒有將它傳遞給適配器。 –

回答

3

你設置你的適配器命令,但是,你沒有爲您的參數給值:

SqlDataAdapter da = new SqlDataAdapter(GetQuery(), conn); 

而是使用這個:

SqlCommand sqlCommand = new SqlCommand(GetQuery()); 
sqlCommand.Parameters.AddWithValue("@SKU", txtSKU.Text); 
sqlCommand.Parameters.AddWithValue("@ProductName", txtProductName.Text); 
SqlDataAdapter da = new SqlDataAdapter(sqlCommand, conn); 

首先獲得您的查詢,給價值爲您的參數,然後使用AddWithValue

if(sqlCommand.CommandText.Contains("@SKU")) 
     sqlCommand.Parameters.AddWithValue("@SKU", txtSKU.Text); 

if(sqlCommand.CommandText.Contains("@ProductName")) 
     sqlCommand.Parameters.AddWithValue("@ProductName",txtProductName.Text);