views:

1812

answers:

3

ASP.NET, C#

As the title suggests I was wondering if anyone knew how to programatically (c# code behind file) add a div to another a container div (in the aspx page).

Thanks in advance

+1  A: 

Use asp:Panel, which maps to a div.

Otávio Décio
+2  A: 
Panel myChildPanel = new Panel();
myContainerPanel.Controls.Add(myChildPanel);
Matthew Vines
+2  A: 

Aside from using a Panel like ocdecio suggested, there are several other possibilities.

  • You can use an asp:Literal control inside the div and fill that with pregenerated HTML
  • Add a runat="server" to the div itself and access it as a HtmlGenericControl, adding other controls to it from your codebehind.
  • Using <%= ... %>

It depends a little on the level of control you need. Still, under a most circumstances, a Panel that starts out invisible would be best:

<div>    
<asp:Panel Visible="false" id="MyPanel" runat="server">
</asp:Panel>
</div>

Then change the visibility from your codebehind when needed.

One cases where you might want to use one of the other methods is when you're stuck with some CSS file that assigns styles based on ID. In that case, using .NET controls is not really an option. But really, you should smack your designer over the head and tell him to use class names instead.

Thorarin