【发布时间】:2016-12-23 12:39:56
【问题描述】:
我的应用程序中有一个 dataGrid。我正在使用 TextChanged 事件来过滤数据网格。我有四个用于过滤的文本框。我正在使用带有 LIKE 的 SQL 查询。 当我使用只有两个文本框的过滤器时,此方法工作正常。但如果我使用四个中的三个(因为我需要四个),它不会正确过滤数据网格。它不会显示所有匹配项,当我清除了文本框,它不会重置 dataGrid 以显示整个表格。
我的 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();
}
}
【问题讨论】: