使用DataGridView Combobox的SelectionChangeCommitted Event获取新值或索引

我使用SelectionChangeCommitted在combobox选择的索引发生变化时捕获事件,但我无法获得它的新值或索引。

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 } 

您好尝试使用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); 

如果我理解得很好,你就会对combobox中的SelectionChangeCommitted事件作出反应,但是试图通过网格获取值。 那是对的吗?

  • ruleList中的承诺是如何完成的?
  • 承诺是否已经在那个时间点发生了?

我的感觉是,通过这个SelectionChangeCommitted事件,您可以直接访问combobox中的值,但尚未通过网格访问,因为它尚未提交。

改进Killercam的方法,你可以检查currentcell是一个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()方法。