当用户更改为新值时验证DataGridViewComboBoxCell
本文关键字:新值时 验证 DataGridViewComboBoxCell 用户 | 更新日期: 2023-09-27 18:10:27
我们在DataGridView中有一个列,用户可以从组合框(DataGridViewComboBoxColumn
)中选择一个值。我们有一些选择的验证逻辑(覆盖OnCellValidating
)。
令人讨厌的是,在对该单元格进行验证之前,用户必须在组合框中进行下拉选择后单击其他地方。我尝试在所选索引发生变化时立即提交编辑(见下文),但是直到单元格失去焦点时才触发验证。我也试过使用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) ...
}
您可以模拟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}");
}