2

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

1 回答 1

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}");
    }
于 2013-04-25T21:56:16.323 回答