Unexpected Event Behavior

Typically, there is rarely a need to change a control’s ID. However, this practice is sometimes useful when debugging a custom control, partiularly one that contains dynamically generated controls.

When a control resides within an AJAX update panel which in turn resides in a Content control on a page that uses a master page however, changing the control ID will result in the attached event not being fired (please note, if the update panel is placed in a page directly, e.g. no master page is used, the code iluustrated below works correctly). At least this is what I have observed in AJAX extension 1.0 for Visual Studio 2005. 

The the following simple user control for example  

public partial class WebUserControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BuildControls();
    }
 
    private void BuildControls()
    {
        CheckBox cb = new CheckBox();
        cb.AutoPostBack = true;
 
        //Event will not fire if the control’s ID is changed
        //and the control is in an update panel.
        cb.ID = String.Format("{0}{1}", "MyBtn", UniqueID);
        cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
 
        this.Controls.Add(cb);
    }
 
    void cb_CheckedChanged(object sender, EventArgs e)
    {
        Label1.Text = String.Format("Check box checked: {0} <br />", (sender as CheckBox).Checked);
    }
}

When the above control (a dynamic button and a label) is embedded within a normal page (e.g. a non-AJAX page), the CheckedChanged event is fired whenever the check box is clicked. But when the same control is put into an update panel, whith the highlighted line of code included, the event will no longer fire.

This strange behavior had caused me some headaches while debugging through a rather complex web user control. So you will need to be extra careful when controls are placed in update panels. Due to limitations like the one I just mentioned a control that works in a normal page might not work properly in an AJAX enabled web page. The solution to this problem is simple, just remove the highlighted line and the event will fire again.

Be Sociable, Share!

Leave a Reply