什么事件会捕获 DataGridViewCell 中组合框中的值变化? [英] What event catches a change of value in a combobox in a DataGridViewCell?

查看:23
本文介绍了什么事件会捕获 DataGridViewCell 中组合框中的值变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 DataGridView 单元格中的 ComboBox 中更改值时处理该事件.

I want to handle the event when a value is changed in a ComboBox in a DataGridView cell.

CellValueChanged 事件,但在我单击 DataGridView 内的其他位置之前,该事件不会触发.

There's the CellValueChanged event, but that one doesn't fire until I click somewhere else inside the DataGridView.

一个简单的 ComboBox SelectedValueChanged 在选择新值后会立即触发.

A simple ComboBox SelectedValueChanged does fire immediately after a new value is selected.

如何向单元格内的组合框添加侦听器?

How can I add a listener to the combobox that's inside the cell?

推荐答案

上面的回答让我暂时走上了报春花路.它不起作用,因为它会导致多个事件触发并且只是不断添加事件.问题是上面捕获了 DataGridViewEditingControlShowingEvent 并且它没有捕获更改的值.因此,它会在您每次聚焦时触发,然后离开组合框,无论它是否已更改.

The above answer led me down the primrose path for awhile. It does not work as it causes multiple events to fire and just keeps adding events. The problem is that the above catches the DataGridViewEditingControlShowingEvent and it does not catch the value changed. So it will fire every time you focus then leave the combobox whether it has changed or not.

关于 CurrentCellDirtyStateChanged 的最后一个答案是正确的方法.我希望这可以帮助人们避免陷入困境.

The last answer about CurrentCellDirtyStateChanged is the right way to go. I hope this helps someone avoid going down a rabbit hole.

这里有一些代码:

// 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();
    }
}

这篇关于什么事件会捕获 DataGridViewCell 中组合框中的值变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆