Many times user faces this situation: A dropdown with some values. User selected a value and SelectdIndexChanged event fires.
In the code block, one can get the current index value of dropdown but what if old value is required. that is value before selecting the new index.
The simple solution is to use viewstate to hold the old value:
Suppose we have a dropdown 'dropdown1' with some item values.
Steps:
1.In code behind, we defined a public property IndexVal that store and fetch dropdown index value from a viewstate variable:
public int IndexVal {
get
{
return Convert.ToInt32(ViewState["OldSelectedIndex"]);
}
set {
ViewState["OldSelectedIndex"] = DropDownList1.SelectedIndex;
}
}
2. When the page loads for 1st time, set the viewstate value to dropdown index value
if (!IsPostBack)
IndexVal = DropDownList1.SelectedIndex;
3. When SelectedIndexChanged event fires, we can get the old index value from viewstate and new index value from the dropdown itself.
Then set the viewstate with new value.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int oldValue IndexVal;
int newValue DropDownList1.SelectedIndex;
IndexVal = DropDownList1.SelectedIndex;
}
Varun Sharma
No comments:
Post a Comment