如何将自定义对象的数据表绑定到GridView [英] How to bind DataTable of custom objects to GridView
问题描述
我有一个包含由ID链接的其他两个自定义对象列表的列表。本质上,我有一个具有许多属性的 CPDActivity对象和一个具有多个属性的 CPDActivityExtended对象。然后,我有一个 CPDActivityComplete对象,其中包含每个其他对象。这些完整的对象将添加到填充DataTable的列表中。
I have a list comprising of two other lists of custom objects that are linked by an Id. Essentially I have an 'CPDActivity' object that has many properties and an 'CPDActivityExtended' object with several more. I then have a 'CPDActivityComplete' object that contains one each of the other objects. These complete objects get added to a list which is what populates a DataTable.
我需要能够将此DataTable绑定到GridView并显示的属性值CPDActivityComplete的两个子对象。例如, A列下的CPDActivityComplete.CPDActivity.A。
I need to be able to bind this DataTable to a GridView and display the values of the properties of the CPDActivityComplete's two child objects. For example CPDActivityComplete.CPDActivity.A under an 'A' column.
这是我要执行的操作的基本图片:
Here is a basic picture of what I'm trying to do:
可视化的自定义对象列表:
The list of custom objects visualised:
到目前为止我已经尝试过:
What I have tried so far:
使用实体框架& LINQ和我已将GridView绑定到生成的数据表:
The DataTables are populated using Entity Framework & LINQ and I have bound the GridView to the resulting DataTable:
DataTable dt = getCPDData.ToDataTable<CPDActivityComplete>(cpdActivityCompleteList);
cpd_gv_activities.DataSource = dt;
cpd_gv_activities.DataBind();
我有一个简单的GridView可以进行测试:
I have a simple GridView to test things out:
<asp:GridView ID="cpd_gv_activities" runat="server" AutoGenerateColumns="false" AllowPaging="True" PageSize="15">
<Columns>
<asp:TemplateField HeaderText="Full Name">
<ItemStyle CssClass="fixedcell"></ItemStyle>
<ItemTemplate>
<asp:Label ID="vd_gv_lbl_FullName" runat="server" Text='<%# Bind("CPDActivity.A") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
但这会导致错误:
DataBinding: 'System.String' does not contain a property with the name 'A'.
如何将label.text绑定到CPDActivityExtended.CPDActivity.A属性?
How do I bind the label.text to CPDActivityExtended.CPDActivity.A property?
推荐答案
切换到强类型GridView。然后,您可以轻松访问所有属性和类型安全性。
Switch to a strongly typed GridView. Then you have easy access to all the properties and type-safety.
因此,首先将 ItemType
添加到GridView中。
So first add the ItemType
to the GridView
<asp:GridView ID="cpd_gv_activities" runat="server" ItemType="YourNameSpace.CPDActivityComplete">
现在您可以在GridView中使用 Item
和访问属性
Now you can use Item
in the GridView and access properties
<asp:Label ID="vd_gv_lbl_FullName" runat="server" Text='<%# Item.A %>'></asp:Label>
最后,不要转换为DataTable(首先不需要),而是绑定
And last, don't convert to a DataTable (was not needed in the first place) but bind the List with the class directly.
cpd_gv_activities.DataSource = cpdActivityCompleteList;
cpd_gv_activities.DataBind();
这篇关于如何将自定义对象的数据表绑定到GridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!