2

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

Tom
  • 1,270
  • 2
  • 12
  • 25

1 Answers1

1

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,

LaGrandMere
  • 10,265
  • 1
  • 33
  • 41
  • Well I am only hooking up the event handler of the control when it is not null. On the first attempt the control is not null and I am able to hook up to the "control_DropDownClosed" event. I can even breakpoint inside the event. On the first try through, EndEdit() reverts the value back to what it was before the dropdown item was selected. All subsequent calls to EndEdit() in that function work just fine so I'm very confused. – Tom Dec 10 '10 at 17:15
  • 1
    @Tom I checked on the Internet and I found someone with the same problem than you : http://www.visualstudiodev.com/visual-basic-express-edition/datagridviewcomboboxcolumn-70711.shtml His workaround was to force the value in the OnLeave EventHandler. – LaGrandMere Dec 10 '10 at 17:24
  • 1
    Well I found a way around this as well, I just keep track of it's the first time using the editing control, if it is I forcefully reset the value after the EndEdit call. Feels like a hack but it works so I'm happy. – Tom Dec 10 '10 at 19:07