![](/img/trans.png)
[英]Set SelectedIndex of combobox to an index found by a key value in the underlying DataSource?
[英]ComboBox remembers SelectedIndex after changing DataSource
背景
最近,我觀察到Winform ComboBox
控件的兩個不良行為:
DataSource
屬性設置為新對象會將SelectedIndex
值設置為0 DataSource
屬性設置為以前使用的對象“記住”以前SelectedIndex
值 以下是一些示例代碼來說明這一點:
private void Form_Load(object sender, EventArgs e)
{
string[] list1 = new string[] { "A", "B", "C" };
string[] list2 = new string[] { "D", "E", "F" };
Debug.Print("Setting Data Source: list1");
comboBox.DataSource = list1;
Debug.Print("Setting SelectedIndex = 1");
comboBox.SelectedIndex = 1;
Debug.Print("Setting Data Source: list2");
comboBox.DataSource = list2;
Debug.Print("Setting SelectedIndex = 2");
comboBox.SelectedIndex = 2;
Debug.Print("Setting Data Source: list1");
comboBox.DataSource = list1;
this.Close();
}
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
Debug.Print("Selected Index Changed, SelectedIndex: {0}", comboBox.SelectedIndex);
}
private void comboBox_DataSourceChanged(object sender, EventArgs e)
{
Debug.Print("Data Source Changed, SelectedIndex: {0}", comboBox.SelectedIndex);
}
這會產生以下輸出:
Setting Data Source: list1 Data Source Changed, SelectedIndex: -1 Selected Index Changed, SelectedIndex: 0 Setting SelectedIndex = 1 Selected Index Changed, SelectedIndex: 1 Setting Data Source: list2 Data Source Changed, SelectedIndex: 1 Selected Index Changed, SelectedIndex: 0 Setting SelectedIndex = 2 Selected Index Changed, SelectedIndex: 2 Setting Data Source: list1 Data Source Changed, SelectedIndex: 2 Selected Index Changed, SelectedIndex: 1
這是最后一個特別有趣的調試語句。
問題
這怎么可能,反正是為了防止這種行為?
ComboBox的“內存”是不確定的,還是受到易受垃圾收集影響的對象的支持? 前一種情況意味着調整DataSource結果的內存消耗,后一種情況表明ComboBox的行為在設置DataSource時是不可預測的。
我不知道DataSource對象的所有內部工作方式,但它可能是ComboBox保留列表的關聯CurrencyManager信息,使其能夠在重新連接DataSource時記住先前的位置。
您可以通過將列表包裝在新的BindingSource對象中來避免此行為:
comboBox.DataSource = new BindingSource(list1, null);
這將默認position屬性返回零(如果有記錄)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.