2

当我DataBind()在 ASP.NET 4 中调用 DropDownList 时,它会抛出 ArgumentNullException:

System.ArgumentNullException:值不能为空。参数名称:System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName, String format) at System.Web.UI.WebControls 的 System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName) 的容器。 ListControl.PerformDataBinding(IEnumerable dataSource) 在 System.Web.UI.WebControls.ListControl.OnDataBinding(EventArgs e) 在 System.Web.UI.WebControls.ListControl.PerformSelect() 在 System.Web.UI.WebControls.BaseDataBoundControl.DataBind( ) 在 MyNamespace.MyClass.MyFunction()

这是我的代码:

myDropdown.Items.Clear();
myDropdown.ClearSelection();
myDropdown.Items.Add(new ListItem("-Select-", "-1"));
myDropdown.DataSource = myDataSource; //List<T> of my business objects
myDropdown.DataBind();

我发现这个论坛帖子似乎建议删除我在标记中设置的下拉菜单中的 DataValueField 和 DataTextField 设置。当我这样做并将代码的倒数第二行更改为此时,我仍然会在选项中获得有意义的文本:

myDropdown.DataSource = myDataSource.Select(elem => new ListItem(elem.Text, elem.Id));

……还是不行。但是,当我删除添加“-Select-”选项的行时,它确实有效。只有在数据绑定之前没有选择任何元素时,它才会中断。

这是怎么回事?

4

1 回答 1

2

进一步的谷歌搜索发现this other post表明数据源中的空对象可能导致此问题。我将我的 DataSource 行更改为:

myDropdown.DataSource = myDataSource.Where(elem => elem != null);

它奏效了。

我还没有确定为什么/如何在该列表中有空值。唔。

于 2012-06-11T20:43:39.037 回答