Search code examples
c#winformsdatagridviewcomboboxdatagridcomboboxcolumn

Set the highlighted item in the comboBox's dropdown list as the current value on cell exit or cell leave


private void dataGridViewSales_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
  if (this.dataGridViewSales.CurrentCell.ColumnIndex == 1)
  {
    ComboBox c = e.Control as ComboBox;
    ((ComboBox)c).AutoCompleteSource = AutoCompleteSource.ListItems;
    ((ComboBox)c).AutoCompleteMode = AutoCompleteMode.SuggestAppend;
    ((ComboBox)c).DropDownStyle = ComboBoxStyle.DropDown;
  }
}

With the code above, am having a problem where by after making my selection from an auto complete combobox, i loose my selection when i exit the combobox Cell by pressing the Tab key. Some times, the selection is retained, other times the selection is cleared, it sort of happens randomly.


Solution

  • 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);
                }
            }