【问题标题】:How to render two column layout using an asp.net repeater如何使用 asp.net 中继器呈现两列布局
【发布时间】:2013-10-05 17:59:06
【问题描述】:

我有一个我想使用转发器呈现的项目列表,不同之处在于这些项目需要在表格布局的两列中呈现。此外,如果有奇数个项目,最后一个单元格将包含一个占位符图像。有什么想法吗?

例如,我的列表 [“string1”,”string2”,”string3”,”string4”,”string5”] 显示

<table>
 <tr>
    <td>string1</td> 
    <td>string2</td>
 </tr>
 <tr>
<td>string3</td> 
    <td>string4</td>
 </tr>
 <tr>
<td>string5</td> 
    <td>string6</td>  or [<td>Some place holder Imge if odd number </td>]
  </tr>
</table>

所以我最终得到一个看起来像这样的视图

“字符串1”“字符串2”

“字符串3”“字符串4”

“字符串 5”“字符串 6”

或者如果列表有奇数个项目

“字符串1”“字符串2”

“字符串3”“字符串4”

“String5”“一些占位符图像”

【问题讨论】:

    标签: asp.net repeater


    【解决方案1】:

    我们可以在标记中呈现两列。我们还必须添加一个占位符,我们将在代码中使用它来插入图像:

    <asp:Repeater ID="rptMyRepeater" runat="server" OnItemDataBound="rptMyRepeater_ItemDataBound">
        <HeaderTemplate>
            <table>  
             <tr>     
        </HeaderTemplate>
        <ItemTemplate>
                <%# (Container.ItemIndex != 0 && Container.ItemIndex % 2 == 0) ? @"</tr><tr>" : string.Empty %> 
                <%# string.Format("{0}{1}{2}", @"<td>", Container.DataItem, @"</td>") %>
            <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        </ItemTemplate>
        <FooterTemplate>
            </tr>
            </table>
        </FooterTemplate>
    </asp:Repeater>
    

    现在在代码中检查最后一项并检查它是否为奇数。如果是,则在 td 中添加图像,将 td 附加到占位符中:

    protected void rptMyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            int count = ((List<string>)rptMyRepeater.DataSource).Count;
            if (e.Item.ItemIndex != 0 && e.Item.ItemIndex % 2 == 0 && e.Item.ItemIndex == count - 1)
            {
                PlaceHolder PlaceHolder1 = e.Item.FindControl("PlaceHolder1") as PlaceHolder;
                Image img = new Image();
                img.ImageUrl="pholder.jpg";
                TableCell td = new TableCell();
                td.Controls.Add(img);
                PlaceHolder1.Controls.Add(td);
            }     
        }
    }
    

    还有我用来测试的代码:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //rptMyRepeater.DataSource = new List<String>() { "String1", "String2", "String3", "String4", "String5", "String6" };
            rptMyRepeater.DataSource = new List<String>() { "String1", "String2", "String3", "String4", "String5" };
            rptMyRepeater.DataBind();
    
        }
    }
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-13
      • 2018-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      相关资源
      最近更新 更多