2014-05-21 40 views
1

我有一個綁定到DataTable的DataGridView。然後使用下面的代碼對2列進行過濾,但是,當您編輯過濾列中的任意一個單元格,然後單擊另一行(或窗體中的任何其他位置)時,編輯後的行因爲過濾器而消失。DataGridView過濾器隱藏已編輯的項目

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; 

如何在編輯某個過濾的字段時阻止發生這種情況?

回答

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。

+0

感謝一些編輯,這正是我所需要的。 – haddow64