簡體   English   中英

在bindingsource上調用ResetBindings來更新ComboBox會導致初始化控制,如何在不初始化的情況下更新項目?

[英]Calling ResetBindings on bindingsource to update ComboBox results in initialising control, how to update items without initialising?

我有一個字符串列表,它是BindingSource對象的DataSource,它轉而是ComboBox的DataSource。

當我更改List(添加或刪除字符串)時,我調用BindingSource上的ResetBindings()方法。 這會按預期更新ComboBox中的項目,但它也會將SelectedIndex設置為“0”,而不是未初始化的值“-1”。 我想在不初始化ComboBox的情況下更新項目

我已經嘗試在SelectedIndexChanged事件處理程序中處理它,如下所示:

private void cmbSelectxx_SelectedIndexChanged(object sender, EventArgs e)
{
   ComboBox cmb = (ComboBox)sender;

   if (!cmb.Focused)
   {
      cmb.SelectedIndexChanged -= new EventHandler(cmbSelectxx_SelectedIndexChanged);
      cmb.SelectedIndex = -1;
      cmb.ResetText();
      cmb.SelectedText = "";
      cmb.SelectedIndexChanged += new EventHandler(cmbSelectxx_SelectedIndexChanged);
      return;
   }

   //...
}

但這並沒有解決我的問題

將控制綁定到數據代碼:

bs = new BindingSource();
bs.DataSource = SomeList;
cmbSelectxx.DataSource = bs;

直接在BindingSource上執行添加/刪除操作,而不是SomeList 這些添加/刪除操作傳播回SomeList '請注意,如果刪除ComboBox中當前選定的項,它將更新為最合適的值。

假設您的SomeList包含值“a”,“b”,“c”,“d”。

  1. 如果選擇“b”並將其從BindingSource刪除,則ComboBox.SelectedItem將更改為“c”。
  2. 如果選擇“b”並從BindingSource刪除“a”,則ComboBox.SelectedItem不會更改。
  3. 如果選擇“d”然后刪除,則ComboBox.SelectedItem將更改為“c”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM