【问题标题】:Validate DataGridViewComboBoxCell when user changes to a new value当用户更改为新值时验证 DataGridViewComboBoxCell
【发布时间】:2013-04-23 19:24:20
【问题描述】:

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

【问题讨论】:

  • 你想做的事有点违反 UI 验证指南。当您离开该行时,通常会进行验证。这样,您可以在一个“事务”中提交多项更改。如果您需要立即验证,请创建一个数据表单,并在那里进行所有您想要的自定义验证。
  • 不过,在这种情况下,我们没有任何“进入”或“离开”一行的概念;只有组合框和相关项目。不仅要单击组合框中的项目,还要单击“关闭”单元格以验证输入,这感觉很奇怪。用户在做出选择时可能会感到惊讶,没有错误,然后单击不同的组合框的行并然后被敲响。如果我们可以在用户单击项目时提交并结束编辑,为什么不验证一下以与 this 外观和感觉保持一致?
  • there's just the combo box and the associated items请解释这部分。
  • 我们没有使用 DGV 来编辑 DataTable 中的行;它更多地用于显示项目列表(DGV 中的一列),用户可以为其设置属性(DGV 中的另一列)。所以 DGV 有像“Foo”“Foo Type”这样的列,其中“Foo Type”是一个组合框。您可以看到为什么在此演示文稿中,“基于行”的编辑要求您选择 Foo 类型,然后单击其他位置进行验证,这感觉很奇怪。
  • “Foo 类型”的有效性取决于什么?如果它是一些“Foo”,那么它与基于行的常规编辑没有什么不同。一旦您更改“Foo Type”并且它不对应于“Foo”,您可能会决定更改“Foo”作为下一步。而且不一定总是相反。在你完成之前,你不需要 UI 对你尖叫。这是关于我所说的那些指导方针。除非我误解了你的意图。在这种情况下,请进一步详细说明。最好尽可能地概述您的要求,使其接近主题。如果可以,请不要使用抽象的“Foo”。

标签: c# winforms validation datagridview


【解决方案1】:

你可以模拟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}");
    }

【讨论】:

  • 如何将此事件处理程序订阅到DataGridViewComboBoxCellDataGridViewComboBoxCell
  • 处理DataGridView的EditingControlShowing事件。
  • 那只会导致它在获得焦点后立即失去焦点,对吗?反正有一个很简单的解决办法here
猜你喜欢
  • 2011-04-30
  • 1970-01-01
  • 1970-01-01
  • 2013-02-25
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
相关资源
最近更新 更多