How would I get the previous item on DropDownList
before OnSelectedIndexChanged
fires the event?
Example: I had a DropDownList
that has names as its items ("John", "Mark"). By default the SelectedIndex
is "John". Upon changing its index and selecting "Mark" the event OnSelectedIndexChanged
will be triggered. When I use ddlName.SelectedIndex
it will return only the index for "Mark" which I want to get is the index of "John".
You can't capture an event prior to the change, but you could easily store the previous value in a variable. Each time SelectedIndexChanged is fired, use the previous value and then set it to the new index (for the next time the event fires). To handle the case when it's a new selection (from the default), you can either set the variable when the page loads, or allow it to be null and have that alert you to the fact it's a new selection (which you can then handle however you like).
<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 file code here:
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;
}
You could use the e.OldValues
property.
<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>
And in code behind (assuming your dropdownlist is in a 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();
..
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With