views:

13

answers:

1

I wonder why asp.net wont allow accessing property of contained class on Gridview's Boundfields while it work in ItemTemplates..

Class User
{
 Diagnosis diagnosis { get; set; } // Contained class
}

Class Diagnosis
{
   string DiagnosisCode { get; set; }
}


 gridview.datasource =
   new List<User>() { 
   new User() { 
   diagnosis = new Diagnosis() { DiagnosisCode = "MALARIA" }} }


 <boundfield datafield='<#% User.diagnosis.DiagnosisCode %>' />
A: 

First off, with the code as-is, you're setting the DataField property, which is the NAME of the column it should be looking at, to the VALUE of the column it should be looking at. At runtime, the GridView will attempt to bind to a field on the User named "MALARIA" (or more likely, it will be unable to determine what the "User" object is to inject the value into the markup in the first place). The BoundField also does not have to know that the object containing the property it's looking for is of type User; it will attempt a simple reflective GetProperty() call using the name of the column you specify; if it fails, binding of that column fails.

With these corrected, you'll still find that BoundField will not reflectively recurse through a compound member identifier like "diagnosis.DiagnosisCode" on its own. The solution is to implement ICustomTypeDescriptor or ITypedList on Diagnosis, each of which exposes methods that BoundField will use to help it recurse through the compound identifier.

KeithS