ComboBox.SelectedIndexChanged is not raised
本文关键字:raised not is SelectedIndexChanged ComboBox | 更新日期: 2023-09-27 18:27:56
我有一个表单,它只包含一个空的ComboBox。我将DataSource设置为空BindingList。当我将某个内容添加到BindingList中时,它会被选中,并且combox1.SelectedIndex会发生更改,但事件combobox1_SelectedIndexChanged并没有引发,甚至在我看来应该很难。为什么没有提出?删除单个项目后,组合框1_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);
}
}
您的逻辑不正确。
comboBox1.SelectedIndex
是-1
并不意味着你在-1
位置选择了item
意味着comboBox1
中没有选择任何项目。
添加一个项目后,SelectedIndex
将变为0
。选择没有发生任何更改,因为没有项目被选在第一位(SelectedIndex=-1)。
解决该错误的一种方法是利用您正在使用的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);