R – Help with dynamically added controls in .net

asp.netcontrolsvb.net

I'm stuck! I understand the page lifecycle and how i need to add the dynamic controls on page_init if I want to take advantage of viewstate. Also I know that I should try to avoid dynamic controls when possible. The dynamic controls are created depending on an object that is created from custom event arguments sent from a custom treeview. Problem is I need viewstate so I need to create them in page_init but I don't have the event args to create the object that tell me what controls to add until later in the lifecycle. Solution…

Private Function GetEventArgs() As npTreeViewEventArgs
    Dim control As Control = Nothing
    Dim e As npTreeViewEventArgs = Nothing
    Dim ctrlname As String = Page.Request.Params("__EVENTTARGET")
    Dim args As String = Request.Params("__EVENTARGUMENT")
    If ctrlname IsNot Nothing AndAlso ctrlname <> String.Empty Then
        control = Page.FindControl(ctrlname)
    End If
    If TypeOf control Is npTreeView AndAlso Not String.IsNullOrEmpty(args) Then
        e = New npTreeViewEventArgs(args)
    End If
    Return e
End Function

I use this in page_init to create my object and controls. This feels very dirty to me. Is there another way to handle this?

Best Answer

This is actually the most straightforward solution to this type of problem. If you can't add all the controls to the page on every postback and use visibility to control their appearance, then what you are doing there is exactly what I would recommend. (And have recommended before.)

I cringe when I see people resort to redirects, or implementing their own viewstate tracking, or doing extreme dynamic control manipulation to solve this. It may feel dirty, but it's infinitely more understandable and maintainable than the alternatives.