开发者

Binding data to a GridView from a Object with child objects containing relevant fields

I have a List of complex objects containing other objects within that I give as the data source to a gridview.(currently I'm using BoundFields for the columns). I need to bin开发者_Python百科d data to the columns from the objects within at run time. How can this be done?


Use a LINQ projection to flatten (denormalise) the entity graph. You can either create a new ViewModel type class, or alternatively bind to an anonymous class, something like this:

var viewList = (
   from entity in entityList
       select new
       {
           Field1 = entity.Field1,
           Field2 = entity.Relation.AnotherField,
           Field3 = entity.Field3 + entity.Relation.YetAnotherField
       }).ToList();
myGridView.DataSource = viewList;
myGridView.DataBind();

Use Field1, Field2 on the GridView properties for the data bindings.

Edit

The above projection, in Lambda syntax:

var viewList = entityList
    .Select(entity => new
       {
           Field1 = entity.Field1,
           Field2 = entity.Relation.AnotherField,
           Field3 = entity.Field3 + entity.Relation.YetAnotherField
       })
   .ToList();


You could also do something like the following:

        <asp:GridView ID="TemplatesGrid" runat="server">
            <Columns>
                <asp:BoundField DataField="TemplateId" HeaderText="ID" />
                <asp:BoundField DataField="Name" HeaderText="Template Name" />
                <asp:TemplateField HeaderText="Author">
                    <ItemTemplate>
                        <%# Eval("AppUser.FullName") %>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

Where AppUser is an object contained within a Template.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜