How to generate dynamic labels and use the column name and value as the text

前端 未结 1 708
既然无缘
既然无缘 2020-12-19 23:52

Is there any way, if it is possible to dynamically generate the ASP.net page from code-behind.

Example:

ASP.net:

相关标签:
1条回答
  • 2020-12-20 00:06

    You could try binding the repeater to the Datatable ColumnCollection:

    private DataTable _dataTable;
    
    public void LoadRepeater()
    {
        //load dataset
        _dataTable = myDataSet.Tables[0];
        repeater.DataSource = _dataTable.Columns;
        repeater.DataBind();
    }
    
    public string GetColumnValue(string columnName)
    {
        return _dataTable.Rows[0][columnName].ToString();
    }
    

    Then on the repeater:

    <ItemTemplate>
       <div class="hidOverflow smallPad">
            <div class="setFloatL halfWidth vertAlignT">
                <span class="profileLabel"><%# Eval("ColumnName") %></span>
            </div>
            <div class="setFloatL vertAlignT">
                <asp:Label ID="lbl2" ClientIDMode="Static" runat="server" Text='<%# GetColumnValue(Eval("ColumnName")) %>'></asp:Label>
            </div>
      </div>
    </ItemTemplate>
    

    This will only work if you have a single row on your DataTable though.

    If you have more Rows, you may have to include an additional repeater for the row dimension.

    ------------------------------------------------------------------

    To Split the columns, you could do something like this (untested):

    private void LoadRepeater()
    {
        //load dataset
        _dataTable = myDataSet.Tables[0];
        int columnCount = _dataTable.Columns.Count;
        int half = (int)columnCount/2;
    
        var columnCollection = _dataTable.Columns.OfType<DataColumn>();
        var firstHalfColumns = columnCollection.Take(half);
        var secondHalfColumns = columnCollection.Skip(half);
    
        repeater1.DataSource = firstHalfColumns;
        repeater1.DataBind();
    
        repeater2.DataSource = secondHalfColumns;
        repeater2.DataBind();
    }
    
    0 讨论(0)
提交回复
热议问题