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

Bob*_*nes 31 asp.net data-binding

我反复遇到这个问题,并且不知道造成它的原因.我在DataBind中得到一个异常:SelectedValue which is invalid because it does not exist in the list of items.

以下是一些重要的信息:

  1. 我在基础数据发生变化时定期重新加载listOrgs.
  2. Organization.DTListAll调用返回2个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();
Run Code Online (Sandbox Code Playgroud)

小智 60

显然我发布的解决方案并不完全有效......最终在我的应用程序中我改为:

listOrgs.Items.Clear();
listOrgs.SelectedIndex = -1;
listOrgs.SelectedValue = null;
listOrgs.ClearSelection();     // Clears the selection to avoid the exception (only one of these should be enough but in my application I needed all..)
listOrgs.DataSource = new Organization().DTListAll(SiteID);
listOrgs.DataTextField = "OrganizationName"; 
listOrgs.DataValueField = "OrganizationID"; 
listOrgs.DataBind();
Run Code Online (Sandbox Code Playgroud)

  • 这是唯一对我有用的解决方案.我从来没有意识到股票ddl是多么可怕 (12认同)
  • `listOrgs.Items.Clear(); listOrgs.SelectedIndex = -1; listOrgs.SelectedValue = null; listOrgs.ClearSelection();`经过一些实验,我能够将这些行简化为:`listOrgs.Items.Clear(); listOrgs.SelectedValue = null;`我仍然不明白为什么其中一个语句是不够的 (4认同)

Daz*_*Cat 7

我一直收到这个错误.
奇怪的是,在我设置数据源并在删除项目后重新绑定所选索引= -1.

如果我明确设置selectedIndex = -1; 然后它工作,并不会抛出错误.

因此,即使它已经-1,将其设置为-1也可以防止错误.

怪啊呃?


Can*_*var 1

更改前两行:

listOrgs.SelectedItem.Selected = false; 
listOrgs.Items.Clear(); 
Run Code Online (Sandbox Code Playgroud)