簡體   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