Binding List<MyObject> to a repeater
I have a complicated class which is something like:
public class Person
{
public int Pid;
IList<Address> Addressess;
public Name Name;
public Name PartnerName;
Person(int id)
{
Addressess = new List<Address>();
}
}
public class Address
{
public string HouseName;
public string street;
public string country;
public string universe;
public string galaxy;
}
public class Name
{
public string Firstname;
public string Lastname;
public string Fullname { get { return Firstname + " " + Lastname; } }
}
So, now, when I bind the repe开发者_JAVA百科ater like so:
rpPeople.DataSource = PeopleNearYou; //this is a List<Person>();
and in the actual repeater, I want to show the details. To access, say, Pid
, all I need to do is:
<%# Eval("Pid") %>
Now, I can't figure out how to access the full name in repeater
<%# Eval("Fullname") %> //error, fullname not found
Also, I want to display only First Address only and I can't do that
<%# Eval("Address").First().Universe %> //red, glarring error. can't figure out how
So, how would I display these stuff please?
Many thanks.
This will be so much easier if you grab required class members when you bind the repeater.
rpPeople.DataSource = PeopleNearYou.Select(r => new
{
Pid = r.Pid,
Universe = r.Addressess.First().Universe,
Fullname = r.Name.Fullname
}
Now all you need to do in your repeater is:
<%# Eval("Universe") %>
<%# Eval("Fullname") %>
If I get in to complicated situations like this I always use the ItemDataBound event as you can get much more control. For example, in your situation I would create a label in the item template, bind the ItemDataBound to code similar to this...
void rpt1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
((Label)e.Item.FindControl("lblFullName")).Text = ((Person)e.Item.DataItem).FullName;
}
You'll need a check on e.Item.Type too if you have header/footer rows.
精彩评论