简体   繁体   中英

C# - Combobox index change after editing

A moment ago someone answered my question on how to edit the combobox loaded with a text file, and how to save the recently edited line.

C#: Real-time combobox updating

The problem now is that I can only change one letter before it updates, and then the selectedindex changes to -1, so I have to select the line I was editing again in the dropdown list.

Hopefully someone knows why it's changing index, and how to stop it from doing that.

As my understanding of the problem goes, you can do one thing. In the comboBox1_TextChanged method, instead of putting the previous code, you can just set a bool variable, say textChangedFlag to true and you can set the default value of this variable as false. And then use KeyDown event to edit the combobox item. I will give a sample code.

Sample Code:

if (e.KeyCode == Keys.Enter)
        {
            if (textChangedFlag )
            {
                if(comboBox1.SelectedIndex>=0)
                {
                    int index = comboBox1.SelectedIndex;
                    comboBox1.Items[index] = comboBox1.Text;
                    textChangedFlag = false;
                }

            }
        }

You can put this code in KeyDown event handler method. Hope it helps

private int currentIndex;

public Form1()
{
    InitializeComponent();

    comboBox1.SelectedIndexChanged += RememberSelectedIndex;
    comboBox1.KeyDown += UpdateList;
}

private void RememberSelectedIndex(object sender, EventArgs e)
{
    currentIndex = comboBox1.SelectedIndex;
}

private void UpdateList(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter && currentIndex >= 0)
    {
        comboBox1.Items[currentIndex] = comboBox1.Text;
    }
}

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