Search code examples
data-bindingc#-4.0repeaterdatarepeater

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 repeater 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.


Solution

  • 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") %>