Search code examples
c#asp.netasp.net-2.0webusercontrol

Is it possible to define a one-off user control in the ASPX codebehind?


One of my big beefs with ASP.NET is that it makes it difficult to organize the controls of a page beyond excessive amounts of prefixing IDs. I have gone to great and complicated lengths in the past to try to alleviate this, but I would like a solution that is easier to implement. So, I'm wondering:

Is it possible to define a user control in the codebehind of a .aspx, and then use it in the .aspx? I'm thinking probably not... I can't get it to work.


Solution

  • No. You must create a user control in it's own .ascx file.

    Though if you wish wish to create a web control, you can define that in whichever .cs/.vb file you want. Though for the sake of your coworkers being able to find your code, I might suggest it live in it's own file anyways.

    NOTE: I would question the validity of "it difficult to organize the controls of a page beyond excessive amounts of prefixing IDs". This is what templated controls (repeater, datalist, etc) are for. They will implement INamingContainer and thus will enable you to name controls with the same name, but different scope. There's some good info here...