我的自定义 ComboBox 源代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace IHWinUtility
{
public class IHComboBox : ComboBox
{
private IHComboBoxItems _ihComboBoxItems;
public IHComboBox()
{
this.DropDownStyle = ComboBoxStyle.DropDownList;
_ihComboBoxItems = new IHComboBoxItems(this);
}
new public IHComboBoxItems Items
{
get { return _ihComboBoxItems; }
set { _ihComboBoxItems = (IHComboBoxItems)value; }
}
new public string SelectedValue
{
get { return this.SelectedItem == null ? "" : ((IHComboBoxItem)this.SelectedItem).Value.ToString(); }
}
}
public class IHComboBoxItems : ComboBox.ObjectCollection
{
public IHComboBox _ihComboBox;
public IHComboBoxItems(IHComboBox owner) : base(owner)
{
_ihComboBox = owner;
}
public int Add(string Text, object Value)
{
int _retValue = 0;
IHComboBoxItem _item = new IHComboBoxItem();
_item.Text = Text;
_item.Value = Value;
_ihComboBox.Items.Add(_item);
_retValue = _ihComboBox.Items.Count;
return _retValue;
}
new public void Insert(int index, object item)
{
}
}
public class IHComboBoxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
}
然后我向该组合框添加了一些数据,如下所示:
private void Form1_Load(object sender, EventArgs e)
{
this.ihComboBox1.Items.Add("Text1", "Value1");
}
它运行良好。 我可以看到 Text1 绑定(bind)到我的 Combobox。 但问题是当我通过单击组合框中的箭头更改 selectedItem 时,它会抛出以下错误:
System.ArgumentOutOfRangeException was unhandled Message="InvalidArgument=Value of '0' is not valid for 'index'.
Parameter name: index
at: System.ArgumentOutOfRangeException System.Windows.Forms.ComboBox.ObjectCollection.get_Item(Int32 index)
at: System.Windows.Forms.ComboBox.get_SelectedItem()
at: System.Windows.Forms.ComboBox.get_Text()
at: System.Windows.Forms.ComboBox.WmReflectCommand(Message& m)
at: System.Windows.Forms.ComboBox.WndProc(Message& m)
at: System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at: System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at: System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
谁能帮我解决这个错误?
最佳答案
在选定的值中,您试图强制一个值。但该值不在集合中。
关于c# - 自定义 ComboBox 抛出 ArgumentOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13390093/