To convert a asp.net user control to a custom control

Source: Internet
Author: User
Tags rar


Author: Kevin Cheng (Cheng Jianhe)
Last modified: 2006-03-14
Overview: How to migrate a ASP.net user control to a asp.net custom control
Keywords: asp.net, user controls, custom controls
This article applies to readers:
-Familiar with the ASPNET, can create the Ascx user control
-Readers who want to create a custom control and fear for its complex implementation
Related downloads:
-The ascx control routines used in this article: WebFtp060308 (pm06). rar
-Custom control routines used in this article: Webftpcontrol 1.0.2259_source.rar
Term statement:
Field class member variable
Property class Properties
Attribute class characteristics
NameSpace namespaces
Assembly Assembly

Introduction:
asp.net custom controls are quite handy to use, but relative to an ascx user control, writing is difficult because it does not have visual programming support.
Is there a simple way? You can use both the advantages of ascx visual programming and the ease with which custom controls can be used.
This article describes a solution: first design the ascx control, and then into the user control. The following are concrete steps.


First, create the Ascx control and debug the pass

Specifically how to create an Ascx user control is not the focus of this article, skip the ~
The ascx routines used in this article can be downloaded by clicking here. This routine creates a Web file-managed ascx control. Effects such as:

second, transfer ascx to a custom control

(a) New project ASPNET custom control project, copy all CS code from the original Ascx class to the custom control class
(ii) Modify the InitializeComponent () function to initialize the control. It can be extended to three small functions, such as private void InitializeComponent ()
{
Createcomponent ();
Setcomponentproperty ();
Setcomponentevent ();
}
which
(1) the createcomponent () function is used to create all the controls that are used and to organize their hierarchical relationships.
private void Createcomponent ()
{
Create
Lblcurrpath = new Label ();
Lblupload = new Label ();
Lblnewfolder = new Label ();


Nest
Controls.Add (this. lblcurrpath);
Controls.Add (New HtmlGenericControl ("BR"));
this. PANADMIN.CONTROLS.ADD (this. file);

}
(2) the Setcomponentproperty () function is used to set properties for these controls, such as
private void Setcomponentproperty ()
{
LblCurrPath.Font.Size = Fontunit.xlarge;
Lblcurrpath.cssclass = "Webftp_title";
Paninfo.backcolor = Color.yellow;
Paninfo.visible = false;

}
It is noteworthy that the combination-bound controls provided by ASPNET (such as the DataGrid, DataList ...) The property settings are more complex, see appendix II
(3) The event handle of the control is set in the Setcomponentevent () function, which is copied from the original InitializeComponent function, as
private void Setcomponentevent ()
{
this. Btnupload.click + + = new System.EventHandler (this. btnupload_click);
this. Btnnewfolder.click + + = new System.EventHandler (this. btnnewfolder_click);
this. DG. ItemCommand + = new System.Web.UI.WebControls.DataGridCommandEventHandler (this. dg_itemcommand);
this. Load + = new System.EventHandler (this. Page_Load);

}


(iii) Fill the render () function to render the output effect. It can be extended to two small functions, such as protected override void Render (HtmlTextWriter output)
{
Renderclientscript (output);
Renderservercomponent (output);
}
which
(1) The Renderclientscript function can be used to output client script, as well as the Stylesheet style style code, such as:
private void Renderclientscript (HtmlTextWriter output)
{
Output.  Write ("<style>{0} {1}</style>", "A {text-decoration:none}", "A:hover {text-decoration:underline } " );

}
(2) The Renderservercomponent function is used to output individual controls, or you can add some output of ordinary HTML code here, such as
private void Renderservercomponent (HtmlTextWriter output)
{
this. Lblcurrpath.rendercontrol (output);
Output. Write ("this. Panadmin.rendercontrol (output);
this. DG. RenderControl (output);
}


(iv) Let class implement INamingContainer interface to avoid situations where multiple controls are placed on a page that cause child control ID conflicts
The interface does not have any functions, just declare the implementation, such as public class WebFtp:System.Web.UI.WebControls.WebControl, INamingContainer

As long as the class implements the interface, the system will automatically implement a method to avoid the ID conflict
The specific step is to enclose the ID of the parent control in front of the internal control ID name. If there is a lable (id=lblname) in the Panel (Id=pan), then the ID of the label is automatically changed to Pan_lblname;
At this point, when compilation debugging succeeds, the control is ready for use. Plus the picture, the effect can be this:

III. Business Standardization custom Controls

When the second step is complete, the control is already available (how to use it). Halo, see appendix V), but it is still a coarse embryo, such as no control icon, no design-time appearance, etc.
The following describes how to modify the control to resemble a standardized commercial control.
(1) Add attribute attributes such as category, description, default value for the properties of a control
These attributes affect the contents of the control in the Properties toolbar
Format such as: [Bindable (true), Category ("category"), Description ("Descriptive Information"), DefaultValue ("Default string Type value")]
Commonly used attributes are: CategoryAttribute attribute category
BrowsableAttribute property can display
Default properties for Defaultpropertyattribute controls
Default value for DefaultValueAttribute property
Description information for the DescriptionAttribute property
Whether the ReadOnlyAttribute property is read-only
Whether the Bindableattribute property can be bound
NotifyParentPropertyAttribute whether the control is notified when the property is modified

More attribute please refer to Appendix III, appendix IV, and System.ComponentModel namespaces
(2) Add toolbar icon
Add attributes for class: [ToolboxBitmap (typeof (Webftp), "Kingsoc.Web.Controls.WebFtp.bmp")]
One of the things to note is:
-The default namespace for the project is Kingsoc.Web.Controls
-The picture name is webftp.bmp and you need to set its compilation options to "Embedded Resources"
So the icon on the toolbar becomes like this:
(3) Add design-time appearance support
To add an attribute to a class: [Designer (typeof (Kingsoc.Web.Controls.WebFtpDesigner))]
Where the class Kingsoc.Web.Controls.WebFtpDesigner inherits to ControlDesigner, which is used to draw a design-time control appearance, such as:
Using System;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.ComponentModel;
Using System.ComponentModel.Design;
Using System.Web.UI.Design;
Using System.Text;
Namespace Kingsoc.Web.Controls
{
public class Webftpdesigner:controldesigner
{
public override string GetDesignTimeHtml ()
{
Return base. GetDesignTimeHtml ();
WebControl Ctrl = (WebControl) this. Component;
StringBuilder sb = new StringBuilder ();
Sb. AppendFormat (
"<label style= ' align:center; Valign:middle; Font-size:small; font-family:arial; Background-color: #eeeeee; padding:2px; border:2px dotted gray; WIDTH:{0}; Height:{1}; ' ><center>{2}</center></lable> ",
Ctrl. Width,
Ctrl. Height,
Ctrl.id);
Return SB. ToString ();
}

public override bool Allowresize
{
get {return true;}
}
}
}

         So, design-time controls have appearance support:.
         (too shabby.) I use Dreamweaver and other design tools design, want to look more good-looking. Copy the HTML code to the GetDesignTimeHtml () function ()
     (4) Add TagPrefix
         specifies that the control name prefix (which is actually an alias for the namespace to which the control belongs) is automatically generated by dragging and dropping controls from the toolbar to the form
         Add in AssemblyInfo.cs file: [Assembly:tagprefix ("Kingsoc.Web.Controls", "KS")]
         So, the Web form that you added the control automatically generates similar code <% @ register tagprefix = "KS"  namespace = "kingsoc.we B.controls " assembly = Kingsoc.Web.Controls.WebFtp"  %>
< ks:webftp  id = "WEBFTP"  ru NAT = "Server" ></ks:webftp >

(5) Set up copyright information
Modify the following attributes in the AssemblyInfo.cs file [Assembly:assemblytitle ("")]
[Assembly:assemblydescription ("")]
[Assembly:assemblyconfiguration ("")]
[Assembly:assemblycompany ("Kingsoc software")]
[Assembly:assemblyproduct ("")]
[Assembly:assemblycopyright ("")]
[Assembly:assemblytrademark ("Kingsoc")]
[Assembly:assemblyculture ("")]

(6) Add the control to the GAC. See annex V
(7) Add control registration protection. See annex VI


--------------------------------------------------------------------
Appendix
--------------------------------------------------------------------
Appendix I: Selection of a custom control base class
Control the base class for all Web controls
WebControl inherits to the control class and adds attributes such as width,height, which are commonly used and default base classes, often used with appearance controls
Component is often used for controls that do not have skins, such as: Data access controls
Therefore, for composite controls, WebControl is generally used as the base class. And for the control without interface, the general use of component can be

Appendix II: Creating a DataGrid bound column in code
(1) Normal bound column BoundColumn col = new BoundColumn ();
Col. DataField = "name";
Col. ReadOnly =

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.