ASP.Net and C# Create HTML Controls Dynamically
May 14, 2008 by Ganesh Mohan
ASP.Net & C# Create HTML Controls
Dynamically
It is very easy to create HTML controls before running a Web Page. Just Drag and Drop from ToolBox or write HTML code or ASP code for that Web Page (.aspx). But people think that generating HTML controls during runtime is difficult. But it’s quite easy.
There are many methods of generating controls during runtime.
Here is the one.
First thing is that you need to add a Panel by drag and drop it from the toolbox.
After that you need to write the C# code in Page Load event or button event as follows :
Panel1.Controls.Add(new LiteralControl(“<table><tr>”));
Panel1.Controls.Add(new LiteralControl(“<td colspan=2 align=center valign=middle >”));
Panel1.Controls.Add(new LiteralControl(“<table><tr><td>”));
Panel1.Controls.Add(new LiteralControl(“<input id=’Text1′ type=’text’ value=’Ganesh Mohan’ />”));
Panel1.Controls.Add(new LiteralControl(“</td><td>”));
Panel1.Controls.Add(new LiteralControl(“<a href=http://ganeshmohan.wordpress.com>”));
Panel1.Controls.Add(new LiteralControl(“Hi This is Ganesh”));
Panel1.Controls.Add(new LiteralControl(“</a>”));
Panel1.Controls.Add(new LiteralControl(“</td></tr></table>”));
That’s it. Its all Done. Its So Simple isn’t it!
HOW TO WRITE EVENT CODE FOR DYANAMICALLY CREATED HTML CONTROL IN ASP.NET(c#)
EXPLAIN WITH SMALL EXAMPLE(CHECKBOX)
When you place a CheckBox on your Aspx Page…
In that CheckBox Properties there is events…
There is a event named “CheckedChanged”
there you need to write this code…
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
//your code
}
But… you need to make AutoPostBack Property of CheckBox to “True”.
Hope This helps you…