Welcome to Greg McKinley.com Sign in | Join | Help

ASP.NET Dynamic Control Postback Events

This sounds simplier in words than I have seen practiced in code.

Working with dynamically created controls that postback events can be tricky. For a lot of applications it is all about timing. On postback the dynamic control must be re-created during Page_Load so the control event can be wired up before the RaisePostDataChangeEvent/RaisePostBackEvent is called. Even if the control was orignally created in say OnPreRender. If the dynamic control is not re-created the control event will not be raised because the control does not exist yet. This kind of problem usually occurs as new controls are added to an existing page that previously did not dynamically create controls.

The example below checks the EVENT_TARGET to determine if it is a dynamic control that the page or control cares about. If so it will re-create the dynamic control and place it in a PlaceHolder that is not visible. Now the postback event will be wired up to the dynamic control. This scenario is also useful if you have a collection of dynamic controls and you only want to create the one that caused the postback.

   Protected Overrides Sub OnInit(ByVal e As System.EventArgs)

        phPostbackControlHolder = New PlaceHolder

        phPostbackControlHolder.Visible = False

        Me.Controls.Add(phPostbackControlHolder)

        MyBase.OnInit(e)

   End Sub

 

   Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)

        If (IsPostBack) Then

            Dim index As Integer

            Dim sEventTarget As String

            sEventTarget = Request(EVENT_TARGET)

 

            If (sEventTarget.IndexOf(CNTL_PREFIX, 0, sEventTarget.Length) <> -1) Then

               ctlDynamicControl = RebuildSelectedControl(sEventTarget)

 

               If (Not ctlDynamicControl Is Nothing) Then

                    phPostbackControlHolder.Controls.Add(ctlDynamicControl)

               End If

            End If

        End If

        MyBase.OnLoad(e)

   End Sub

Published 29-09-2006 09:45 by gmckinley

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

What do you think?

(required) 
(optional)
(required) 
captcha Image