首先有个问题(DropDownList 有一个无效的 SelectedValue,因为它不存在于项目列表中 https://stackoverflow.com/questions/1869150/dropdownlist-has-a-selectedvalue-which-is-invalid-because-it-does-not-exist-in-th , DropDownList“有一个无效的 SelectedValue,因为它不存在于项目列表中” https://stackoverflow.com/questions/5704651/dropdownlist-has-a-selectedvalue-which-is-invalid-because-it-does-not-exist-in-t , asp:DropDownList 错误:“DropDownList1”的 SelectedValue 无效,因为它不存在于项目列表中 https://stackoverflow.com/questions/38612/aspdropdownlist-error-dropdownlist1-has-a-selectedvalue-which-is-invalid-beca)关于这个问题,并且有建议的解决方法,但我的问题实际上是为什么会发生这种情况。更重要的是,我对建议的解决方法并不满意,我发现它们非常丑陋。
所以有一个带有下拉列表和按钮的页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="TestWebApplication.WebForm2" ViewStateMode="Disabled" %>
<html lang="en" >
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlTest" runat="server">
</asp:DropDownList>
<asp:Button Text="Test" ID="btnTest" runat="server" onclick="btnTest_Click" />
</div>
</form>
</body>
</html>
我将 ddlTest 与 Page_Init 上的一些项目绑定,然后在 btnTest_Click 中再次绑定:
using System;
namespace TestWebApplication
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
//SelectedIndex is -1, SelectedValue is "", SelectedItem is null
ddlTest.DataSource = new[] { 1, 2, 3 };
ddlTest.DataBind();
ddlTest.SelectedValue = "3";
}
protected void btnTest_Click(object sender, EventArgs e)
{
//SelectedIndex is 2, SelectedValue is "3", SelectedItem is {3}
ddlTest.ClearSelection();
//SelectedIndex is 0, SelectedValue is "1", SelectedItem is {1}
ddlTest.SelectedIndex = -1; //Nothing changes including SelectedIndex
ddlTest.SelectedValue = ""; //Nothing changes including SelectedValue
ddlTest.Items.Clear();
//SelectedIndex is -1, SelectedValue is "", SelectedItem is null
ddlTest.DataSource = null; //Nothing changes except for the DataSource property
ddlTest.DataSource = new[] { 1, 2 };
ddlTest.DataBind();//Exception!
//'ddlTest' has a SelectedValue which is invalid because it does not exist in the list of items.
//Parameter name: value
}
}
}
为什么我会遇到异常。我尝试了这些的不同版本,但没有一个有效。我尝试仅使用 ClearSelection 但仍然遇到相同的异常。这是控件中的错误还是我错过的东西。其他问题的丑陋解决方法是唯一的解决方案吗?
注意 - 即使删除按钮并且所有代码都移动到单个事件处理程序中,该错误也是可重现的。只需绑定一次设置选定的值并再次绑定即可。