What is the server side control used to add an H4 to the markup from the code behind?
4 Answers
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);
Comments
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 Comments
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>.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 Comments
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.