Почему настройка comboBox.SelectedIndex не может изменить то, что отображается в редактируемой части моего ComboBox? - PullRequest
0 голосов
/ 05 июня 2018

У меня есть приложение C # Winform.Он имеет ComboBox.Моя цель состоит в том, чтобы элемент, выбранный в раскрывающемся списке ComboBox, отображался в редактируемой части ComboBox при вводе клавиши delete.Например, если ComboBox имеет элементы A, BC, тогда элемент A отображается при загрузке Form.Если щелкнуть раскрывающийся список, навести указатель мыши на элемент C, а затем нажать клавишу delete, я хочу, чтобы раскрывающийся список был отклонен, а C появился в редактируемой части ComboBox. * 1015.*

На самом деле, я подтвердил, что получаю текст выбранного элемента, но строка кода comboBox.SelectedIndex = comboBox.FindStringExact(selectedItemText); не меняет того, что появляется в редактируемой части ComboBox

MCVE.:

Примечание. Форма содержит поле со списком combobox и текстовое поле с именем textbox

using System.Collections;
using System.Collections.Specialized;
using System.Windows.Forms;

namespace Winforms_Scratch
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //using string collection because I need to simulate what is returned from an Application Settings list
            StringCollection computerList = new StringCollection { "C", "B", "A" };

            ArrayList.Adapter(computerList).Sort();

            comboBox.DataSource = computerList;

            comboBox.KeyDown += ComboBox_KeyDown;

            computerList = null;

        }

        private void ComboBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete && comboBox.DroppedDown)
            {
                ComboBox comboBox = (ComboBox)sender;

                //get the text of the item in the dropdown that was selected when the Delete key was pressed
                string selectedItemText = comboBox.GetItemText(comboBox.SelectedItem);

                //take focus away from the combobox to force it to dismiss the dropdown
                this.Focus();

                //load selectedItemText into the textbox just so we can verify what it is
                textBox.Text = selectedItemText;

                //set the comboBox SelectedIndex to the index of the item that matches the  
                //text of the item in the dropdown that was selected when the Delete key was pressed
                comboBox.SelectedIndex = comboBox.FindStringExact(selectedItemText);
                comboBox.Refresh();

                //Stop all further processing
                e.Handled = true;

            }
            else if (e.KeyCode == Keys.Down && !comboBox.DroppedDown)
            {
                //If the down arrow is pressed show the dropdown list from the combobox
                comboBox.DroppedDown = true;
            }
        }


    }
}

1 Ответ

0 голосов
/ 05 июня 2018

Я предполагаю, что комбо-бокс ведет себя по-разному после потери фокуса.В любом случае, я внес следующие изменения, и это работает, согласно моему пониманию ваших требований.Вы можете позвонить this.Focus() после установки выбранного элемента, если есть отдельное требование вернуть фокус в окно.Ваш подход SelectedIndex / FindStringExact работает идентично установке SelectedItem в строку.

Я избавился от текстового поля, поскольку, насколько я понимаю, это только для целей отладки.

private void ComboBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete && comboBox.DroppedDown)
    {
        ComboBox comboBox = (ComboBox)sender;

        //  Get the text of the item in the dropdown that was selected when the 
        //  Delete key was pressed
        string selectedItemText = comboBox.GetItemText(comboBox.SelectedItem);

        comboBox.DroppedDown = false;

        comboBox.SelectedItem = selectedItemText;

        //Stop all further processing
        e.Handled = true;

    }
    else if (e.KeyCode == Keys.Down && !comboBox.DroppedDown)
    {
        //  If the down arrow is pressed show the dropdown list from the combobox
        comboBox.DroppedDown = true;
    }
}
...