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

人走茶凉 提交于 2020-01-04 14:11:29

问题


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 bind data to the columns from the objects within at run time. How can this be done?


回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/3264336/binding-data-to-a-gridview-from-a-object-with-child-objects-containing-relevant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!