WPF通过文本框过滤数据网格 [英] WPF filter datagrid through textbox

查看:50
本文介绍了WPF通过文本框过滤数据网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直到处搜索,但我做不到。
我有一个简单的 DataGrid

I have been searching everywhere and I just cannot make it.. I have a simple DataGrid:

<DataGrid Name="myGrid" HorizontalAlignment="Left" Height="399" 
                  Margin="272,150,0,0" VerticalAlignment="Top" Width="735"/>

我的表单加载时。我有此功能来填充datagrid:

When my form loads. I have this function to fill datagrid :

public MainWindow()
{
    InitializeComponent();
    myGrid.ItemsSource = datatble;
}

我有一个 TextBox 命名为 txtSearch,我的目标是过滤数据网格并查找包含txtSearch.Text的所有行(并隐藏其他行)

I have a TextBox name "txtSearch" and my goal is to filter the datagrid and find all rows that contain txtSearch.Text (and hide the other rows)

有人可以提供示例吗?

Could someone provide an example ?

推荐答案

您可以设置 DataView 的system.data.dataview.rowfilter(v = vs.110).aspx rel = nofollow noreferrer> RowFilter 属性用于过滤器表达式。这是过滤 DataTable 的方式。

You could set the RowFilter property of the DataView to a filter expression. This is how you would filter a DataTable.

这是一个基本示例,应为您提供概念:

Here is a basic example that should give you the idea:

public partial class MainWindow : Window
{
    DataTable _dataTable;
    public MainWindow()
    {
        InitializeComponent();
        _dataTable = new DataTable();
        _dataTable.Columns.Add(new DataColumn("Name"));
        _dataTable.Columns.Add(new DataColumn("Id"));
        _dataTable.Rows.Add("First", "1");
        _dataTable.Rows.Add("Second", "2");
        myGrid.ItemsSource = _dataTable.DefaultView;
    }

    private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
    {
        string filter = txtSearch.Text;
        if (string.IsNullOrEmpty(filter))
            _dataTable.DefaultView.RowFilter = null;
        else
            _dataTable.DefaultView.RowFilter = string.Format("Name Like '%{0}%' OR Id Like '%{0}%'", filter);
    }
}

这篇关于WPF通过文本框过滤数据网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆