2010-09-20 23 views
0

刚才有人回答我的问题,关于如何编辑装有文本文件的组合框,以及如何保存最近编辑的行。现在C# - 编辑后的组合框索引更改

C#: Real-time combobox updating

的问题是,我只能改变一个字母它更新之前,然后将selectedIndex更改为-1,所以我要选择我在下拉列表中再次编辑线。

希望有人知道它为什么会改变索引,以及如何阻止它做到这一点。

+0

我们在这里看不到prev的答案,或者你是如何实现它的。请更新上一个问题。投票结束。 – 2010-09-20 13:00:44

+0

[C#:实时组合框更新]的可能重复(http://stackoverflow.com/questions/3750990/c-real-time-combobox-updating) – 2010-09-20 13:01:04

+0

我做了,无论如何。 – Nick 2010-09-20 13:25:18

回答

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; 
    } 
} 
+0

谢谢,其他代码也可能有效,但这个对我来说似乎更灵活一些。 – Nick 2010-09-22 06:23:35

4

正如我对这个问题的理解一样,你可以做一件事。在comboBox1_TextChanged方法中,您可以设置一个bool变量,比如说textChangedFlag为true,而不是放置以前的代码,您可以将此变量的默认值设置为false。 然后使用KeyDown事件来编辑组合框项目。 我会给出一个示例代码。

示例代码:

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

      } 
     } 

你可以把这个代码在KeyDown事件处理程序方法。 希望它有帮助

+0

comboBox1.SelectedIndex等于-1 – SKINDER 2010-09-20 14:27:08

+0

谢谢你的代码,我不能测试它,直到明天,所以我会让你知道。 – Nick 2010-09-21 06:31:57