Friday, July 11, 2008

ASP: Inserting ASP tags from code behind files

Put a PlaceHolder object in your ASPX file like this:
<asp:PlaceHolder id="ph1" runat="server"/>

Then, from your code file insert dynamically the ASP tags like this:
TextBox tb = new TextBox();
tb.Text = "...some text...";
ph1.Controls.Add(tb);


This will add the <asp:textBox> control to the ASP file.

You can also add HTML tags using the HtmlXXX classes like this:
HtmlImage img = new HtmlImage();
img.Src = "./img123.jpg";
ph1.Controls.Add(img);


or like this:
HtmlGenericControl gc = new HtmlGenericControl("a");
gc.Attributes.Add("href", "http://www.hp.com");
gc.InnerText = "Hewlet Packard";
ph1.Controls.Add(gc);


Sometimes, you will need to add a HTML tag literally. For example, you may wish to add the <br/>. However, the following code:
HtmlGenericControl gc = new HtmlGenericControl("br");
would generate:
<br> </br>

So - instead, you should use the LiteralControl class like this:
ph1.Controls.Add(new LiteralControl("<br/>"));

No comments: