检查其中属性的实现Reflector如下所示:
public object SelectedValue
{
get
{
if ((this.SelectedIndex != -1) && (this.dataManager != null))
{
object item = this.dataManager[this.SelectedIndex];
return this.FilterItemOnProperty(item, this.valueMember.BindingField);
}
return null;
}
set
{
if (this.dataManager != null)
{
string bindingField = this.valueMember.BindingField;
if (string.IsNullOrEmpty(bindingField))
{
throw new InvalidOperationException(SR.GetString("ListControlEmptyValueMemberInSettingSelectedValue"));
}
PropertyDescriptor property = this.dataManager.GetItemProperties().Find(bindingField, true);
int num = this.dataManager.Find(property, value, true);
this.SelectedIndex = num;
}
}
}
所以这似乎取决于this.dataManager不为空。
如果this.dataManager不为 null,则 setter 将调用setFind()为key您设置的值SelectedValue:
internal int Find(PropertyDescriptor property, object key, bool keepIndex)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
if (((property != null) && (this.list is IBindingList)) && ((IBindingList) this.list).SupportsSearching)
{
return ((IBindingList) this.list).Find(property, key);
}
if (property != null)
{
for (int i = 0; i < this.list.Count; i++)
{
object obj2 = property.GetValue(this.list[i]);
if (key.Equals(obj2))
{
return i;
}
}
}
return -1;
}
key如果为null,它将引发异常。
我猜dataManager只有当 ComboBox 插入容器(例如表单)时才设置为非 null,这就是为什么它不在容器中时不会爆炸的原因。
(实际上,dataManager当您将Control.DataSource属性设置为非空时,将设置为非空。)
但是,这似乎不太正确,因为您报告了 aNullReferenceException并且这显然会抛出ArgumentNullException.
[编辑] 这确实是一个ArgumentNullExeption; OP 已相应更新。