2010-01-11 59 views
4

DataGridView.IsCurrentRowDirty仍然true在我將更改提交到數據庫後。我想將它設置爲false,因此它在失去焦點時不會觸發RowValidating。我有一個DataGridView綁定到BindingList<T>。我處理CellEndEdit事件並將更改保存到數據庫。在保存這些更改後,我想將DataGridView.IsCurrentRowDirty設置爲true,因爲該行中的所有單元都是最新的;但是,它設置爲false提交更改後,DataGridView行仍舊髒

這對我造成了問題,因爲當該行失去焦點時,它將觸發RowValidating,我將處理並驗證所有三個單元格。因此,即使所有單元格都是有效的,沒有髒的,仍然會驗證它們全部。這太浪費了。

這裏是什麼,我有一個例子:

void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
{ 
    // Ignore cell if it's not dirty 
    if (dataGridView.isCurrentCellDirty) 
     return; 

    // Validate current cell. 
} 

void dataGridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e) 
{ 
    // Ignore Row if it's not dirty 
    if (!dataGridView.IsCurrentRowDirty) 
     return; 

    // Validate all cells in the current row. 
} 

void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{ 
    // Validate all cells in the current row and return if any are invalid. 

    // If they are valid, save changes to the database 

    // This is when I would expect dataGridView.IsCurrentRowDirty to be false. 
    // When this row loses focus it will trigger RowValidating and validate all 
    // cells in this row, which we already did above. 
} 

我讀過的職位,說我可以調用窗體的Validate()方法,但是這將導致RowValidating火,這是我想避免。

任何想法如何設置DataGridView.IsCurrentRowDirtytrue?或者也許阻止RowValidating不必要地驗證所有單元格?

回答

3

您是否在將數據保存到數據庫後嘗試調用DataGridView1.EndEdit()。

+0

是的,這沒有奏效。當行失去焦點時,「RowValidating」仍然會觸發。工具提示說'EndEdit()'在當前單元格上工作。如果有類似的東西,比如EndRowEdit,我可能會很幸運。還是)感謝你的建議! – Ecyrb

+2

如果有人遇到過像我這樣的人。我通過調用'datagrid.currentrow.datagrid.endedit()'然後'datagrid.endedit'和最後'bindingSource.endedit()'來解決這個問題。 – ppumkin

0

我和Validating發生了兩次相同的問題。在編輯完成之前(如預期的那樣),但是之後我再次考慮改變焦點。

沒有足夠的時間進行調查。快速修復是this.ActiveControl = null;我不確定這是否有任何意想不到的後果,但它通過編程方式解決了控件的問題,從而解決了驗證問題。

private void cntrl_MethodParameters_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
{ 
    //Init 
    var dgv = (DataGridView)sender; 
    int row = e.RowIndex; 
    int col = e.ColumnIndex; 

    //Validate Edit 
    if ((row >= 0) && (col == cntrl_MethodParameters.Columns.IndexOf(cntrl_MethodParameters.Columns[MethodBuilderView.m_paramValueCol]))) 
    { 
     string xPropertyName = (string)cntrl_MethodParameters[MethodBuilderView.m_paramNameCol, row].EditedFormattedValue; 
     string xPropertyValue = (string)cntrl_MethodParameters[MethodBuilderView.m_paramValueCol, row].EditedFormattedValue; 
     bool Validated = FactoryProperties.Items[xPropertyName].SetState(xPropertyValue); 

     //Cancel Invalid Input 
     if (!Validated) 
     { 
      dgv.CancelEdit(); 
     } 
    } 
    this.ActiveControl = null; 
}