How can the child controls be created in server controls?

Platform: ASP.NET| Category: Custom Controls

Child controls can be created by overridding the CreateChildControl method as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace WebCustomControl1
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:WebCustomControl1 runat=server> </{0}:WebCustomControl1>")]
    public class WebCustomControl1 : WebControl
    {
        public TextBox txtname = new TextBox();
        public TextBox txtnum = new TextBox();
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null) ? String.Empty : s);
            }
            set
                        {
                            ViewState["Text"] = value;
                        }
                }
        protected override void CreateChildControls()
        {
            Controls.Add(new LiteralControl("Name: "));
                            Controls.Add(txtname);
            txtname.Text = "";
            txtname.ToolTip = "Enter a Username";
            txtname.Attributes.Add("autocomplete", "off");
 
            Controls.Add(new LiteralControl("</br>"));
            Controls.Add(new LiteralControl("EmpNo: "));
            this.txtnum = new TextBox();
            Controls.Add(txtnum);
            txtnum.Text = "";
 
            txtnum.ToolTip = "Enter a Username";
            txtnum.Attributes.Add("autocomplete", "off");
            Controls.Add(new LiteralControl("</br>"));
 
        }
 
        protected override void RenderContents(HtmlTextWriter writer)
        {
            this.EnsureChildControls();
            this.RenderChildren(writer);
         }
        }
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.