DataSource更改时未调用ComboBox SelectedValueChanged

时间:2016-06-20 07:53:03

标签: c# .net winforms

我很惊讶我以前没有注意到这一点,并且无法在任何地方找到这个问题。也许我错过了一些明显的东西。当我将DataSource的{​​{1}}设置为ComboBox时,如果我从列表中删除了某个项目,则BindingListSelectedValueChanged个事件不会已解雇,但SelectedValue确实发生了变化。以下是重现的完整来源:

SelectedIndexChanged

所有表单都有一个public partial class Form1 : Form { public readonly BindingList<string> Items = new BindingList<string>(); public Form1() { InitializeComponent(); Items.Add("One"); Items.Add("Two"); Items.Add("Three"); comboBox1.DataSource = Items; comboBox1.SelectedValueChanged += comboBox1_SelectedValueChanged; comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged; button1.Click += button1_Click; timer1.Interval = 250; timer1.Tick += timer1_Tick; timer1.Start(); } private string GetCurrentText() { return comboBox1.SelectedValue as string ?? "NULL"; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { textBox1.Text += "Index Changed: " + GetCurrentText() + Environment.NewLine; } private void comboBox1_SelectedValueChanged(object sender, EventArgs e) { textBox1.Text += "Value Changed: " + GetCurrentText() + Environment.NewLine; } private void timer1_Tick(object sender, EventArgs e) { Text = GetCurrentText(); } private void button1_Click(object sender, EventArgs e) { Items.Remove((string)comboBox1.SelectedValue); } } ,一个ComboBox,一个Button来跟踪实际的ComboBox的SelectedValue和一个多行Timer来记录事件。

要重现,请运行表单,从组合框中选择第二个值(&#34; Two&#34;),然后按按钮。按下按钮时不会触发TextBoxSelectedValueChanged事件,但表单的文本将显示计时器给出的新值(&#34; Three&#34;),也将是组合框中显示的值。因此实际选择的值肯定会发生变化,没有事件被触发。

不幸的是没有SelectedIndexChanged事件,所以我不知道开发者应该如何处理这种情况。我不确定哪个&#34; edge&#34;案件将导致价值无声地改变,所以无论我提出什么样的黑客解决方案都可能无法涵盖所有​​情况。我想知道是否有人提出了真正的解决方案。

1 个答案:

答案 0 :(得分:-1)

这在逻辑上是正确的。选择&#39; Two&#39; comboBox1.SelectedIndex = 1。然后你删除了&#39; Two&#39;项目。所以&#39;三&#39;成为索引&#39; 1&#39;来自&#39; 2&#39;,组合框中没有更改索引。没有组合的事件会被解雇。

您第二次点击按钮将触发组合的事件。