Skip to main content
 首页 » 编程设计

c#之asp.net 下拉列表在数据绑定(bind)后不接受文本

2024年02月06日15jyk

我的页面中有两个 dorpdownlists。一个是数据绑定(bind)的,另一个是在设计时添加的值。

<asp:DropDownList ID="maritalStatus" runat="server" Width="180px"> 
        <asp:ListItem Value="-1">--SELECT--</asp:ListItem> 
        <asp:ListItem>Single</asp:ListItem> 
        <asp:ListItem>Divorced</asp:ListItem> 
        <asp:ListItem>Married</asp:ListItem> 
        <asp:ListItem>Widow(er)</asp:ListItem> 
</asp:DropDownList> 
<asp:DropDownList ID="country" runat="server" Width="180px"> 
</asp:DropDownList> 

这是我填充国家下拉列表的代码隐藏

using (SqlCommand com = new SqlCommand("SELECT CountryID,  CountryName FROM Country", con)) 
{ 
      SqlDataAdapter dad = new SqlDataAdapter(com); 
      DataTable countryTab = new DataTable("Country"); 
      dad.Fill(countryTab); 
      country.DataSource = countryTab; 
      country.DataTextField = "CountryName"; 
      country.DataValueField = "CountryID"; 
      country.DataBind(); 
      country.Items.Insert(0, new ListItem("--SELECT--", "-1")); 
 
} 

但是当我将“--SELECT--”设置为两个 dropDownList 时,maritalStatus dropDownList 工作正常;但是,国家/地区下拉列表显示此错误

"'country' has a SelectedValue which is invalid because it does not exist in the list of items"

maritalStatus.Text = "--SELECT--"; 
country.Text = "--SELECT--"; 

如果我将国家文本设置为“-1”,它将正常工作。我不明白为什么两个 dropDownLists 的行为方式不同。

请您参考如下方法:

您的问题是您的下拉列表中没有像 --SELECT-- 这样的值,因此它们在 ListItem 集合中不匹配,因此出现异常。

根据 Dropdownlist 的文档 Text属性它:-

Gets or sets the SelectedValue property of the ListControl control.

因此,当您说 country.Text = "--SELECT--"; 时,它正在搜索 --SELECT-- 的值,它是不存在于集合中,但当您搜索 -1 时,它会找到它并且没有异常(exception)。

关于两个下拉列表的行为差异,无论您是以编程方式还是以声明方式绑定(bind)它都没有关系,两者的行为相同,您将在两种情况。