0

刚才有人回答了我关于如何编辑加载了文本文件的组合框以及如何保存最近编辑的行的问题。

C#:实时组合框更新

现在的问题是我在更新之前只能更改一个字母,然后 selectedindex 更改为 -1,所以我必须在下拉列表中再次选择我正在编辑的行。

希望有人知道它为什么要更改索引,以及如何阻止它这样做。

4

2 回答 2

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 事件处理程序方法中。希望能帮助到你

于 2010-09-20T14:15:43.210 回答
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;
    }
}
于 2010-09-20T14:19:29.077 回答