使用DataGridView Combobox的selectionchangecomcommitted事件获取新的值或索

本文关键字:获取 事件 DataGridView Combobox selectionchangecomcommitted 使用 | 更新日期: 2023-09-27 18:14:03

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

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
    }

使用DataGridView Combobox的selectionchangecomcommitted事件获取新的值或索

我尝试使用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事件。

您可以使用:

获取新的值
ComboBox comboBox = sender.Control as ComboBox;
MessageBox.Show(comboBox.Text);

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

  • 规则列表中的承诺如何完成?
  • 承诺在那个时间点已经发生了吗?

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

改进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

为了完整,我还添加了 enddit ()方法