如何构建自定义控件

public class SubHeader : WebControl   //一定要继承于WebControl且为public类
    {
    
// The URL to navigate to in case the user is not registered
        private string _register = string.Empty;

        
public SubHeader()   //在构造函数中定义其大小及样式
        {
            
// Initialize default values
            this.Width = new Unit(100, UnitType.Percentage);
            
this.CssClass = "SubHeader";
        }


        
// Property to allow the user to define the URL for the registration page
        public string RegisterUrl
        
{
            
get return _register; }
            
set { _register = value; }
        }


        
// This method is called when the control is being built
        
//重写CreateChildControls方法,从而在此控件内添加其他控件,这样可封装在一起
        protected override void CreateChildControls()
        
{
            
// Clear any previously loaded controls一定要先清除自定义控件内的所有控件后,才能添加其他控件。
            this.Controls.Clear();
            Label lbl;
            HyperLink reg 
= new HyperLink();

            
if (_register == string.Empty)
            
{
                reg.NavigateUrl 
= Context.Request.ApplicationPath + 
                    Path.AltDirectorySeparatorChar 
+ "Secure" + 
                    Path.AltDirectorySeparatorChar 
+ "NewUser.aspx";
            }
 
            
else
            
{
                reg.NavigateUrl 
= _register;
            }


            
if (Context.User.Identity.IsAuthenticated)
            
{
                reg.Text 
= "Edit my profile";
                reg.ToolTip 
= "Modify your personal information";
                HyperLink signout 
= new HyperLink();
                signout.NavigateUrl 
= Context.Request.ApplicationPath + 
                    Path.AltDirectorySeparatorChar 
+ "Logout.aspx";
                signout.Text 
= "Logout";
                signout.ToolTip 
= "Leave the application";
                
this.Controls.Add(new LiteralControl(" | "));
                
this.Controls.Add(signout);
            }

            
else 
                reg.Text 
= "Register";

            
this.Controls.AddAt(0, reg);

            
// Add it before the logout control if it was added 
            this.Controls.AddAt(0, reg);
            
this.Controls.Add(new LiteralControl(" - "));

            
// Add a label with the current data
            lbl = new Label();
            lbl.Text 
= DateTime.Now.ToLongDateString();
            
this.Controls.Add(lbl);
        }

    }

原文地址:https://www.cnblogs.com/ahuang1118/p/172569.html