Dynamic Controls

In this article we will see how to create Dynamic controls in .NET. Creating controls at run time and adding them to the web page.

First create a new website and add an asp panel to it.

<asp:Panel ID="Panel1" runat="server" Height="500px" Width="500px">
</asp:Panel>

In the code behind write the following code.

private TextBox t1;
private Button b1;
private Label l1;
protected void Page_Load(object sender, EventArgs e)
{
//create text box and button
t1 = new TextBox();
b1 = new Button();
b1.Text = "Click Me!!";
//here intellisense will populate the event for us if we click
on TAB.
b1.Click += new EventHandler(b1_Click);
//add the text box to the panel
Panel1.Controls.Add(t1);
//add this for formatting
Panel1.Controls.Add(new LiteralControl("<br/><br/>"));
//add the button to the panel
Panel1.Controls.Add(b1);
//add this for formatting
Panel1.Controls.Add(new LiteralControl("<br/><br/>"));

//validation label
l1 = new Label();
Panel1.Controls.Add(l1);

}
void b1_Click(object sender, EventArgs e)
{
if (t1.Text.Trim() == "")
l1.Text= "Validation failed";
else
l1.Text = "Welcome "+t1.Text.Trim();
}