views:

62

answers:

2

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?

A: 

Yes. The way I did it is to overload the viewstate of the dynamic controls to store it in their parents viewstate. Also overload the reading of the dynamic controls view state. Then you can create them late in the page cycle.

Of course it is a little trickier than that... but you get the idea. (I would post code examples, but it was a prior job and don't have access to them right now.)

Hogan
+2  A: 

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.

womp