Bob*_*nes 31 asp.net data-binding
我反复遇到这个问题,并且不知道造成它的原因.我在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();
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)
我一直收到这个错误.
奇怪的是,在我设置数据源并在删除项目后重新绑定所选索引= -1.
如果我明确设置selectedIndex = -1; 然后它工作,并不会抛出错误.
因此,即使它已经-1,将其设置为-1也可以防止错误.
怪啊呃?
更改前两行:
listOrgs.SelectedItem.Selected = false;
listOrgs.Items.Clear();
Run Code Online (Sandbox Code Playgroud)