我有一个ComboBox,我绑定到列表数据源。列表开始为空,之后我想向其中添加项目。问题是当我添加第一项时,我得到ArgumentOutOfRangeException:InvalidArgument =值'0'对'SelectedIndex'无效。 任何人都有解决方法吗?
这里描述了完全相同的问题,但我不确定它是否曾经解决过。
combobox--bindingsource-possible-bug
以下是该帖子的代码:
BindingList<int> bl = new BindingList<int>();
BindingSource bs = new BindingSource();
ComboBox cb = new ComboBox();
this.Controls.Add(cb);
cb.DataSource = bs;
bs.DataSource = bl;
//bs.DataError += delegate { throw new Exception("DataError"); };
bl.Add(99);
结果堆栈跟踪:
System.Windows.Forms.dll!System.Windows.Forms.ComboBox.SelectedIndex.set(int value) + 0x1e8 bytes
System.Windows.Forms.dll!System.Windows.Forms.ListControl.DataManager_PositionChanged(object sender, System.EventArgs e) + 0x36 bytes
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.OnPositionChanged(System.EventArgs e) + 0x39 bytes
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.ChangeRecordState(int newPosition, bool validating, bool endCurrentEdit, bool firePositionChange, bool pullData) + 0x16a bytes
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.List_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) + 0x2f9 bytes
System.Windows.Forms.dll!System.Windows.Forms.BindingSource.OnListChanged(System.ComponentModel.ListChangedEventArgs e) + 0x82 bytes
System.Windows.Forms.dll!System.Windows.Forms.BindingSource.InnerList_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) + 0x2e bytes
System.dll!System.ComponentModel.BindingList<int>.OnListChanged(System.ComponentModel.ListChangedEventArgs e) + 0x17 bytes
System.dll!System.ComponentModel.BindingList<int>.InsertItem(int index, int item) + 0x62 bytes
mscorlib.dll!System.Collections.ObjectModel.Collection<int>.Add(int item) + 0x36 bytes
WindowsFormsApplication1.exe!WindowsFormsApplication1.Form1.button1_Click(object sender, System.EventArgs e) Line 35 + 0x10 bytes C#
答案 0 :(得分:0)
绑定ComboBox后,无法添加任何不在数据源中的值。我建议您将新项添加到数据源中,并每次重新绑定ComboBox。
答案 1 :(得分:0)
您可以像这样使用ArrayList.Adapter -
在winforms应用程序上拖动组合框控件并包含以下代码:
var items = ArrayList.Adapter(comboBox1.Items);
items.Add("TestSample1");
在这里,您稍后会添加这些项目。