Reputation: 612
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.
Upvotes: 0
Views: 1171
Reputation: 7440
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%'
).
Upvotes: 0
Reputation: 63327
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;
}
Upvotes: 0