我想使用BindingList作爲C#中的數據源,但每當我嘗試將第一項添加到BindingList,我得到一個ArgumentOutOfRangeException拋出。 在我的項目中,我需要清除BindingList,並在將其設置爲DataSource後添加新項目。ArgumentOutOfRangeException當添加第一項到綁定列表數據源
BindingList<string> dataSource = new BindingList<string>();
myComboBox.DataSource = dataSource;
dataSource.Add("something"); // Exception, here.
我知道這個異常由.NET Framework處理,但我需要找到一種方法來避免它。
我也試過
List<DirectoryInfo> list = aList.ToList();
list.AddRange(bList);
//set the index to -1 as suggested
var index = myComboBox.SelectedIndex;
myComboBox.SelectedIndex = -1;
myComboBox.DataSource = null;
bindingList.Clear();
bindingList.AddRange(list.Distinct());
if (bindingList.Count > 0)
{
//internal ArgumentOutOfRangeException here when binding
myComboBox.DataSource = bindingList;
myComboBox.SelectedIndex = index;
}
else
myComboBox.DataSource = null;
謝謝你,這裏是調用堆棧
System.Windows.Forms.dll!System.Windows.Forms.ComboBox.SelectedIndex.set(int value)
System.Windows.Forms.dll!System.Windows.Forms.ListControl.DataManager_PositionChanged(object sender, System.EventArgs e)
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.OnPositionChanged(System.EventArgs e)
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.ChangeRecordState(int newPosition, bool validating, bool endCurrentEdit, bool firePositionChange, bool pullData)
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.List_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e)
System.dll!System.ComponentModel.BindingList<System.__Canon>.OnListChanged(System.ComponentModel.ListChangedEventArgs e)
System.dll!System.ComponentModel.BindingList<System.__Canon>.FireListChanged(System.ComponentModel.ListChangedType type, int index)
System.dll!System.ComponentModel.BindingList<System.__Canon>.InsertItem(int index, System.__Canon item)
######.dll!System.Collections.ObjectModel.Collection<###########>.Add(######### item)
因此當您更改順序並首先將數據源分配給BindingList然後綁定到組合框時會發生什麼? – MethodMan 2014-11-05 20:53:16
異常來自組合框。由於它已綁定到數據源BindingList,所以當您添加到BindingList時,組合框會發現它已設置爲不在列表中的值和barfs。因此,首先將所需的一切添加到BindingList,然後將組合框綁定到列表,錯誤消失。 – StarPilot 2014-11-05 21:18:14
問題是:「我需要清除BindingList,並在將其設置爲DataSource後添加新項目。」我知道這個異常是由comboBox引發的,我們可以在callstack中看到它。但換行不是我的項目中的可用選項。 – Heyjee 2014-11-05 21:25:11