下拉列表中的第一条记录不会更新其他下拉框

时间:2013-10-31 22:13:05

标签: c# asp.net

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

我的问题是 - 在我的活动中我需要包含什么才能让Frost(或者第一个记录是什么)更新到第一个下拉框? -

代码隐藏:

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>

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

此问题上升是因为您为dropdownlist编写的代码已更改但最初在此时选择的第一个值下拉列表更改了未触发的事件。如果你选择第二个,然后选择第一个它将工作正常。

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

dropdownlist1.Items.Add( “ - 选择 - ”);