【问题标题】:DataGridView filter hiding edited itemsDataGridView 过滤器隐藏已编辑的项目
【发布时间】:2014-05-21 10:39:32
【问题描述】:

我有一个绑定到 DataTable 的 DataGridView。然后使用下面的代码在 2 列上进行过滤,但是当您编辑过滤列中的任一单元格然后单击另一行(或表单中的任何其他位置)时,编辑的行会​​因为过滤器而消失。

string rowFilter = string.Format("[{0}] = '{1}'", "Assigned To", comboBoxDepartment.Text);
rowFilter += string.Format(" AND [{0}] = '{1}'", "Status", comboBoxCaseStatus.Text);
(dataGridViewCases.DataSource as DataTable).DefaultView.RowFilter = rowFilter;

在编辑其中一个过滤字段时如何阻止这种情况发生?

【问题讨论】:

    标签: c# .net winforms datagridview


    【解决方案1】:

    (我假设您有一个唯一的 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,你就可以解决它。

    【讨论】:

    • 感谢一些编辑,这正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多