Search code examples
c#comboboxindexingeditingtextchanged

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.


Solution

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