2016-12-23 86 views
0

我有一個dataGrid在我的app.I使用TextChanged事件來過濾數據grid.I有四個文本框用於過濾。我正在使用SQL查詢與LIKE 。 當我只用兩個文本框使用過濾器時,此方法工作正常。但如果我使用三個(四個)(因爲我需要四個),它不會過濾數據網格right.It不顯示所有匹配,並且當我清除文本框時,它不會重置dataGrid以顯示整個表格。dataGrid搜索與SQL LIKE查詢不工作,因爲它應該

我的XAML:

<DataGrid x:Name="dataGridSearch" HorizontalAlignment="Center" VerticalAlignment="Top" Height="227" Width="990" Margin="0,202,0,0" ItemsSource="{Binding DataSource}" AutoGenerateColumns="False" IsReadOnly="True"> 
        <DataGrid.Columns> 
         <DataGridTextColumn Header="Name" Binding="{Binding name}" Width="200" /> 
         <DataGridTextColumn Header="Type" Binding="{Binding type}" Width="300"/> 
         <DataGridTextColumn Header="City" Binding="{Binding city}" Width="250" /> 

         <DataGridTextColumn Header="Place" Binding="{Binding place}" Width="*" /> 


        </DataGrid.Columns> 
       </DataGrid> 

我對TextChanged事件代碼:

using (SqlConnection sc = new SqlConnection(ConString)) 
     { 
      sc.Open(); 
      string query_search = "SELECT * FROM object WHERE name LIKE @name AND type LIKE @type AND city LIKE @city AND place LIKE @place"; 
      SqlCommand com = new SqlCommand(query_search, sc); 
      com.Parameters.AddWithValue("@name", "%" + textBoxPlace.Text + "%"); 
      com.Parameters.AddWithValue("@type", "%" + textBoxType.Text + "%"); 
      com.Parameters.AddWithValue("@city", "%" + textBoxCity.Text + "%"); 
      com.Parameters.AddWithValue("@place", "%" + textBoxPlace.Text + "%"); 


      using (SqlDataAdapter adapter = new SqlDataAdapter(com)) 
      { 
       DataTable dt = new DataTable(); 
       adapter.Fill(dt); 
       dataGridSearch.ItemsSource = dt.DefaultView; 
      } 
      sc.Close(); 
     } 

此外,在窗的打開,我有在開始填充DataGrid中的一個方法

public void fillGrid() 
    { 

     using (SqlConnection sc = new SqlConnection(ConString)) 
     { 
      sc.Open(); 
      string query = "SELECT * FROM object"; 
      SqlCommand com = new SqlCommand(query, sc); 

      using (SqlDataAdapter adapter = new SqlDataAdapter(com)) 
      { 
       DataTable dt = new DataTable(); 
       adapter.Fill(dt); 
       adapter.Update(dt); 
       // dataGridSvi.AutoGenerateColumns = false; 

       dataGridSearch.ItemsSource = dt.DefaultView; 
      } 
      sc.Close(); 
     } 
    } 

回答

1
com.Parameters.AddWithValue("@name", "%" + textBoxPlace.Text + "%"); 
com.Parameters.AddWithValue("@type", "%" + textBoxType.Text + "%"); 
com.Parameters.AddWithValue("@city", "%" + textBoxCity.Text + "%"); 
com.Parameters.AddWithValue("@place", "%" + textBoxType.Text + "%"); 

檢查文本框,你叫相同的文本框兩次。也許這就是問題所在

哦以及有關重置您的網格,你可以叫fillGrid()一個更多的時間,當所有的文本框將明確

+0

這僅僅是爲stackoverfow question.I錯字都有了正確的進入在我的code.sorry的typo.also它看起來像來自數據庫的一些領域,它工作正常。但對於一些它不 – Alexander

+0

好吧,如果你用'按鈕'做它?不是'textchange事件'?你能發表確切的代碼嗎? – Noah