2013-04-23 83 views
2

我們的DataGridView中有一列可供用戶從組合框中選擇值(DataGridViewComboBoxColumn)。我們有一些選擇的驗證邏輯(覆蓋OnCellValidating)。用戶更改爲新值時驗證DataGridViewComboBoxCell

令人討厭的是,用戶在組合框中進行下拉選擇之後,必須單擊其他位置,然後才能對該單元格進行驗證。一旦選定的索引發生變化,我嘗試提交編輯(見下文),但驗證在單元失去焦點之前仍然沒有發射。我也嘗試使用EndEdit()而不是CommitEdit()

只要用戶選擇組合框中的項目,是否有辦法讓驗證激發?

protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e) 
    { 
     // Validate selection as soon as user clicks combo box item. 
     ComboBox combo = e.Control as ComboBox; 
     if (combo != null) 
     { 
      combo.SelectedIndexChanged -= combo_SelectedIndexChanged; 
      combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged); 
     } 

     base.OnEditingControlShowing(e); 
    } 

    void combo_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     this.NotifyCurrentCellDirty(true); 
     this.CommitEdit(DataGridViewDataErrorContexts.Commit); 
    } 

    protected override void OnCellValidating(DataGridViewCellValidatingEventArgs e) 
    { 
     // (our validation logic) ... 
    } 
+0

你想要做什麼樣的違背UI驗證方針。驗證通常在您離開該行時發生。這樣你可以在一個'交易'中提交多個更改。如果您需要立即驗證,請創建一個數據表單,並在其中提供所有您想要的自定義驗證。 – Neolisk 2013-04-23 21:22:41

+0

但是,在這種情況下,我們沒有任何「進入」或「離開」行的概念;只有組合框和相關的項目。不僅要點擊組合框中的項目,還要點擊「關閉」單元以驗證輸入,這感覺很奇怪。用戶在做出選擇時可能會感到驚訝,不會出現錯誤,然後單擊不同的組合框的行,然後_then_變爲dinged。如果我們可以在用戶單擊某個項目時提交併結束編輯,那麼爲什麼不驗證以及是否與_this_的外觀和感覺保持一致呢? – 2013-04-23 23:27:12

+0

'只有組合框和相關的項目'請解釋這部分。 – Neolisk 2013-04-23 23:46:00

回答

0

您可以模擬tab鍵來強制細胞失去焦點:

private void combo_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     //I expect to get the validation to fire as soon as the user 
     //selects an item in the combo box but the validation 
     //is not firing until the cell loses focus 
     //simulate tab key to force the cell to lose focus 
     SendKeys.Send("{TAB}"); 
     SendKeys.Send("+{TAB}"); 
    } 
+0

您如何將此事件處理程序訂閱到「DataGridViewComboBoxCell」或「DataGridViewComboBoxCell」? – 2013-10-22 21:43:11

+0

處理DataGridView的'EditingControlShowing'事件。 – 2013-10-23 09:18:13

+0

這會導致它在獲得它後立即失去焦點,對嗎?無論如何,有一個非常簡單的解決方案[這裏](http://stackoverflow.com/a/9609103/60067)。 – 2013-10-23 15:57:14