Suppress or Cancel Filter on DataGridView edit

孤街浪徒 提交于 2020-01-06 13:57:23

问题


I have DataGridView that allows editing (ReadOnly = false). The DataGridView may also have one or more filters associated with its datasource. For example:

(myDataGridView.DataSource as DataTable).DefaultView.RowFilter = "[myColumn] = 'value'";

If the filter is applied, and the user edits the field in myColumn, the row immediately "disappears", as it no longer fulfills the filter's criteria. Is there a way to suppress or cancel this action? Ideally, I want the user to "refresh" the grid so that the filter is re-applied at will.


回答1:


You can simply set the RowFilter in some Refresh method and only call that method at that time. However you have to add some or condition to the RowFilter in some appropriate event handler such as a CellEndEdit event handler to keep the current row from being disappeared no matter what value the user entered:

string baseFilter = "[myColumn] = 'value'";
//CellEndEdit event handler for your myDataGridView
private void myDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e){
    (myDataGridView.DataSource as DataTable).DefaultView.RowFilter = baseFilter + " OR [myColumn] = '" + myDataGridView[e.ColumnIndex,e.RowIndex].Value + "'";
}
//you can call this method such as in some Click event handler of some Refresh Button
public void RefreshGrid(){
  (myDataGridView.DataSource as DataTable).DefaultView.RowFilter = baseFilter;
}



回答2:


The mehod stated by 'King King' is not so good because it causes to show also all other rows which have similar values for that column.

You have an option to avoid using auto filter mechanism of DataTable.DefaultView.RowFilter and instead perform a loop through all rows of your DataGridView and check your filteringcriteria to set each row Visible property.

    void applyFilter()
    {
        foreach (DataGridViewRow row in grid1.Rows)
        {
            string columnA = row.Cells["ColumnA"].Value as string;
            string columnB = row.Cells["ColumnB"].Value as string;
            row.Visible = (columnA == "valueA" && columnB == "valueB");
        }
    }

you may also use something like as: columnA.IndexOf("valueA", StringComparison.OrdinalIgnoreCase) > -1 to search with 'Contains' criteria (like as RowFilter = '%valueA%').



来源:https://stackoverflow.com/questions/19102819/suppress-or-cancel-filter-on-datagridview-edit

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