当用户更改为新值时,验证DataGridViewComboBoxCell

时间:2013-04-23 19:24:21

标签: c# winforms validation datagridview

我们的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) ...
    }

1 个答案:

答案 0 :(得分: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}");
    }