(我假设您有一个唯一的 ID 列)
您必须在任何方法之外声明您的过滤器。
string filter;
也声明这些:
int id;
string nameOfcolumn;
string newValue;
像最初一样应用您的过滤器,但现在过滤器是在方法之外声明的。
在单元格DataGridView_CellParsing事件方法中获取单元格编辑后的值,但在应用过滤器之前获取,在该事件方法中必须保存正在修改的行的id:
private void DataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
//Get the id, (assuming that the id is in the first column)
id =int.Parse(DataGridView.Rows[e.RowIndex].Cells[0].Value.ToString());
//If you need more comparison, you can get the name of the column and the new value of the cell too
nameOfcolumn = DataGridView.Columns[e.ColumnIndex].Name;
newValue = e.Value.ToString();
}
现在在 DataGridView_CellEndEdit 事件方法上,您将修改您的过滤器并重新应用它。
private void DataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
filter += " OR id=" + id.ToString(); //The modified value is now being included on the filter
//If you need more comparisons or if you can't use an id, you can use columnName and newValue
//filter += " OR (" + columnName + " LIKE '" + newValue+ "' AND id=" + id.ToString() + ")";
//Re-apply it
(DataGridView.DataSource as DataTable).DefaultView.RowFilter=filter;
}
我从这个post 中获得了这个想法,但有人抱怨说第一个答案“还显示了该列具有相似值的所有其他行”,但如果你使用 ID,你就可以解决它。