josephj1989
josephj1989

Reputation: 9709

ASP.NET Repeater bind List<string>

I am binding a List<string> to a Repeater control. Now I want to use the Eval function to display the contents in ItemTemplate like

<%# Eval("NAME") %>.  

But I am not sure what I should use instead of NAME.

Upvotes: 107

Views: 94161

Answers (7)

Kevin
Kevin

Reputation: 301

Set the ItemType to System.String

<asp:Repeater ItemType="System.String" runat="server">
    <ItemTemplate>
        <%# Item %>
    </ItemTemplate>
</asp:Repeater>

Upvotes: 28

Kai
Kai

Reputation: 145

you have to use the databind syntax here or it will not work.

<%# this.GetDataItem().ToString() %>

Upvotes: 3

Ankit Kashyap
Ankit Kashyap

Reputation: 79

Inside Item Template

     <ItemTemplate>
 <asp:Label ID="lblName"  runat="server" Text='<%# Eval("YourEntityName").ToString() ==""? "NA" : Eval("YourEntityName").ToString()%>'></asp:Label>
    <ItemTemplate>

or Simply Add inside Item Template

<%# Eval("YourEntityName").ToString() ==""? "NA" : Eval("YourEntityName").ToString()%>

Upvotes: 0

Vadim
Vadim

Reputation: 17957

Just use <%# Container.DataItem.ToString() %>

If you are worried about null values you may want to refactor to this (.NET 6+)

<asp:Repeater ID="repeater" runat="server">
    <ItemTemplate>
        <%# Container.DataItem?.ToString() ?? string.Empty%>
    </ItemTemplate>
</asp:Repeater>

Note if you are using less than .NET 6 you cannot use the null-conditional operator Container.DataItem?.ToString()

Upvotes: 221

John M
John M

Reputation: 14668

A more complete example based on the LINQ provided by @RobertoBr:

In code behind:

List<string> notes = new List<string>();
notes.Add("Value1")
notes.Add("Value2")

repeaterControl1.DataSource = from c in notes select new {NAME = c};
repeaterControl1.DataBind();

On page:

   <asp:Repeater ID="repeaterControl1" runat="server" >
    <ItemTemplate>
        <li><%# Eval("NAME")  %></li>
    </ItemTemplate>
    </asp:Repeater>

Upvotes: 4

RobertoBr
RobertoBr

Reputation: 1801

rptSample.DataSource = from c in lstSample select new { NAME = c };

in the repeater you put

<%# Eval("NAME") %>

Upvotes: 10

Nathan Anderson
Nathan Anderson

Reputation: 6878

This should work just fine:

<ItemTemplate>
   <%=this.GetDataItem().ToString() %>
</ItemTemplate>

Upvotes: 9

Related Questions