Adding Html from Code Behind in Asp.net

Vinay Pratap Singh picture Vinay Pratap Singh · Dec 31, 2013 · Viewed 68.8k times · Source

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.

Answer

Yair Nevet picture Yair Nevet · Dec 31, 2013

For appending HTML to your panel, add a LiteralControl control to your panel:

string yourHTMLstring = "<div class='Main'>....";
pnlUserdata.Controls.Add(new LiteralControl(yourHTMLstring));