First, the implementation of the custom Control inherits the Control to add custom properties, and then rewrite the Render method. This method is used to output the Control code. Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Linq;
Using System. Text;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Namespace OwnControl
{
Public class NameControl: Control
{
Private string name;
Private bool isImport;
Public string Name
{
Get
{
Return name;
}
Set
{
Name = value;
}
}
Public bool IsImport
{
Get
{
Return isImport;
}
Set
{
IsImport = value;
}
}
Protected override void Render (HtmlTextWriter writer)
{
String txt;
If (isImport)
Txt = string. Format ("Else
Txt = string. Format ("Writer. Write (txt );
}
}
}
Write the above files to a separate class project and compile them. Add a reference to the project in a web project.
Then use this control on the asp.net page.
Registration control: <% @ Register Namespace = "OwnControl" TagPrefix = "useown" Assembly = "OwnControl" %>
Control: <useown: NameControl ID = "use1" runat = "server" Name = "yijianliang" IsImport = "true"> </useown: NameControl>
Code <% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "UseOwnControlForm. aspx. cs" Inherits = "TestCodeBehind. UseOwnControlForm" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<% @ Register Namespace = "OwnControl" TagPrefix = "useown" Assembly = "OwnControl" %>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> No title page </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Useown: NameControl ID = "use1" runat = "server" Name = "yijianliang" IsImport = "true"> </useown: NameControl>
<Useown: NameControl ID = "user2" runat = "server" Name = "yijianxiang" IsImport = "false"> </useown: NameControl>
</Div>
</Form>
</Body>
</Html>