views:

112

answers:

2

Hi again,

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.

http://stackoverflow.com/questions/3750990/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.

+5  A: 

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_programmer
comboBox1.SelectedIndex equals -1
SKINDER
Thank you for the code, I cant test it untill tomorrow so I'll let you know.
Nick
+3  A: 
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
Thank you, the other code might have worked too, but this one seemed a little more flexible to me.
Nick