简体   繁体   中英

Using the ASP.NET Repeater Control with List<T> object data

I have an ASP.NET web app that places several string data into an object as properties. The string data is sourced from a JSON feed from Twitter. A collection of my TwitterMessages is held in a Generic List.

What I want to do is use an asp:repeater to iterate through my List<T> to display all of the contents of the objects it holds, by using <%# Eval("MyURL") %> . MyURL is the name of a property inside my TwitterMessage object.

In a previous question I was advised to use the asp:Repeater template to display my data in a custom HTML table. So being able to use a template somehow or other, is really what I'm interested in.

Where I am struggling is in working out how to perform a databind to the Repeater so I can reference my object data in the .aspx page.

I am aware that I need to use the ItemDataBound method in order to make a data-bound event so that I can reference the property names in my string data object.

Hope that's enough info for some much appreciated help! :)

It's pretty straightforward to databind to your repeater. Depending on where your list object resides, you can either bind your repeater using markup, or codebehind.

If you want to do it in markup, you should make an ObjectDataSource wrapper around the List. Something like this:

<asp:Repeater ID="rpt" runat="server" DataSourceID="twitterFeedSource" >
<ItemTemplate>
<tr><td><%# Eval("MyURL") %></td></tr>
</ItemTemplate>
</asp:Repeater>

<asp:ObjectDataSource ID="twitterFeedSource" runat="server"
  SelectMethod="GetTheListOfTwitterFeedObjects"
  TypeName="myTwitterFeedClass"
>
</asp:ObjectDataSource>

The GetTheListOfTwitterFeedObjects method should return the list of objects. Each object would need to have the property MyURL . You can of course extend your template and bind to any other properties that your twitter objects have.

Otherwise, you can do it straight from the code. Simply do something like this in Page_Load:

if (!IsPostBack)
{
    myRepeater.DataSource = myGenericList;
    myRepeater.DataBind();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM