【问题标题】:How to Filter Datagrid values using TextBox (WPF C#)如何使用 TextBox (WPF C#) 过滤 Datagrid 值
【发布时间】:2015-08-19 00:25:11
【问题描述】:

我在使用文本框过滤数据网格值(来自数据库)时遇到了一些问题。事实上,我是 WPF C# 的新手,在这种情况下我需要一些帮助。

这是我的 XAML:

<Button Name="btnSelect"
        Content="Select All"
        Height="30"
        Width="80"
        Margin="4"
        HorizontalAlignment="Center"
        Click="btn_SelectUser"/>
    <DataGrid Name="dtgUser" 
              AutoGenerateColumns="True" 
              HorizontalAlignment="Left" 
              VerticalAlignment="Top" Height="380" Width="684" 
              Margin="10,54,0,0"/>

这是我在按下 Select 按钮后从数据库中选择值的代码:

private void btn_SelectUser(object sender, RoutedEventArgs e)
        {

            _con = new SqlConnection(_strConn);
            try
            {
                _con.Open();
                string query = "select id_int_user, name_str_user  from tbl_user";
                _cmd = new SqlCommand(query, _con);
                _cmd.ExecuteNonQuery();

                _adp = new SqlDataAdapter(_cmd);
                _dt = new DataTable("tbl_user");
                _adp.Fill(_dt);
                dtgUser.ItemsSource = _dt.DefaultView;
                _adp.Update(_dt);

                _con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

这是在文本框中选择刚刚编辑的值。如何实现此方法? (注意:我需要通过数据网格从数据库中获取值):

private void txt_SearchUser(object sender, TextChangedEventArgs e)
    {
        //Here is my difficulty //I know nothing how to do it.
    }

【问题讨论】:

  • DataGridItemsSource 可以让您将数据放入其中,但是,它只需要IEnumerable&lt;T&gt;,因此您可能想找到解决方法。
  • 为什么要返回数据库中的所有值?如果已经输入了值,为什么不在 SQL 查询中添加 where 子句?
  • @Nikerym 他使用Update 将数据放入DataTable。我假设他想全部查询并从客户端过滤。

标签: c# .net wpf database datagrid


【解决方案1】:

您的方法可能不是填充 DataGrid 的最佳方式(将来您可能希望使用data binding),但这里有一些适合您情况的快速技巧:

1) 如果用户需要先点击全选按钮,再按ID过滤数据:

private void txt_SearchUser(object sender, TextChangedEventArgs e)
{
    DataTable tempDt = _dt.Copy();
    tempDt.Clear();
    if (txt_Search.Text != "") // Note: txt_Search is the TextBox..
    {
        foreach (DataRow dr in _dt.Rows)
        {
            if (dr["id_int_user"].ToString() = txt_Search.Text)
            {
                tempDt.ImportRow(dr);
            }
        }
        dtgUser.ItemsSource = tempDt.DefaultView;
    }
    else
    {
        dtgUser.ItemsSource = _dt.DefaultView;
    }
}

2) 如果您希望每次用户在搜索框中输入 ID 时都从数据库中过滤数据(不先单击“全选”按钮):

private void txt_SearchUser(object sender, TextChangedEventArgs e)
{
    _con = new SqlConnection(_strConn);
    try
    {
        _con.Open();
        string query = "select id_int_user, name_str_user from tbl_user";
        if(txt_Search.Text != "") // Note: txt_Search is the TextBox..
        {
            query += " where id_int_user = " + txt_Search.Text;
        }
        _cmd = new SqlCommand(query, _con);
        _cmd.ExecuteNonQuery();

        _adp = new SqlDataAdapter(_cmd);
        _dt = new DataTable("tbl_user");
        _adp.Fill(_dt);
        dtgUser.ItemsSource = _dt.DefaultView;
        _adp.Update(_dt);

        _con.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

【讨论】:

  • 当用户在文本框中启动输入 ID 时,我想使用此代码自动数据网格根据文本框上的 ID 显示结果。不按按钮怎么做?
  • 如果这是你需要的,那么我认为这个答案中的第二个例子应该适合你。
  • 是的,第二个示例接近我需要的答案。但是当我输入一个有效的 id 时,什么也没有发生。
  • 嗯..这很奇怪..这个例子基本上只是在你的原始代码中添加了一个 where 子句。因此,如果您的 btn_SelectUser 函数有效,那么它应该有效。您已将其注册为 TextChanged 事件处理程序,对吗?即&lt;TextBox x:Name="txt_Search" TextChanged="txt_SearchUser" /&gt; ?
  • 谢谢。现在可以了。只需将 TextChanged = "txt_SearchUser" 放入 XAML。
【解决方案2】:

在 View Model 中使用 ICollectionView 代表 DataGrid.ItemsSource 并设置 Filter 以过滤项目。

首先,准备一个集合对象(例如ObservableCollection&lt;YourItemClass&gt;)并在视图模型中定义SourceItems

public ICollectionView SourceItems {
  get {
    return _sourceItems 
      ?? (_sourceItems = CollectionViewSource.GetDefaultView(_source));
  }
}

然后响应一些事件,添加过滤谓词来过滤View中的项目:

var items = (ListCollectionView)SourceItems;
items.Filter = obj => obj.UserName == user_name_for_filter;

当然,设置绑定。

<Window.DataContext>
  <local:YourViewModel />
</Window.DataContext>

<DataGrid ItemsSource={Binding SourceItems} ... />

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 2013-11-25
    • 2016-08-31
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多