Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would you use a Web User Control over a Web Custom Control?

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.

like image 850
Mike Avatar asked Sep 22 '08 17:09

Mike


2 Answers

This is from Microsoft's site:

Web user controls

  • Easier to create
  • Limited support for consumers who use a visual design tool
  • A separate copy of the control is required in each application
  • Cannot be added to the Toolbox in Visual Studio
  • Good for static layout

Web custom controls

  • Harder to create
  • Full visual design tool support for consumers
  • Only a single copy of the control is required, in the global assembly cache
  • Can be added to the Toolbox in Visual Studio
  • Good for dynamic layout

http://msdn.microsoft.com/en-us/library/aa651710(VS.71).aspx

like image 68
AaronS Avatar answered Nov 02 '22 23:11

AaronS


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.

like image 36
The Digital Gabeg Avatar answered Nov 02 '22 21:11

The Digital Gabeg