2014-02-14 6 views
0

두 개의 주어진 매개 변수로 데이터를 필터링하려고하는 다음 코드를 사용 중입니다. 그러나 작동하지 않습니다. 어떤 제안이 있니?C#의 SQL 매개 변수가 작동하지 않습니다.

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

하는 대신 사용

감사합니다, 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

는 명령 코드입니다 만 이 :

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); 
관련 문제