Search code examples
c#winformsdatagridviewcomboboxcell

Weird problem with DataGridViewComboBoxCell, trying to autocommit changes


So my goal is once a user clicks on the item from the dropdown list, the cell will automatically call EndEdit(). The weirdest thing is that the code below will work on the 2nd-n ComboBoxesCells that I drop down and select values from but NEVER the first one. Is there something I'm missing here??

        protected override void OnCellClick(DataGridViewCellEventArgs e)
        {
            base.OnCellClick(e);

            DataGridViewComboBoxEditingControl control = this.EditingControl as DataGridViewComboBoxEditingControl;
            if (control != null)
            {
                   control.DropDownClosed += new EventHandler(control_DropDownClosed);
            }
        }

            void control_DropDownClosed(object sender, EventArgs e)
            {
                this.EndEdit();
                DataGridViewComboBoxEditingControl control = sender as DataGridViewComboBoxEditingControl;
                control.DropDownClosed -= new EventHandler(control_DropDownClosed);
            }

Should add here that I am inheriting from DataGridView if that's not obvious


Solution

  • When something like "The weirdest thing is that the code below will work on the 2nd-n ComboBoxesCells that I drop down and select values from but NEVER the first one" happens, it's often because the Event happens before something you need is done.

    Seing your example, I would say that the first time, when you click,

    DataGridViewComboBoxEditingControl control = this.EditingControl as DataGridViewComboBoxEditingControl;
    

    gives you control == null.

    Maybe you should change the Event chosen to do your stuff from Click to SelectedIndexChanged or SelectedValueChanged ?

    Hope this helps,