Add dynamic controls to web page

Suppose your requirement is to add dynamic controls to your web page. Then do the following.
Drag & drop a lable control.
Go to the aspx.cs page & write the below code.


TextBox t1;
protected void Page_Load(object sender, EventArgs e)
{
        if(!IsPostBack)
        t1.Text = "Text Box1";
}
override protected void OnInit(EventArgs e)
{     
        t1 = new TextBox();
        t1.ID = "TextBox1";
        t1.Style["Position"] = "Absolute";
        t1.Style["Top"] = "25px";
        t1.Style["Left"] = "100px";
        form1.Controls.Add(t1);     
        this.t1.TextChanged += new System.EventHandler(this.TextBox_TextChanged);
        base.OnInit(e);
}
private void TextBox_TextChanged(object sender, System.EventArgs e)
{
        TextBox txtBoxSender = (TextBox)sender;
        string strTextBoxID = txtBoxSender.ID;

        switch (strTextBoxID)
        {
            case "TextBox1":
                Label1.Text = "TextBox1 text was changed";
                break;
        }
}

Comments