0

我有一个从 SQL 查询的结果填充的下拉框。从 dropdownlist1 中选择的值成功地填充了 lbAuthors 下拉列表。在测试期间,我意识到 dropdownlist1 中的第一条记录永远不会更新到 lbAuthors 下拉列表中。这是一个示例:如果我在第二个下拉框中有三个作者姓名(Frost、Kipling、Poe),那么名字 - Frost - 不会更新到第一个下拉框中。Kipling 或 Poe 会——但 Frost 不会。

我的问题是 - 我需要在我的事件中包含什么以允许 Frost(或任何第一条记录)更新到第一个下拉框中?——</p>

代码隐藏:

protected void update_SelectedItem(object sender, EventArgs e)
{
    lbAuthorList.Items.Clear();
    lbAuthorList.Items.Add(new ListItem(DropDownList1.SelectedItem.Text, DropDownList1.SelectedItem.Text));
    lbAuthorList.Items.FindByValue(DropDownList1.SelectedItem.Text).Selected = true;
}

标记:

<asp:DropDownList runat="server" 
                  ID="lbAuthors" 
                  style="float:left;" 
                  DataSourceID="odsAuthorList" 
                  DataTextField="DisplayAuthorName" DataValueField="AuthorID" 
                  onselectedindexchanged="lbUserList_SelectedIndexChanged" 
                  AppendDataBoundItems="True" >
</asp:DropDownList>
<asp:DropDownList ID="DropDownList1" 
                  runat="server" 
                  AppendDataBoundItems="True" 
                  DataSourceID="SqlDataSource2" 
                  DataTextField="Display_AuthorName"  
                  EnableViewState="false"
                  DataValueField="Display_AuthorName"                  
                  OnSelectedIndexChanged="update_SelectedItem" 
                  AutoPostBack="true">
</asp:DropDownList>
4

2 回答 2

1

那是因为当您选择第一项时,选择的索引不会改变。您需要像这样插入一个虚拟项目::

<asp:DropDownList ID="DropDownList1" runat="server" 
                  AppendDataBoundItems="True" 
                  DataSourceID="SqlDataSource2" 
                  DataTextField="Display_AuthorName"  
                  EnableViewState="false"
                  DataValueField="Display_AuthorName"  
                  OnSelectedIndexChanged="update_SelectedItem" 
                  AutoPostBack="true">
    <asp:ListItem Text="--Select One--" Value="-1"></asp:ListItem>
</asp:DropDownList>
于 2013-10-31T22:40:00.570 回答
0

之所以出现此问题,是因为您为下拉列表更改了代码,但最初选择的第一个值当时未触发下拉列表更改事件。如果你选择第二个,然后选择第一个,它会正常工作。

只需在下拉列表项中添加一个虚拟变量..

dropdownlist1.Items.Add("--选择--");

于 2013-11-01T11:38:27.823 回答