如果我嘗試更改ComboBox
的Items
中的值,它只會在新值不同時實際更新從當前值不區分大小寫進行比較。如果新值的字符串表示不區分大小寫等於當前值,則ComboBox.ObjectCollection不會更新
讓我們做一個ComboBox
一個項目:
ComboBox cboBox = new ComboBox();
cboBox.Items.Add("Apple");
下面的代碼將使ComboBox
仍表現出「蘋果」,儘管該字符串應該是不同的:
cboBox.Items[0] = "APPLE";
而幼稚解決方法,我一直在使用,這將使其正確顯示:
cboBox.Items[0] = "";
cboBox.Items[0] = "APPLE";
我想弄清楚這是怎麼發生的,所以我挖了一個反射器,發現了這個。這是ComboBox.ObjectCollection.SetItemInternal
方法當您試圖修改的值被調用:
internal void SetItemInternal(int index, object value)
{
...
this.InnerList[index] = value;
if (this.owner.IsHandleCreated)
{
bool flag = index == this.owner.SelectedIndex;
if (string.Compare(this.owner.GetItemText(value), this.owner.NativeGetItemText(index), true, CultureInfo.CurrentCulture) != 0)
{
this.owner.NativeRemoveAt(index);
this.owner.NativeInsert(index, value);
if (flag)
{
this.owner.SelectedIndex = index;
this.owner.UpdateText();
}
if (this.owner.AutoCompleteSource == AutoCompleteSource.ListItems)
{
this.owner.SetAutoComplete(false, false);
return;
}
}
else
{
if (flag)
{
this.owner.OnSelectedItemChanged(EventArgs.Empty);
this.owner.OnSelectedIndexChanged(EventArgs.Empty);
}
}
}
}
這true
在string.Compare
告訴它忽略字符串的情況下。爲什麼選擇此方法來決定是否更新該值?爲什麼他們沒有公開大小寫?
是否有替代方法更新ObjectCollection
中的項目,以便我不必猜測它是否實際更新?
編輯:我要指出的是,DropDownStyle
設置爲DropDownList
:這是一個只讀ComboBox
偶爾需要更新,由於在程序中其他地方的行動。
but this.InnerList [index] = value;這是什麼內心?您是否嘗試過在更改值後下拉組合?項目在那裏改變了嗎? – Steve 2012-03-22 23:24:39
'InnerList'是一個私有'ArrayList'。在更改值並下拉列表後,該項目不會被明顯改變;它仍然說「蘋果」。 – 2012-03-22 23:31:03