Filter a DataGrid in WPF

后端 未结 5 2089
庸人自扰
庸人自扰 2020-12-05 08:21

I load a lists of objects in a datagrid with this:

dataGrid1.Items.Add(model);

The model become data from a database. It has a

5条回答
  •  醉话见心
    2020-12-05 08:53

    You can use dataview filter in order to filter the datagrid rows.

                DataView dv = datatable.DefaultView;
    
                StringBuilder sb = new StringBuilder();
                foreach (DataColumn column in dv.Table.Columns)
                {
                    sb.AppendFormat("[{0}] Like '%{1}%' OR ", column.ColumnName, "FilterString");
                }
                sb.Remove(sb.Length - 3, 3);
                dv.RowFilter = sb.ToString();
                dgvReports.ItemsSource = dv;
                dgvReports.Items.Refresh();
    

    Where the "datatable" is datasource given to your datagrid and using string builder you build the filter query where "Filter String" is the text you want to search in your datagrid and set it to dataview and finally set the dataview as itemsource to your datagrid and refresh it.

提交回复
热议问题