DataGridView autoComplete comboBox column not reta

2019-06-28 04:09发布

问题:

I have a bound dataGridView with an autoComplete combobox column and the autocomplete is working except that am observing one behaviour thats abit irritating.

When i type text in the autocomplete cell for the first time and move to the next cell with the tabKey, my selection is not retained, what ever i selected is cleared and the autocomplete cell is left null. If ii immediately use the left arrow key to return to that autocomplete cell and type in text, what ever i select is retained with out any issues.

So, the problem am having is getting the cell retain my very first initial selection, the only work around now is to Tab to the next cell, then return back to this problematic autoComplete combobox cell and do the typing all all-over. At this point, it works.

Could there be some event i should handle to commit my selected text on cell leave?

Code:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (e.Control is ComboBox)
        {
                ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
                ((ComboBox)e.Control).AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
                ((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
        }
    }

Edit: On CellLeave below, value is also returned as null even when i have made a selection.

 private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
    {
        var Row = this.dataGridView1.CurrentRow.Index;
        string value = this.dataGridView1["itemID", Row].Value.ToString();
    }

回答1:

handling the CurrentCellDirtyStateChanged event resolved the issue, i hope it doesn't result into some other issue though!

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (dataGridView1.IsCurrentCellDirty)
    {
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}


回答2:

Very Simply this can be done by invoking notifycurrentcelldirty event on editingcontrol showing event.

Private Sub dataGridView1_EditingControlShowing(sender As Object, 
                         e As Forms.DataGridViewEditingControlShowingEventArgs) 
                         Handles Me.EditingControlShowing
            dataGridView1.NotifyCurrentCellDirty(True)
End Sub

Private Sub dataGridView1_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles Me.CurrentCellDirtyStateChanged
            If IsCurrentCellDirty = True Then
                CommitEdit(Forms.DataGridViewDataErrorContexts.Commit)
            End If
End Sub