2013-04-23 23 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