Search code examples
asp.nethtmluser-controlsweb-user-controls

Align dynamically loaded user controls horizontally inside HTML table cell


I have a html table which has a element with runat=server. I am loading some user controls inside it from code behind.

    <td id ="ModuleGridHolder" runat="server" rowspan="3">            
    </td>

This is the user control HTML

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ModuleGrid.ascx.cs"
    Inherits="RadTreeListTest.Controls.ModuleGrid" %>

    <table cellpadding="0px" cellspacing="0px" style="width:100%;">

    <tr>
    <td colspan="2">
        <asp:GridView ID="gvSectionCells" runat="server" Width="100%" AutoGenerateColumns= "true">
            <HeaderStyle BackColor="#9999FF" />
            <RowStyle HorizontalAlign="Center" />
        </asp:GridView>
    </td>
    <td>
        <asp:GridView ID="gvSectionTotalCells" runat="server" Width="100%" AutoGenerateColumns="false">
            <HeaderStyle BackColor="#9999FF" />
            <RowStyle HorizontalAlign="Center" />
          <Columns>
                <asp:BoundField DataField="sumRow" HeaderText="" />                                      
            </Columns>              
        </asp:GridView>
    </td>
</tr>

And this is the simplyfied version of the code which is rendering several user controls inside it.

  foreach loop
  {
      ModuleGrid mg = (ModuleGrid)LoadControl("ModuleGrid.ascx");
      ModuleGridHolder.Controls.Add(mg);
  }

The problem is all the rendered controls are loading vertically I.E. on top of each other. How do I align them horizontally inside the cell?

I have tried using float:left but it is not working?


Solution

  • Use the CssClass parameter in your code and apply to each control. This way you can centrally style each dynamic control that you load on the page:

    foreach loop
    {
        ModuleGrid mg = (ModuleGrid)LoadControl("ModuleGrid.ascx");
        mg.CssClass = "myStyle";
        ModuleGridHolder.Controls.Add(mg);
    }
    

    Once the controls are using your stylesheet class, link a stylesheet to your aspx page and use something like this:

    .myStyle
    {
       float: left;
       width: 100px;
    }
    

    If you're already doing something similar to this, I'd suggest assigning a fixed width (or percentage) to each control to see if that gets them to float to the left of each other, it could be that without a width specified the controls are just using 100% width and causing subsequent controls to "stack" vertically.

    Overall I'd avoid using a table for this entirely and just stick to DIV tags. I find them much easier to position than having to mess around with tables, columns and rows.