【问题标题】:C# - Combobox index change after editingC# - 编辑后组合框索引更改
【发布时间】:2011-04-14 16:16:58
【问题描述】:

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

C#: Real-time combobox updating

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

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

【问题讨论】:

  • 我们在这里看不到上一个答案,也看不到你是如何实现的。请更新上一个问题。投票结束。
  • 可能是它正在改变索引,因为它会检查 items[selectedIndex] 是否等于 comboBox1.Text,如果不等于则返回 -1。

标签: c# combobox indexing editing textchanged


【解决方案1】:

根据我对问题的理解,您可以做一件事。在 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 事件处理程序方法中。 希望对你有帮助

【讨论】:

  • comboBox1.SelectedIndex 等于 -1
  • 谢谢你的代码,我明天才能测试,所以我会告诉你的。
【解决方案2】:
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;
    }
}

【讨论】:

  • 谢谢,其他代码可能也可以工作,但对我来说,这个代码似乎更灵活一些。
猜你喜欢
  • 2017-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
相关资源
最近更新 更多