I must be having a brain block or something, but for some reason I cannot get a drop down list to databind properly on a postback in ASP.NET.
Check out the following code:
Result = Item.GetItemList("sku,descript",null,"descript");
if (Result > 0)
{
ListItem item = null;
this.cmbParentPk.DataSource = Item.DataSet.Tables["ItemList"];
this.cmbParentPk.DataTextField ="descript";
this.cmbParentPk.DataValueField = "sku";
--> this.cmbParentPk.DataBind();
// *** Add blank item if for items that aren't a subitem
item = new ListItem();
item.Value = "";
item.Text = "*** This item is not a subitem";
this.cmbParentPk.Items.Insert(0,item);
}
This code works fine on a non-postback to the page, but if fails once submitted with a POST on the second hit to the page. I get the following:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: value
Source Error:
Line 119: this.cmbParentPk.DataTextField ="descript";
Line 120: this.cmbParentPk.DataValueField = "sku";
Line 121: this.cmbParentPk.DataBind();
Line 122:
Line 123: // *** Add blank item if for items that aren't a subitem |
As far as I can tell there’s no invalid data in the table – no nulls or other extended characters. I also checked to make sure there are no duplicate values in the table (although that shouldn't matter anyway). In this case I’m saving an existing inventory item and not even making a change to the data on the page. Simply re-posting.
But the code works fine if I do the binding manually:
Result = Item.GetItemList("sku,descript",null,"descript");
if (Result > 0)
{
ListItem item = null;
foreach(DataRow dr in Item.DataSet.Tables["ItemList"].Rows)
{
item = new ListItem();
item.Value = (string) dr["Sku"];
item.Text = (string) dr["Descript"];
this.cmbParentPk.Items.Add(item);
}
// *** Add blank item if for items that aren't a subitem
item = new ListItem();
item.Value = "";
item.Text = "*** This item is not a subitem";
this.cmbParentPk.Items.Insert(0,item);
}
This works just fine.
So the big question is WTF is ASP.NET choking on? It appears to be the value which would seem to point to some sort of SelectedValue binding, except I’m not doing any binding at that point (there’s some custom databinding using my two-way databinding controls, but this happens much later in the code).
Other Posts you might also like