Creating server controls in Asp.net is the same as Windows Form controls. There are several ways:
1. User control
2. Custom controls derived from Control and WebControl
3. Expand from existing Asp.net server controls
User controls have .ascx extension and are saved as text files. User controls do not need to be precompiled like server controls derived from Control and WebControl. When user controls are used in .aspx pages, the page parser starts from . A class is dynamically generated from an aspx file and compiled into an assembly. Its advantages are: it solves code reuse, and each user control has its own object model, and its writing language has nothing to do with the language of the .aspx page.
Expanding from the existing Asp.net server control, it mainly enhances the functions of the .net native server control to meet the needs of our development and end users.
Custom controls derived from Control and WebControl are deployed in the form of compiled class libraries.
The above 1 and 3 will not be explained in this series. In this series, only the server controls derived from Control and WebControl will be explained.
If we want to write a custom control, we only need to inherit from Control and WebControl. Control has implemented the IComponent interface, and WebControl itself is derived from Control, so they also support the visual design of components.
Render method and HtmlTextWriter class. When we derive an Asp.net server control from a Control class, the Control class provides us with an overloadable Render and an instance of the HtmlTextWriter type. The Render method is to send the server control content to the provided HtmlTextWriter object, and HtmlTextWriter encapsulates the function of writing HTML text stream.
using System; using System.Collections.Generic; using System.Text;
namespace ClassLibrary1 { public class Control1 : System.Web.UI.Control { protected override void Render(System.Web.UI.HtmlTextWriter writer) { writer.Write("I'm here."); } }
public class Control2 : System.Web.UI.WebControls.WebControl { protected override void Render(System.Web.UI.HtmlTextWriter writer) { writer.Write("I'm here too."); } } } |
In the above code, we define a Control1 and Control2, which inherit from Control and WebControl respectively. So what are the essential differences between them? First look at the following effect:
From the above effects, it is not difficult to see the difference between them. The WebControl class provides support for styles through attributes, such as font, height, background color, etc. So when do we choose to derive from Control, and when do we choose to derive from WebControl? If the control wants to generate non-visual elements or display to non-HTML clients, it will be derived from Control, such as SqlDataSource; if it is to provide the client with visual HTML, then we will derive from WebControl, such as TextBox.