103

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.

sll
  • 56,967
  • 21
  • 100
  • 149
josephj1989
  • 8,761
  • 9
  • 45
  • 67

7 Answers7

214

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

Matthew Lock
  • 11,495
  • 11
  • 84
  • 122
Vadim
  • 17,547
  • 4
  • 36
  • 62
26

Set the ItemType to System.String

<asp:Repeater ItemType="System.String" runat="server">
    <ItemTemplate>
        <%# Item %>
    </ItemTemplate>
</asp:Repeater>
Anders Lindén
  • 5,893
  • 4
  • 42
  • 92
Kevin
  • 281
  • 3
  • 3
10
rptSample.DataSource = from c in lstSample select new { NAME = c };

in the repeater you put

<%# Eval("NAME") %>
RobertoBr
  • 1,781
  • 12
  • 20
9

This should work just fine:

<ItemTemplate>
   <%=this.GetDataItem().ToString() %>
</ItemTemplate>
Nathan Anderson
  • 6,522
  • 23
  • 29
3

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

<%# this.GetDataItem().ToString() %>
Kergorian
  • 23
  • 1
  • 4
3

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>
John M
  • 12,652
  • 28
  • 84
  • 132
0

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()%>
Ankit Kashyap
  • 81
  • 1
  • 10