2

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

例如,我的列表 [“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”</p>

“字符串3” “字符串4”</p>

“字符串5” “字符串6”</p>

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

“字符串1” “字符串2”</p>

“字符串3” “字符串4”</p>

“String5” “一些占位符图片”</p>

4

1 回答 1

3

We can render two columns in markup. Also we have to add a placeholder that we will use in code to insert image :

<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>

Now in the code check for last item and check if it is odd. If it is, add an image inside td, append the td in placeholder:

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);
        }     
    }
}

And the code I have used for testing:

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();

    }
}

Hope it helps!

于 2013-10-06T05:08:39.447 回答