I want to add HTML structure and control like this from code behind into a panel
<div class='Main'>
<div class='cst'>
First Name
</div>
<div class='csc'>
<asp:Label ID="lblFirstName" CssClass="ronly" runat="server"></asp:Label>
</div>
<div class='cst'>
First Name
</div>
<div class='csc'>
<asp:Label ID="lblFirstName" CssClass="ronly" runat="server"></asp:Label>
</div> <div class='cst'>
First Name
</div>
<div class='csc'>
<asp:Label ID="lblFirstName" CssClass="ronly" runat="server"></asp:Label>
</div>
<div class='end'>
</div>
</div>
<asp:Panel runat="server" CssClass="sxpnl" ID="pnlUserdata">
</asp:Panel>
If i try to add like this
HtmlGenericControl divcontrol = new HtmlGenericControl(); divcontrol.Attributes["class"] = "sxro sx1co"; divcontrol.TagName = "div"; pnlUserSearch.Controls.Add(divcontrol); Label question = new Label(); questionDescription.Text = "text"; pnlUserSearch.Controls.Add(question);
It will add controls one after another, how can i make controls go nested like that as shown above.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
For appending HTML to your panel, add a LiteralControl control to your panel:
string yourHTMLstring = "<div class='Main'>...."; pnlUserdata.Controls.Add(new LiteralControl(yourHTMLstring));
Method 2
Don’t add that child control to the panel, add it to the control that should be the parent:
HtmlGenericControl divcontrol = new HtmlGenericControl();
divcontrol.Attributes["class"] = "sxro sx1co";
divcontrol.TagName = "div";
pnlUserSearch.Controls.Add(divcontrol);
Label question = new Label();
question.Text = "text";
divcontrol.Controls.Add(question); // add to the new div, not to the panel
Method 3
- Take one local string variable TEMP.
- Create same html as you want to display on screen and store it in variable TEMP.
- You can take html creation of control in separate function based on requirement.
- Place that created html as innerHTML to your panel/div.
That’s it…
Method 4
<div id="Div1" runat="server"> Div1.InnerText = "Text";
Method 5
Make the div runat="server"
<div id="d" runat="server"></div>
and add the controls inside div like below
d.Controls.Add();
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0