哪个事件在DataGridViewCell的组合框中捕获了值的更改?

| 我想在
DataGridView
单元格的
ComboBox
中更改值时处理事件。 有
CellValueChanged
事件,但是直到我单击
DataGridView
内的其他位置后,该事件才会触发。 选择新值后,便会立即触发简单的
ComboBox
SelectedValueChanged
。 如何将侦听器添加到单元格内部的组合框中?     
已邀请:
上面的答案使我走上了报春花的道路。它不起作用,因为它会引发多个事件,并且只会不断添加事件。问题在于上面的内容捕获了DataGridViewEditingControlShowingEvent,而没有捕获更改的值。因此,它将在您每次聚焦时触发,无论组合框是否更改,都将其离开。 关于
CurrentCellDirtyStateChanged
的最后答案是正确的方法。我希望这可以帮助某人避免掉进兔子洞。 这是一些代码:
// Add the events to listen for
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);



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

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    // My combobox column is the second one so I hard coded a 1, flavor to taste
    DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[1];
    if (cb.Value != null)
    {
         // do stuff
         dataGridView1.Invalidate();
    }
}
    
您还可以处理
CurrentCellDirtyStateChanged
事件,无论何时更改值,该事件都会被调用,即使未提交也是如此。要获得列表中的选定值,您可以执行以下操作:
var newValue = dataGridView.CurrentCell.EditedFormattedValue;
    
这是代码,它将触发dataGridView的comboBox中的选择事件:
public Form1()
{
    InitializeComponent();

    DataGridViewComboBoxColumn cmbcolumn = new DataGridViewComboBoxColumn();
    cmbcolumn.Name = \"cmbColumn\";
    cmbcolumn.HeaderText = \"combobox column\";
    cmbcolumn.Items.AddRange(new string[] { \"aa\", \"ac\", \"aacc\" });
    dataGridView1.Columns.Add(cmbcolumn);
    dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
}

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    ComboBox combo = e.Control as ComboBox;
    if (combo != null)
    {
        combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
        combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
    }
}

private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    ComboBox cb = (ComboBox)sender;
    string item = cb.Text;
    if (item != null)
        MessageBox.Show(item);
}
    
ComboBox cmbBox = (ComboBox)sender;                
MessageBox.Show(cmbBox.SelectedValue.ToString());
    

要回复问题请先登录注册