我反复遇到这个问题,并且不知道导致它的原因。我在DataBind中得到一个例外:
"SelectedValue which is invalid because it does not exist in the list of items"
以下是一些重要的信息:
listOrgs.Items.Clear();
listOrgs.SelectedValue = "0";
listOrgs.DataSource = new Organization().DTListAll(SiteID);
listOrgs.DataTextField = "OrganizationName";
listOrgs.DataValueField = "OrganizationID";
listOrgs.DataBind();
答案 0 :(得分:0)
检查现有值
this.DropDownList1.Items.Clear();
//--dont use this:
//this.DropDownList1.SelectedValue = "0";
DataTable dt = new DataTable();
dt.Columns.Add("x", typeof(System.Int32));
dt.Columns.Add("xs", typeof(System.String));
for (int x = 0; x < 100; x++)
{
DataRow dr = dt.NewRow();
dr["x"] = x;
dr["xs"] = x.ToString();
dt.Rows.Add(dr);
}
DropDownList1.DataValueField = "x";
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
// check for existing value:
int valueToCheck = 99; // last item
if (this.DropDownList1.Items.FindByValue(valueToCheck.ToString()) != null)
{
this.DropDownList1.SelectedValue = valueToCheck.ToString();
}
除此之外 - 你可能想尝试在绑定之前设置datatext和datavalue字段(afaik这是一个性能++)