代码之家  ›  专栏  ›  技术社区  ›  Bullines

具有可变列数的ASP.NET表

  •  2
  • Bullines  · 技术社区  · 15 年前

    我必须显示一些表格数据,其中最多显示3列,但有时只需要1或2列。迄今为止,我已:

    <asp:FormView ID="myFormView" runat="server" DataSourceID="myXmlDataSource">
        <ItemTemplate>
            <table cellspacing="0" cellpadding="0" class="myTableStyle">
                <colgroup>
                    <col class="myCol1Style" />
                    <col class="myCol2Style" />
                    <col class="myCol3Style" />
                </colgroup>
                <thead>
                    <tr>
                        <th class="myCol1HeaderStyle">Column 1</th>
                        <th class="myCol2HeaderStyle">Column 2</th>
                        <th class="myCol3HeaderStyle">Column 3</th>
                    </tr>
                </thead>
                <tr>
                    <td>
                        <p>Column 1 data goes here</p>
                    </td>
                    <td>
                        <p>Column 2 data goes here</p>
                    </td>
                    <td>
                        <p>Column 3 data goes here</p>
                    </td>
                </tr>
            </table>
        </ItemTemplate>
    </asp:FormView>
    <asp:XmlDataSource ID="myXmlDataSource" runat="server" />
    

    列1将始终显示,但在某些情况下,我需要隐藏列2和/或3。

    处理这个问题的最佳方法是什么?

    2 回复  |  直到 15 年前
        1
  •  2
  •   womp    15 年前

    我建议使用“AutoGenerateColumns”设置为true的GridView控件,而不是FormView控件。然后将其绑定到数据源,它将始终显示与数据源相同的列数。

    如果需要根据用户事件而不是其中的数据隐藏列,那么GridView最终将为您提供对行/列的更多控制。

        2
  •  1
  •   TheVillageIdiot    15 年前

    简单的解决方案是使用GridView等,它可以从数据源自动生成列。如果不能使用它,那么如果可以使用jquery,那么我在代码中使用了一个方法。

    为第一列、第二列和第三列定义不同的类。定义三个受保护的变量或使用类数组隐藏。使用以下命令将此数组注册为javascript数组 ClientScriptManager . 然后在页面加载时,使用jquery隐藏包含数组中类的列或tds。

    C#:

    protected string SecondCol="true";
    protected string ThirdCol = "true";
    
    void BinData(){
        ////
        ////DataBinding Code
        ////
        if(!SecondColumnNeeded) SecondCol="false";
        if(!ThirdColumnNeeded) ThirdCol="false";
    }
    

    ASPX:

          <tr>
                <td>
                    <p>Column 1 data goes here</p>
                </td>
                <td class="second">
                    <p>Column 2 data goes here</p>
                </td>
                <td class="third">
                    <p>Column 3 data goes here</p>
                </td>
            </tr>     
    
     <script type="text/javascript">
     var s="<%= SecondCol %>";
     var t="<%= ThirdCol %>";
    
     $(document).ready(function(){
        if(s==="true"){
            $("td.second").hide();//or remove
        }
        //similarly remove third column and column headers also
     });
     </script>
    

    希望这对你有帮助:)