Can someone explain when to use each of these? They almost seem interchangeable in many cases.
The Custom Control gets added to the toolbar while the User Control (ascx) can not. The Custom Control does not get rendered in the Designer while the User Control does. Beyond that, how do you choose which is the right one to use?
Also, I am looking for the best way to access the controls from JavaScript (GetElementById). So, a point in the right direction for adding client side support would be great.
This is from Microsoft's site:
Web user controls
Web custom controls
http://msdn.microsoft.com/en-us/library/aa651710(VS.71).aspx
A UserControl has to be hosted by a web site and is associated with an ASCX file using the codebehind model. Therefore, with a user control you can define the basic markup for the control in the ASCX file, and put all the code into the ASCX.CS file.
A WebControl is just a class, and doesn't let you define an associated ASCX file; you need to override the Render function to print out any markup the control is going to produce. However, because it doesn't depend on an ASCX it can be put into a shared library. (a DLL)
To respond to your question: both Web- and UserControls have the same benefit - they take some portion of a page and encapsulate it. I use UserControls when the code in question applies to only one of my sites; if I'm using similar code in multiple sites, then I'll convert the code to a WebControl and move it into a shared library. That way when I need to update it, I make changes in one place and not 3 or 4.
Tip: you can get around some of the trouble of defining your own WebControl by inheriting from one of the standard ASP WebControls. Many standard controls like Label or Image aren't sealed - you can inherit from them and override their methods to create your own specialized version of that control. This is much easier and less error-prone than extending WebControl directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With