C# asp.net dropdownlist在数据绑定后不接受文本

C# asp.net dropdownlist在数据绑定后不接受文本,c#,asp.net,C#,Asp.net,我的页面中有两个dorpdownlists。一个是数据绑定的,另一个在设计时添加了值 <asp:DropDownList ID="maritalStatus" runat="server" Width="180px"> <asp:ListItem Value="-1">--SELECT--</asp:ListItem> <asp:ListItem>Single</asp:ListItem>

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

<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>
但是当我将-SELECT-设置为两个dropDownLists时,maritalStatus dropDownList运行良好;但是,国家/地区下拉列表显示了此错误

“country”有一个SelectedValue,该值无效,因为它没有 存在于项目列表中


如果我将国家文本设置为-1,它将正常工作。我不明白为什么两个下拉列表的行为方式都不一样

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

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

获取或设置ListControl控件的SelectedValue属性

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


在两个下拉列表中显示行为差异,无论是以编程方式还是声明方式绑定,两者的行为都是相同的,并且在这两种情况下都会出现异常。

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

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

获取或设置ListControl控件的SelectedValue属性

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

关于两个下拉列表中的行为差异,无论您是以编程方式还是以声明方式绑定它,两者的行为都是相同的,在这两种情况下都会出现异常。

只需替换即可

country.Items.Insert(0, new ListItem("--SELECT--", "-1"));

这将解决问题

只需更换

country.Items.Insert(0, new ListItem("--SELECT--", "-1"));

这将解决问题

只需更换

country.Items.Insert(0, new ListItem("--SELECT--", "-1"));

替换

country.Items.Insert(0, new ListItem("--SELECT--", "-1"));


你看过这条线了吗?你看过这条线了吗?谢谢:第一次我没有得到例外。但它不起作用。现在修复了…谢谢:我没有得到第一个例外。但它不起作用。现在修复了。。。
country.Items.Insert(0, new ListItem("--SELECT--", "-1"));
country.Items.Insert(0, new ListItem("--SELECT--", "0"));