Which one is recommended ? Let me explain what I want to achieve !
I have one pages used by many users, every user has a different Role like admin, operator, normal use
I wouldn't do it dynamically as the gain is not worth the complexity or perceived savings. Also if you set visible = false
, keep in mind that the viewstate is still enabled for your controls. If you are worried about the back and forth data and dealing with a larger viewstate, make sure you disable the viewstate for all the controls or for a parent panel that contains them. You will have the same inconvenience for maintaining their state on postback as doing it dynamically though.
Also, doing it non-dynamically is much easier to maintain to the next guy working with the code. The layout is obvious and easier to visualize than trying to figure out what code when is putting what where.
Creating controls dynamically really doesn't gain you much at all except for the exclusion of viewstate and maybe negligable processing server side. I think you would find it difficult to even measure much of a noticable difference, even under load between, a non-viewstate control and the overhead of dynamically having to add them as needed.
Lastly, it's easier to not do it dynamically so why not take the easiest route first and see if it is a problem. If it does become an issue then refine it where necessary.
Another inconvenience with dynamic controls is the large amount of brittle code that you have to write to handle them, and the headaches with debugging them. Unless you have extremely complex controls that do time consuming things, or you've actually identified a performance problem, I would highly recommend the invisible method (and regularly do). It's the KISS principle in action (not to mention the "don't pre-optimize" principle).
What if you put controls of different roles in different panel and simply Visible/invisible whole panel
.Visible = false
is quite a reasonable approach for this. Don't concern yourself with the speed of this method until you prove, via profiling, that it is required.