ASP.NET Repeater bind List<string>

asp.netData BindingRepeater

asp.net Problem Overview


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.

asp.net Solutions


Solution 1 - asp.net

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

Solution 2 - asp.net

Set the ItemType to System.String

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

Solution 3 - asp.net

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

in the repeater you put

<%# Eval("NAME") %>

Solution 4 - asp.net

This should work just fine:

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

Solution 5 - asp.net

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

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

Solution 6 - asp.net

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>

Solution 7 - asp.net

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjosephj1989View Question on Stackoverflow
Solution 1 - asp.netVadimView Answer on Stackoverflow
Solution 2 - asp.netKevinView Answer on Stackoverflow
Solution 3 - asp.netRobertoBrView Answer on Stackoverflow
Solution 4 - asp.netNathan AndersonView Answer on Stackoverflow
Solution 5 - asp.netKergorianView Answer on Stackoverflow
Solution 6 - asp.netJohn MView Answer on Stackoverflow
Solution 7 - asp.netAnkit KashyapView Answer on Stackoverflow