0

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.

Community
  • 1
  • 1
Nick
  • 1,082
  • 1
  • 15
  • 27
  • We can't see the prev answer here or how you implemented that. Please update the previous question. Voting to close. – H H Sep 20 '10 at 13:00
  • possible duplicate of [C#: Real-time combobox updating](http://stackoverflow.com/questions/3750990/c-real-time-combobox-updating) – H H Sep 20 '10 at 13:01
  • may be it's changing index because it checks if items[selectedIndex] equal comboBox1.Text and returns -1 if not. – SKINDER Sep 20 '10 at 14:39

2 Answers2

4

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

sumit_batcoder
  • 3,369
  • 1
  • 25
  • 36
3
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;
    }
}
SKINDER
  • 950
  • 3
  • 17
  • 39
  • Thank you, the other code might have worked too, but this one seemed a little more flexible to me. – Nick Sep 22 '10 at 06:23