1

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

<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

4

1 回答 1

2

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

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

dropdownlist1.DataBind()

在此之后您可以设置索引。但是如果您在绑定之前设置它会出错,因为下拉列表中没有项目。

于 2013-07-02T16:36:28.293 回答