[英]Databinding a list to a GridView. GridView can't find my property!
Given: 鉴于:
I have a class: 我有一堂课:
class MyObject
{
public string Field1;
public string Field2;
}
and the following code: 和以下代码:
var list = SomeFunction(); // returns a valid List<MyObject>
gvMyList.DataSource = list;
gvMyList.DataBind(); // THIS THROWS AN EXCEPTION
And a GridView control in an aspx page: 在aspx页面中还有一个GridView控件:
<asp:GridView ID="gvMyList" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="Field 1">
<ItemTemplate>
<asp:Label ID="lblCourse" runat="server" Text='<%# Eval("Field1") + " " + Eval("Field2") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Problem: 问题:
So I know that if something implements IEnumerable
then it can be passed to the DataSource
property. 所以我知道,如果某些实现
IEnumerable
则可以将其传递给DataSource
属性。 As far as I know, if you pass DataSource
a List then I should have access to the MyObject
's properties by using Eval("Field1")
or Eval("Field2")
. 据我所知,如果您向
DataSource
传递一个列表,那么我应该可以使用Eval("Field1")
或Eval("Field2")
来访问MyObject
的属性。 Thats not the case here. 事实并非如此。 Instead I get an exception thrown:
相反,我抛出了一个异常:
DataBinding: 'MyObject' does not contain a property with the name 'Field1'.
Your class contains Fields , not Properties ; 您的课程包含字段 ,而不是属性 ; You have to define Properties this way :
您必须通过以下方式定义属性:
class MyObject
{
public string Field1 { get; set; }
public string Field2 { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.