How to create a three column table in ASP.Net Repeater

前端 未结 6 661
无人共我
无人共我 2020-12-03 17:01

I would like to be able to use the ASP.Net Repeater control to create an HTML Table that has three columns and as many rows as necc.

For example if the Data were to

6条回答
  •  萌比男神i
    2020-12-03 18:06

    I am assuming you have all those name in 5 rows of data and you want to spread it across 3 columns in a repeater and not have 2 rows of data with 3 fields which would be straight forward. Based on my assumption your data is something like:

    DataTable (or whatever your source is):

    ID      Name
    ---------------
    1       Bob
    2       John
    3       Joe
    4       Mary
    5       Mike
    

    You can do it using a Repeater and a Literal with a little logic on the OnDataBinding event of the Literal.

    First define your Repeater:

    
        
            
            
        
            

    Next you will need a constant for the total columns you want and two global variables to track the binding operation. Define them like so:

    public partial class _YourPage : System.Web.UI.Page
    {
        private const int _repeaterTotalColumns = 3;
        private int _repeaterCount = 0;
        private int _repeaterTotalBoundItems = 0;
    

    Then you will need to implement the OnDataBinding to do all the custom work:

    protected void litItem_DataBinding(object sender, System.EventArgs e)
    {
        Literal lt = (Literal)(sender);
        _repeaterCount++;            
        if (_repeaterCount % _repeaterTotalColumns == 1)
        {
            lt.Text = "";
        }
    
        lt.Text += string.Format("{0}", Eval("Name").ToString());
    
        if (_repeaterCount == _repeaterTotalBoundItems)
        {
            // Last item so put in the extra  if required
            for (int i = 0;
                 i < (_repeaterTotalColumns - (_repeaterCount % _repeaterTotalColumns));
                 i++)
            {
                lt.Text += "";
            }
            lt.Text += "";
        }
    
        if (_repeaterCount % _repeaterTotalColumns == 0)
        {
            lt.Text += "";
        }
    }
    

    Then make sure when you bind your Repeater you are saving the total count:

     _repeaterTotalBoundItems = yourDataTable.Rows.Count;
     repeater.DataSource = yourDataTable;
     repeater.DataBind();
    

    The output produced would be:

    Bob John Joe
    Mary Mike

    You could probably improve the DataBinding code but I just rattled it off to give the basic premise of how to accomplish your goal. If the DataBinding needs to do a lot of string concat operations, you should probably switch to to using a StringBuilder and then just assign the Literal in the last operation.

提交回复
热议问题