繁体   English   中英

以编程方式选择索引0(从-1)时,组合框未触发SelectedIndexChanged

[英]Combobox not firing SelectedIndexChanged when programmatically selecting index 0 (from -1)

我有一个组合框,我正在使用SelectIndexChanged事件捕获用户和程序更改。

清除并重新加载绑定到组合框的列表将自然触发索引为-1的事件处理程序。

但是然后selectedindex = -1

combobox1.SelectedIndex = 0 ; // will NOT fire the event.

combobox1.SelectedIndex = 1 ; // or higher number WILL fire the event.

在这两种情况下,我都是以编程方式更改selextedindex并期望事件被触发。

我以简单的形式验证了行为。

namespace cmbTest
{
    public partial class Form1 : Form
    {
        private BindingList<string> items = new BindingList<string>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.DataSource = items;
            loadItems();
        }

        private void loadItems()
        {
            items.Add("chair");
            items.Add("table");
            items.Add("coffemug");
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            MessageBox.Show("Fired with selected item index:" + comboBox1.SelectedIndex);
        }

        private void button1_Click(object sender, EventArgs e)
        {

            int index = comboBox1.SelectedIndex;

            // Clear and reload items for whatever reason.
            items.Clear();
            loadItems();

            // try select old item index; if it doesnt exists, leave it.
            try { comboBox1.SelectedIndex = index; }
            catch { }
        }





    }
}

该表单具有一个combobox1和一个button1。

为清楚起见进行编辑(我希望):

  1. 运行程序
  2. 选择“椅子”。 消息“使用选定的项目索引:0触发”
  3. 点击按钮。 消息“与所选项目索引一起发射:-1”
  4. 选择“表格”。 消息“与选定的项目索引一起发射:1”
  5. 点击按钮。 消息“使用所选项目索引:-1触发”和“使用所选项目索引:1触发”。

我也希望在选择“椅子”时按一下按钮也会收到两条消息,因为我以编程方式将索引更改为0。

那么,为什么这不能按我预期的那样工作?什么是可以接受的解决方法?

当您将第一个项目添加到项目集合时,索引会自动更改为0。这就是为什么当您之前的索引另存为0,然后使用此行comboBox1.SelectedIndex = index;再次对其进行设置的原因comboBox1.SelectedIndex = index; ,索引不变。 因此,该事件未触发。

查看ComboBox的源代码,在两种情况下不会触发该事件:抛出了异常,或者索引设置为与原来相同的值。

如果您真的想对此进行一些破解,可以采用以下方式:

int index = comboBox1.SelectedIndex;

// Clear and reload items for whatever reason.
items.Clear();
loadItems();

if(comboBox1.SelectedIndex == index)
{
    comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged;
    comboBox1.SelectedIndex = -1;
    comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
}

// try select old item index; if it doesnt exists, leave it.
try { comboBox1.SelectedIndex = index; }
catch
{
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM