Search code examples
c#winformscombobox

C# Combobox Selected.Index = -1 not working


It should reset the Combobox to no value, Combobox is in the same panel, but the code sets the index to 0 which is the first value of the data binded list. It works on the second click though... ON the first click it sets the index to 0, on the second to -1.

        if (((Button)sender).Parent.Controls.OfType<ComboBox>().Count() > 0)
        {
           foreach(ComboBox C in ((Button)sender).Parent.Controls.OfType<ComboBox>().ToList())
            {
                if(C.SelectedIndex != -1)
                {
                    C.SelectedIndex = -1;
                }
            }
        }

Solution

  • thanks all for answers...in the end I solved the issue with a workaround. The problem was, that button of the code above needed two clicks to set index to -1. On the first click it moved to 0 and on the second to -1. I dont know why tho...Another problem was i had a index changed event on combobox and i wanted to fire it only once - not twice. I solved the problem this way...

            if (((Button)sender).Parent.Controls.OfType<ComboBox>().Count() > 0)
            {
               foreach(ComboBox C in ((Button)sender).Parent.Controls.OfType<ComboBox>().ToList())
                {
                    if(C.SelectedIndex != -1)
                    {
                        C.SelectedIndexChanged -= this.ComboBox_Promo_SelectedIndexChanged;
                        while (C.SelectedIndex != -1)
                        {
                            C.SelectedIndex = -1;
                        }
                        C.SelectedIndexChanged += this.ComboBox_Promo_SelectedIndexChanged;
                        this.ComboBox_Promo_SelectedIndexChanged(C, EventArgs.Empty);
                    }
                }
            }