2011-01-26 40 views
5

如何在OnSelectedIndexChanged觸發事件之前獲取DropDownList上的前一項?如何在OnSelectedIndexChanged觸發事件之前獲取DropDownList上的項目

例如:我有一個DropDownList,其名稱爲它的項目(「John」,「Mark」)。默認情況下,SelectedIndex是「John」。在更改索引並選擇「標記」後,將觸發事件OnSelectedIndexChanged。當我使用ddlName.SelectedIndex時,它將只返回「Mark」的索引,我想得到的索引是「John」的索引。

回答

4

在更改之前無法捕獲事件,但可以輕鬆地將以前的值存儲在變量中。每次觸發SelectedIndexChanged時,都使用先前的值,然後將其設置爲新索引(在下次事件觸發時)。爲了處理這種情況,當它是一個新的選擇時(默認情況下),你可以在頁面加載時設置變量,或者允許它爲空,並提醒你這是一個新的選擇(然後你​​可以處理不過你喜歡)。

+0

感謝您的信息drharris。 – 2011-01-31 01:19:37

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; 

     } 
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> 

而且在後面的代碼(假設你的下拉列表是一個FormView)...

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(); 
.. 
    } 
相關問題