【问题标题】:Get the new value or index with SelectionChangeCommitted Event of DataGridView Combobox使用 DataGridView Combobox 的 SelectionChangeCommitted 事件获取新值或索引
【发布时间】:2011-11-11 07:22:36
【问题描述】:

我使用 SelectionChangeCommitted 来捕获组合框选定索引更改时的事件,但我无法获取它的新值或索引。

private void ruleList_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (e.Control is ComboBox)
        {
            ComboBox comboBox = e.Control as ComboBox;
            comboBox.SelectionChangeCommitted += ruleListColumnComboSelectionChanged;
        }
    }

    private void ruleListColumnComboSelectionChanged(object sender, EventArgs e)
    {
        string value = ruleList.CurrentCell.Value.ToString(); // just return the old value before the change
    }

【问题讨论】:

    标签: c# datagridview selectedindexchanged datagridviewcombobox


    【解决方案1】:

    您好尝试使用CommitEdit 关键字(CommitEdit,MSDN 页面上也有一个示例)。将此添加到您的DataGridView

    // This event handler manually raises the CellValueChanged event
    // by calling the CommitEdit method.
    void dataGridView1_CurrentCellDirtyStateChanged(object sender,
        EventArgs e)
    {
        if (dataGridView1.IsCurrentCellDirty)
        {
            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
    }
    

    然后您可以只监听CellValueChanged,而不必尝试在底层编辑控件上注册 ComboBoxValueChanged 事件。

    【讨论】:

      【解决方案2】:

      您可以使用以下方法获取新值:

      ComboBox comboBox = sender.Control as ComboBox;
      MessageBox.Show(comboBox.Text);
      

      【讨论】:

        【解决方案3】:

        如果我理解得很好,您正在对组合框中的 SelectionChangeCommitted 事件做出反应,但试图通过网格获取值。对吗?

        • ruleList中的commitment是怎么做的?
        • 承诺在那个时间点是否已经发生?

        我的感觉是,通过这个SelectionChangeCommitted 事件,您可以直接从组合框中访问值,但还不能通过网格,因为它还没有提交。

        【讨论】:

          【解决方案4】:

          改进Killercam 的方法,您可以检查当前单元格是否为datagridviewcomboboxcell 并执行(在VB 中可以轻松转换为C#)

          If TypeOf CType(sender, DataGridView).CurrentCell Is DataGridViewComboBoxCell Then
              CType(sender, DataGridView).CommitEdit(DataGridViewDataErrorContexts.Commit)
              CType(sender, DataGridView).EndEdit()
          End If
          

          为了完整性,我还添加了 EndEdit() 方法。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-10-10
            • 2011-03-15
            • 2011-11-12
            • 2012-12-06
            相关资源
            最近更新 更多