ASP.NET Repeater bind List<string>

≡放荡痞女 提交于 2019-11-26 19:26:50

问题


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.


回答1:


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




回答2:


Set the ItemType to System.string

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



回答3:


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

in the repeater you put

<%# Eval("NAME") %>



回答4:


This should work just fine:

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



回答5:


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

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



回答6:


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>



回答7:


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


来源:https://stackoverflow.com/questions/5011617/asp-net-repeater-bind-liststring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!