DataKeyNames in databound controls must be a property?
I use a ListView along with an ObjectDataSource tied to a business object. This object is defined as 开发者_Go百科follows:
public class Employee
{
public int Id;
public string Name;
}
When I try setting the DataKeyNames property of the ListView to Id, ASP.net blows up and says:
DataBinding: 'Employee' does not contain a property with the name 'Id'.
However, when I change the object to that:
public class Employee
{
public int Id {get; set;}
public string Name;
}
It works!!!
I couldn't find any documentation about this behavior. Why is it not accepting a simple variable for DataKeyNames and instead it insists on a property?
There's not really a long explanation for this one, you've already found it. ASP.Net can bind to properties and not public variables. This is probably tied to the way the MSIL is generated. When compiled, a property is generated as a method (and binding allows you to bind to methods and properties) while public variables are not.
Unfortunately a quick search didn't uncover the reasoning beyond my own guess above, but here is MS saying "properties, expressions, methods" also: http://support.microsoft.com/kb/307860
精彩评论