DataGridView ComboBox列:从下拉列表中选择后更改单元格值?

joh*_*ohn 18 c# datagridview

我为我的DataGridView设置了一个ComboBoxColumn,并从枚举中设置了它的可选值.它主要按照我想要的方式运行,但有以下异常.

每当我单击下拉箭头然后选择其中一个枚举值时,它仍然处于"中间"状态,其中未触发CellValueChanged事件.我需要专注于另一个单元格或另一个控件来触发事件.

我还有一个DataGridView的Leaving事件的事件处理程序,它通过确保没有单元格为空来"验证"内容.

因此,如果我创建一行并填充所有单元格并进入(当前为空白)ComboBox列,请将其更改为值,然后单击"运行"按钮; 弹出我的错误对话框,因为ComboBox选择未"保存".

我怎么能绕过这个?有没有办法在我从下拉列表中选择一个值后自动"设置"该值?

谢谢!

ion*_*den 25

您应该使用CurrentCellDirtyStateChangedevent并强制对网格进行提交编辑:

    private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!


Bio*_*ukh 14

我会通过检查单元格类型而不是列类型来扩展Moop的答案.

dataGridView1.CurrentCellDirtyStateChanged += dataGridView1_CurrentCellDirtyStateChanged;

void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (CurrentCell is DataGridViewComboBoxCell)
    {
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        dataGridView1.EndEdit();
    }
}
Run Code Online (Sandbox Code Playgroud)


Moo*_*oop 5

我将通过在强制之前检查DataGridViewColumn的类型来扩展ionden的答案。这样可以防止其他对象过早提交。DataGridViewComboBoxColumnCommitEditDataGridViewColumn

    dataGridView1.CurrentCellDirtyStateChanged += dataGridView1_CurrentCellDirtyStateChanged;

    void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        DataGridViewColumn col = dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex];
        if (col is DataGridViewComboBoxColumn)
        {
            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
    }
Run Code Online (Sandbox Code Playgroud)