user2367773
user2367773

Reputation: 23

How to render two column layout using an asp.net repeater

I have a list of items I want to render using a repeater, the twist is these items need to render in two columns in a table layout. Also if there are odd number of items the last cell will contain a place holder image. any thoughts?

Ex, my list [“string1”,”string2”,”string3”,”string4”,”string5”] Display

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

So that I end up with a view that looks like this

“String1” “String2”

“String3” “String4”

“String5” “String6”

Or if the list has odd number of Items

“String1” “String2”

“String3” “String4”

“String5” “Some place holder image”

Upvotes: 2

Views: 8426

Answers (1)

afzalulh
afzalulh

Reputation: 7943

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!

Upvotes: 3

Related Questions