如何在SelectedIndexChanged触发事件之前获取DropDownList中的上一项

时间:2011-01-26 06:14:13

标签: c# .net asp.net

DropDownList发生此事件之前,如何在OnSelectedIndexChanged上获取上一项?

示例:我有DropDownList名称作为其项目(“John”,“Mark”)。默认情况下,SelectedIndex为“John”。在更改其索引并选择“标记”后,将触发事件OnSelectedIndexChanged。当我使用ddlName.SelectedIndex时,它只会返回“Mark”的索引,我想得到的是“John”的索引。

3 个答案:

答案 0 :(得分:4)

您无法在更改之前捕获事件,但可以轻松地将先前值存储在变量中。每次触发SelectedIndexChanged时,使用前一个值,然后将其设置为新索引(下次触发事件时)。要处理新选择时的情况(默认情况下),您可以在页面加载时设置变量,或者允许它为空,并提醒您它是一个新的选择(然后您可以处理它)但是你喜欢)。

答案 1 :(得分:3)

<asp:DropDownList ID="ddlName" runat="server" AutoPostBack="true" 
        onselectedindexchanged="ddlName_SelectedIndexChanged">
        <asp:ListItem Text="John" Value="1"></asp:ListItem>
        <asp:ListItem Text="Mark" Value="2"></asp:ListItem>
        <asp:ListItem Text="Jim" Value="3"></asp:ListItem>
    </asp:DropDownList>

.cs文件代码:

public static int PreviousIndex;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlName.AppendDataBoundItems = true;
                ddlName.Items.Add(new ListItem("Other", "4"));
                PreviousIndex = ddlName.SelectedIndex;
            }

        }

        protected void ddlName_SelectedIndexChanged(object sender, EventArgs e)
        {
            string GetPreviousValue = ddlName.Items[PreviousIndex].Text;
            Response.Write("This is Previously Selected Value"+ GetPreviousValue);
            //Do selected change event here.

            PreviousIndex = ddlName.SelectedIndex;

        }

答案 2 :(得分:1)

您可以使用e.OldValues属性。

<asp:DropDownList ID="esDropDownList" runat="server" DataSourceID="SqlDataSourceddlEnrolmentStatus" DataTextField="EnrolmentStatusDescription" DataValueField="EnrolmentStatusID" SelectedValue='<%# Bind("StudentEnrolmentStatus") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSourceddlEnrolmentStatus" runat="server"
ConnectionString="<%$ ConnectionStrings:ATCNTV1ConnectionString %>" SelectCommand="SELECT [EnrolmentStatusID], [EnrolmentStatusDescription] FROM [tblEnrolmentStatuses] ORDER BY [EnrolmentStatusID]">
</asp:SqlDataSource>

在后面的代码中(假设您的下拉列表在窗体视图中)...

    protected void FormView1_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
    {
..
            String msg = "This is the new value " + e.NewValues["StudentEnrolmentStatus"].ToString()+ " and this is the old value " + e.OldValues["StudentEnrolmentStatus"].ToString();
..
    }