【问题标题】:ComboBox SelectedIndexChanged event fired twice for items with same DisplayMember对于具有相同 DisplayMember 的项目,ComboBox SelectedIndexChanged 事件触发了两次
【发布时间】:2014-11-26 08:55:00
【问题描述】:

我有一个如下的组合框,其中包含 3 个项目(“abc”、“abc”和“bbb”)。 组合框还具有 AutoCompleteMode "SuggestAppend" 和 AutoCompleteSource "ListItems" 属性。现在我希望文本框显示组合框的 SelectedIndex,如下所示:

http://i.imgur.com/MJ4JdDN.png

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.textBox1.Text = this.comboBox1.SelectedIndex.ToString(); 
    }

在我选择第二个“abc”之前,一切似乎都很好,SelectedIndexChanged 事件将第一次进入并在文本框中正确显示索引。但是当组合框失去焦点时,SelectedIndexChanged 事件会再次触发,导致索引显示错误。我发现它只发生在具有相同价值的物品上。有没有办法阻止事件触发两次?

http://i.imgur.com/gEw46xf.png

            this.comboBox1.DataSource = dt;
            this.comboBox1.DisplayMember = "Description"; //Some descriptive field to be shown in combobox
            this.comboBox1.ValueMember = "Code"; //Unique code that user won't understand
            this.comboBox1.SelectedIndex = -1;

【问题讨论】:

  • 为什么有一个包含相同值的组合框?
  • 在您的 selectionchange 方法中尝试 e.Handled=true
  • 它是 win 形式...我在哪里可以找到我的 xaml 代码? :p SelectedIndexChanged 似乎没有 e.Handled KeyPressArgs?.... 我需要具有相同的值,因为组合框的唯一性在“ValueMember”而不是“DisplayMember”中
  • 尝试使用 SelectionChangeCommitted 它应该只触发一次
  • SelectionChangeCommitted 不太合适,因为 ComboBox 的“DropDownStyle”是“DropDown”,所以如果用户在框中输入值,索引不会改变

标签: c# winforms combobox


【解决方案1】:

将 comboBox1_SelectedIndexChanged 代码放入 comboBox1_ValueChanged 中,您将在事件参数中获取索引(发送者,即您的组合框将其投射到组合框中)。

使用 comboBox1.SelectedIndex 你会得到索引。

【讨论】:

  • 与“SelectedValueChanged”事件相同的问题,因为我有 2 个具有相同值的项目......我想我现在唯一能做的就是关闭“AutoCompleteMode”和“AutoCompleteSource” " 的组合框 =/
  • value 是 key 成员,如果它相同则应该是唯一的,那么它是冗余字段并且不是一个好习惯。所以一定要创建一个唯一的密钥。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-31
  • 2018-07-13
  • 2012-04-28
  • 2021-03-17
  • 2014-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多