即使值存在,DropDownMenu.SelectedIndex也会导致错误

时间:2013-07-02 16:26:53

标签: c# asp.net

我有一个从数据库表中填充的下拉列表:

<asp:DropDownList ID="userNameDropDown" runat="server" DataSourceID="SqlDataSource1"
    DataTextField="Name" DataValueField="PK_User" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
    SelectCommand="SELECT [Name], [PK_User] FROM [User] ORDER BY [Name]">
</asp:SqlDataSource>

当我将特定行指定为默认行时,它可以正常工作:

userNameDropDown.SelectedIndex = 3;

但是,当我使用此下拉列表时:

    <asp:DropDownList ID="catagoryDropDownListEdit" runat="server" DataSourceID="SqlDataSource5"
        DataTextField="Catagory" DataValueField="PK_SupportCatagory">
    </asp:DropDownList>
    <asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
        SelectCommand="SELECT [PK_SupportCatagory], [Catagory] FROM [SupportCatagory]">
    </asp:SqlDataSource>

尝试:

catagoryDropDownListEdit.SelectedIndex = 1;

我收到此错误:

'catagoryDropDownListEdit' has a SelectedIndex which is invalid because it does not exist in the list of items.
Parameter name: value

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentOutOfRangeException: 'catagoryDropDownListEdit' has a SelectedIndex which is invalid because it does not exist in the list of items.
Parameter name: value

这是一张显示有实际值的图片:

http://i.stack.imgur.com/akNaf.png

1 个答案:

答案 0 :(得分:2)

  

DataBinding在控件的PreRender事件发生后引发   在页面的PreRender事件之后。 (这适用于其控件   DataSourceID属性以声明方式设置。否则事件   当你调用控件的DataBind方法时会发生。)

因此,要在页面加载时设置下拉列表的选定inedex,您必须像这样调用DataBind()方法...

dropdownlist1.DataBind()

在此之后你可以设置index.But如果你在绑定之前设置它会给出错误,因为dropdownlist中没有项目。

相关问题