1

What is the server side control used to add an H4 to the markup from the code behind?

4 Answers 4

3
var h4 = new HtmlGenericControl("h4");
h4.InnerHtml = "Heading Text";
parentControl.Controls.Add(h4);
2

I recommend creating an HtmlGenericControl in your code-behind. The benefit of these over Literals is that they are proper HtmlControls, with the ability for you to programmatically set and modify properties such as InnerHtml, CssClass, Style etc.

HtmlGenericControl myH4 = new HtmlGenericControl("h4") 
{ 
   ID = "myH4",
   InnerHtml = "Your Heading Here" 
});
yourContainerControl.Controls.Add(myH4);
1

You could use an asp:Literal control - this just writes out the exact text that you set it to.

E.g:

Dim myLiteral as Literal = new Literal()
myLiteral.Text = "<h4>My Heading</h4>"

Then add your Literal to the page.

7
  • I need it to be an H4 in the actual HTML source code, though, not just there. Jul 25, 2011 at 13:47
  • It will write out an actual <h4> tag in the source as rendered to the browser. Do you mean that you want the <h4> tag to be in your aspx code along with your other server tags? Jul 25, 2011 at 13:50
  • In your aspx code have <asp:Literal runat="server" id="myLiteral" /> then like above use myLiteral.Text = "<h4>My Heading</h4>"; in the code behind
    – Dave
    Jul 25, 2011 at 13:53
  • If you're going to use a Literal, it would still be better to leave the <h4> in the markup. So, have the markup as <h4><asp:Literal ID="HeaderText" runat="server" /></h4>. Jul 25, 2011 at 13:53
  • I have an unknown number of h4 tags, though. Jul 25, 2011 at 13:54
1

There is nothing like a <asp:H4 /> control. However, you can add any HTML element to a page via HtmlGenericControl type in your code behind.

For example, to create it:

HtmlGenericControl headerControl = new HtmlGenericControl(HtmlTextWriterTag.H4.ToString());
headerControl.ID = "myHeader";
headerControl.InnerHtml = "Hello World";
placeHolder.Controls.Add(headerControl);

To access it from code behind later:

HtmlGenericControl headerControl = FindControl("myHeader") as HtmlGenericControl;
2
  • If you give an id and a runat="server" to an element, it should just be another property of the page object, just like a normal ASP.Net control (e.g. Label). So instead of using FindControl, you can just do this.myHeader. Jul 25, 2011 at 13:52
  • Unfortunately the question was how to add dynamically. Jul 25, 2011 at 13:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.