Saturday, March 24, 2012

Triggering Dynamic Controls

Hi,

I got several Textboxes which are being created dynamically.

private TextBox CreateTextBoxes(int i)
{
TextBox tb = new TextBox();
tb.Width = 30;
tb.Height = 20;
tb.CssClass = "inputfield";
tb.ID = "TextBoxID" + i.ToString();
tb.Text = i.ToString();

Microsoft.Web.UI.ControlEventTrigger trig = new Microsoft.Web.UI.ControlEventTrigger();
trig.ControlID = this.FindControl(tb.ID.ToString()).ToString();
trig.EventName = "CheckChanged";
UpdatePanel1.Triggers.Add(trig);

return tb;
}

Throws an Error at FindControl:Object reference not set to an instance of an object.

When I don't use FindControl it compiles but the Event is never triggered. The dynamic Controls are wrapped in a static UpdatePanel1 via the designer.

Is that possible at all with Atlas yet?

The problem with this code is that you never added the dynamically created text box to any control collections. FindControl() works by traversing the controls collections, and control are only rendered (unless you call RenderControl() yourself) if they appear somewhere in the control collection tree for a page.

Actually, you have no reason in the code segment above to call FindControl(), because you have the class instance local to that scope. You would only use FindControl() to retrieve a control instance where you have no local variable assigned or had no way to retrieve the instance using other means.

The reason you never see the trigger is because the control you created in the code was never attached to anything that would have ended up visible on the client. If you added the control to the collection for after this code segment, you have no guarantee that the actual control ID generated once the page is rendered would be the same as you assume in this code, since control ID's actual values depend on their placement within the naming container "tree" starting from the page down.

My suggestion would be to never do anything that assumes a consistent control ID (and UpdatePanels depend on this for handling a variety of things on the client side) with a dynamic control until you have added it to a control collection that is attached to a page already. Then all the things that need to be wired to make your triggers (or commands or events) work will work.


The textbox method is called in a foreach loop, mostly about 4-6 textboxes are being created.

Is this maybe possible with the new Dynamic UpdatePanel featured in the new Atlas build?
The new UpdatePanel in the June CTP certainly does change the dynamics of the problem you described.

No comments:

Post a Comment