When I call DataBind()
on a DropDownList in ASP.NET 4, it's throwing an ArgumentNullException:
System.ArgumentNullException: Value cannot be null. Parameter name: container at System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName) at System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName, String format) at System.Web.UI.WebControls.ListControl.PerformDataBinding(IEnumerable dataSource) at System.Web.UI.WebControls.ListControl.OnDataBinding(EventArgs e) at System.Web.UI.WebControls.ListControl.PerformSelect() at System.Web.UI.WebControls.BaseDataBoundControl.DataBind() at MyNamespace.MyClass.MyFunction()
Here is my code:
myDropdown.Items.Clear();
myDropdown.ClearSelection();
myDropdown.Items.Add(new ListItem("-Select-", "-1"));
myDropdown.DataSource = myDataSource; //List<T> of my business objects
myDropdown.DataBind();
I found this forum post that seems to suggest taking away the DataValueField and DataTextField settings on the dropdown, which I've set in markup. When I do that and change the second-to-last line of my code to this so I still get meaningful text in the options:
myDropdown.DataSource = myDataSource.Select(elem => new ListItem(elem.Text, elem.Id));
...it still doesn't work. It does work, though, when I take away the line that adds the "-Select-" option. And it only breaks when there is no element selected before it's data bound.
What's going on?
Further Google searching found this other post that suggests that null objects in the datasource can cause this problem. I changed my DataSource line to this:
myDropdown.DataSource = myDataSource.Where(elem => elem != null);
And it worked.
I have yet to determine why/how I have null values in that list. Hmm.