Reputation: 1102
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.
Upvotes: 0
Views: 2796
Reputation: 1020
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;
}
}
Upvotes: 3
Reputation: 3379
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
Upvotes: 4