Anonymous types and the ItemDataBound event

As you will probably know, when you bind a list of items to a Repeater, you can then convert the DataItem to the type of that item in the ItemDataBound event of the Repeater like this:

public class Person
{
    public string Name { get; set; }
	public string Email { get; set; }
	public int Age { get; set; }
}

public void Page_Load(object sender, EventArgs e)
{
	List<Person> people = new List<Person>
    {
        new Person { Name = "Bob", Email = "bob@example.com", Age = 28 },
        new Person { Name = "John", Email = "john@example.com", Age = 31 },
        new Person { Name = "Phil", Email = "phil@example.com", Age = 24 }
    };

    MyRepeater.ItemDataBound += new RepeaterItemEventHandler(PersonDataBound);
    MyRepeater.DataSource = people;
    MyRepeater.DataBind();
}

public void PersonDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Person p = e.Item.DataItem as Person;

        string name = p.Name;
        string email = p.Email;
        int age = p.Age;
    }
}

But what when you aren’t databinding to a list of a concrete class but to a list of an anonymous type? Well, before .NET 4.0 you had to that like this:

public void Page_Load(object sender, EventArgs e)
{
	var people = from p in DB.GetPeople()
	             select new { Name = p.Name, Age = p.Age };

    MyRepeater.ItemDataBound += new RepeaterItemEventHandler(PersonDataBound);
    MyRepeater.DataSource = people;
    MyRepeater.DataBind();
}

public void PersonDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        string name = Convert.ToString(DataBinder.Eval(e.Item.DataItem, "Name"));
        int age = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "Age"));
    }
}

Using the new .NET 4.0 dynamic type, this can be done a lot easier:

public void PersonDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
		dynamic person = e.Item.DataItem as dynamic;

        string name = person.Name;
        int age = person.Age;
    }
}

This entry was posted in Development and tagged . Bookmark the permalink.

2 Responses to Anonymous types and the ItemDataBound event

  1. Pingback: Tweets that mention Anonymous types and the ItemDataBound event | Kristof Claes -- Topsy.com

  2. Dreed says:

    Thank you