I am creating a gridview dynamically using Itemplate but I have run into an issue where the event handlers I create for my drop down boxes in edititem template are accumulating every time it fires.
To be more specific. When I enter edit mode and select a new item in the dropdownlist the event handler fires twice (this I know is because the event handler is updating a second dropdownlist), but if I change another dropdownlist during the same edit session or change the same dropdownlist again the new event fires then the original two fire again. Then if I make a third change I get four events and it keeps incrementing.
I am removing the orignal event handler before adding a new event handler so there shouldn;t be multiple handlers for each instance.
else if (ControlType == "DropDown")
{
var dropVals = new Dictionary<string, string>();
DropDownList field_dropbox = new DropDownList();
field_dropbox.ID = FieldName;
field_dropbox.SelectedIndexChanged -= new EventHandler(field_dropbox_SelectedIndexChanged);
field_dropbox.SelectedIndexChanged += new EventHandler(field_dropbox_SelectedIndexChanged);
field_dropbox.AutoPostBack = true;
My event handler updates another dropdown so I know why the event should fire twice but it doesn't explain why they keep firing.
protected void field_dropbox_SelectedIndexChanged(Object sender, EventArgs e)
{
string syncDrop = "";
string list = "";
var _sync = new Dictionary<string,string>();
_sync = GlobalVars._DropSync;
list = ((DropDownList)sender).ID.ToString();
if (_sync.ContainsKey(list))
{
syncDrop = _sync[list].ToString();
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
// Get the reference of the first DropDownlist that will generate this SelectedIndexChanged event
DropDownList dropdownlist1 = (DropDownList)gvr.FindControl(list);
// Get the reference of second DropDownlist in the same row.
DropDownList ddlSync = (DropDownList)gvr.FindControl(syncDrop);
if (ddlSync != null)
{
ddlSync.ClearSelection();
//ddlParagraph.Items.FindByText(dropdownlist1.SelectedItem.Value.ToString()).Selected = true;
ddlSync.Items.FindByText(dropdownlist1.SelectedValue.ToString()).Selected = true;
}
}
//new Page().Session["EventhandlerFired"] = ((DropDownList)sender).ID;
}
Is there a way to purge the eventhandler after it is fired so it does not fire if I make a subsequent change?