簡體   English   中英

DataGridView過濾器隱藏已編輯的項目

[英]DataGridView filter hiding edited items

我有一個綁定到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;

編輯已過濾的字段之一時,如何阻止這種情況發生?

(我假設您有一個唯一的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;  
  }

我從這篇文章中得到了這個主意,但是有一個抱怨,第一個答案“還顯示該列具有相似值的所有其他行”,但是如果使用ID,則可以解決。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM