简体   繁体   中英

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 wich is the first value of the data binded list. It works on the second click tho...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;
                }
            }
        }

Perhaps you could try adding a dummy first item to your ComboBox to act as a placeholder.

This way you can deselect simply using ComboBox.SelectedIndex = 0;

Just be sure not to interpret this item in the ComboBox as a real item anywhere.

Also, try:

ComboBox.ResetText();
ComboBox.SelectedIndex = -1;

Or:

ComboBox.SelectedItem = null;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM