‘myObject’不包含名称为’ID’的属性(不是拼写错误)

我正在构建一个ASP.NET C#网站,我有一个下拉列表,我绑定到我创建的对象列表。 绑定下拉列表的代码如下所示:

protected void PopulateDropdownWithObjects(DropDownList dropdownlist, List() myObjects) { dropdownlist.DataValueField = "ID"; dropdownlist.DataTextField = "Name"; dropdownlist.DataSource = myObjects; // my code fails here dropdownlist.DataBind(); } 

但是,当它遇到方法中的第3行时,会抛出exception:

 DataBinding: 'myObject' does not contain a property with the name 'ID'. 

但是,我可以在调试时清楚地看到myObject.ID值:我可以在立即窗口中访问它,它是公共的,它不是空的,我拼写正确并且使用正确的大小写:

 public class myObject { public int ID; // see? "ID" is right here! public string Name; public myObject( int id, string name ) { this.ID = id; this.Name = name; } } 

还有什么可以导致此错误吗?

您的代码无效,因为ID字段 ,而不是属性

如果您更改了类,如下所示,代码将按预期工作:

 public class myObject { public int ID // this is now a property { get; set; } public string Name { get; set; } public myObject( int id, string name ) { this.ID = id; this.Name = name; } }