Have you got a DropDownList control and do you want to confirm with the user that they want to actually change the value before you perform any processing within the code behind event of the DropDown? (SelectedIndexChanged)
Turns out that this is not a straight forward issue because the DropDownList does not provide us with any client-side events to latch onto. (At least not via the IDE).
Here is my solution:
I inject code in the Page_Load event for the DropDownList using the "Attributes.Add" method available on the DropDownList control object. The code displays a prompt to the user and if they answer No, then the return statement is hit. This code works because the return statement stops the code flow and hence the code-behind event does not get called. (The rest of the code in the script makes sure that the old value of the drop down is reset when the user responds No to the prompt).
example (C#):
const string message = "Are you sure you want to change the value of the drop down?";
const string onChangeScript = "var jsDdlObj = document.getElementById('ddlObjID');" +
"var curIndex = jsDdlObj .selectedIndex;" +
"if (curIndex == 0){curIndex = 1;}else{curIndex=0;}" +
"if (!confirm('" + message + "')){jsDdlObj.selectedIndex=curIndex; return;}";
ddlObj.Attributes.Add("OnChange", onChangeScript);
An important thing to note about the above code is that the DropDown has only 2 values (No,Yes). The code that resets the value uses this information to toggle between these values. If you have more values - then you need to figure out how to set the old value back. (One issue you will face is that when the OnChange event is fired - the old value is erased and what you get is only the new value - so you probably will have to store the current selected index even before the OnChange event is called - so that you have the ability to reset it to that old value.
No comments:
Post a Comment
Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.