【问题标题】:ComboBox.SelectedIndexChanged is not raised未引发 ComboBox.SelectedIndexChanged
【发布时间】:2014-10-27 15:33:11
【问题描述】:

我有一个只包含一个空 ComboBox 的表单。 我将 DataSource 设置为一个空的 BindingList。 当我向 BindingList 添加某些内容时,它被选中并且 combobox1.SelectedIndex 更改,但事件 comboBox1_SelectedIndexChanged 没有引发,即使在我看来也应该如此。为什么不养?当单个项目被移除时,comboBox1_SelectedIndexChanged 被正确触发。

public partial class Form1 : Form
{
    public Form1()
    {
        var test_ = new BindingList<int>();
        InitializeComponent();
        comboBox1.DataSource = test_;
        Console.WriteLine(comboBox1.SelectedIndex); // -1
        test_.Add(42); // BUG? no comboBox1_SelectedIndexChanged -> 0
        Console.WriteLine(comboBox1.SelectedIndex); // 0
        test_.Remove(42); // comboBox1_SelectedIndexChanged -> -1
        Console.WriteLine(comboBox1.SelectedIndex); // -1
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Console.WriteLine("index changed " + comboBox1.SelectedIndex);
    }
}

【问题讨论】:

    标签: c# winforms data-binding


    【解决方案1】:

    你的逻辑不正确。

    comboBox1.SelectedIndex-1 并不意味着您在-1 位置选择了item
    这意味着在comboBox1 中没有选择项目。

    添加一个项目,SelectedIndex 变为 0。选择没有发生更改,因为一开始没有没有选择项目(SelectedIndex = -1)

    【讨论】:

    • 你确定?当状态从“选择项目 0”变为“未选择项目”时,我会收到一个事件,那么反向操作不应该也引发事件吗?
    【解决方案2】:

    解决该错误的一种方法是利用您正在使用的 BindingList 集合的 ListChanged 事件:

    var test_ = new BindingList<int>();
    comboBox1.DataSource = test_;
    test_.ListChanged += (sender, e) => {
      if (e.ListChangedType == ListChangedType.ItemAdded && test_.Count == 1) {
        comboBox1_SelectedIndexChanged(comboBox1, EventArgs.Empty);
      }
    };
    test_.Add(42);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      • 2021-05-23
      • 2020-05-15
      相关资源
      最近更新 更多