Last listened to The Ricky Gervais Show 2002-02-09 by Ricky Gervais, Stephen Merchant & Karl Pilkington (on 25 Aug 2010, 16:00)

DataBinding with Anonymous Types in C#

I wanted to use an ASP.NET repeater to bind some data to a web form, but the data in the code came from two different places. I used LINQ to join my two data collections together, but the problem was that this resulted in my query returning an IEnumerable of anonymous types. I thought that this would mean I'm not going to be able to bind these anonymous type objects to my repeater without creating a strongly typed class or struct.

It turns out that I was wrong: I can bind anonymous types to a repeater! That's pretty cool, and I'll show you how I did it. My LINQ query looked like this:

Customer[] customers = GetCustomers();
Country[] countries = GetCountries();

var query = from customer in customers
            join country in countries on customer.CountryID equals country.CountryID
            where customer.Age > 21 &&
                  country.Name == "United Kingdom"
            select new
                       {
                           CustomerName = customer.Name,
                           CountryName = country.Name
                       };

MyRepeater.DataSource = query.ToArray();
MyRepeater.DataBind();

As you can see, I'm using CustomerName from one type of object, and CountryName from another type, and joining these together into a new anonymous type.

After this, in my HTML/ASCX I can use a repeater like this:

<asp:Repeater ID="MyRepeater" runat="server">
    <ItemTemplate>
        <p>
            <%# Eval("CustomerName") %>
            lives in
            <%# Eval("CountryName") %>
        </p>
    </ItemTemplate>
</asp:Repeater>

When you think about it, this actually makes sense. Anonymous types of course are real types - it's just that the compiler generates the type for me, so I don't have to.

Comments

9/1/2010 3:46:25 AM #

wow gold

ok ,it good!!

wow gold People's Republic of China | Reply

9/2/2010 9:01:47 AM #

nikon d95

Hi admin ! i like ur blog very amazing but why didnt you upgrade to newer version ? http://gadgetax.com/category/hp http://gadgetax.com/category/lg http://gadgetax.com/category/asus        

nikon d95 United States | Reply

Add comment




  Country flag

Visual verification


biuquote
  • Comment
  • Preview
Loading