WPF filter datagrid through textbox

独自空忆成欢 提交于 2020-04-12 07:25:27

问题


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"/>

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

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

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 ?


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/44947854/wpf-filter-datagrid-through-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!