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);
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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 Comments

I need it to be an H4 in the actual HTML source code, though, not just there.
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?
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
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>.
I have an unknown number of h4 tags, though.
|
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 Comments

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.
Unfortunately the question was how to add dynamically.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.