Event that fires during DataGridViewComboBoxColumn SelectedIndexChanged

后端 未结 3 1214
暗喜
暗喜 2020-12-01 14:17

I have DataGridView with two columns. The first column is TextBoxCol(DataGridViewTextBoxColumn) and the Second one is ComboBoxCol(DataGridVie

3条回答
  •  余生分开走
    2020-12-01 14:46

    This answer is floating around in a couple of places.

    Using the DataGridViewEditingControlShowingEventHandler will fire more events than you intend. In my testing it fired the event multiple times.

    Also using the combo.SelectedIndexChanged -= event will not really remove the event, they just keep stacking.

    Anyway, I found a solution that seems to work. I'm including a code sample below:

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

提交回复
热议问题