SelectedValue无效,因为它不存在于项列表中

时间:2009-09-04 02:12:01

标签: exception drop-down-menu selectedvalue

我反复遇到这个问题,并且不知道导致它的原因。我在DataBind中得到一个例外:

"SelectedValue which is invalid because it does not exist in the list of items"

以下是一些重要的信息:

  1. 我在基础数据发生变化时定期重新加载listOrgs。
  2. Organization.DTListAll调用返回大约500个Int,String对。
  3. 返回的数据中没有重复或空值
  4. 在下面的前两行之后,listOrgs.Items.Count为0,且Selected Value为0
  5. 执行DataBind操作时所选的值是不在返回的ID值集中的值
  6. listOrgs.Items.Clear();
    listOrgs.SelectedValue = "0";
    listOrgs.DataSource = new Organization().DTListAll(SiteID);
    listOrgs.DataTextField = "OrganizationName";
    listOrgs.DataValueField = "OrganizationID";
    listOrgs.DataBind();
    

1 个答案:

答案 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这是一个性能++)