GridView bound with Properties of nested class
Asked Answered
O

2

35

I have an object map similar to what's listed below. When I try to bind the properties of NestedClass in a GridView I get the error:

"A field or property with the name 'NestedClass.Name' was not found on the selected data source."

The GridView is bound to an ObjectDataSource and the ObjectDataSource is bound to a fully populated instance of BoundClass.

Is there any way around this?

Sample classes:

public class BoundClass
{
    public string Name { get; set; }
    public NestedClass NestedClass { get; set; }
}

public class NestedClass
{
    public string Name { get; set; }
}
Ormolu answered 15/7, 2009 at 9:28 Comment(1)
The column name 'NestedClass.Name' does not exist from the data it is retriveing it from.Locke
D
55

Only immediate properties of an instance can be displayed in a BoundField column.

One must instead use DataBinder.Eval in an itemtemplate to access the nested property instead of assigning it to a boundfield.

Example:

<asp:TemplateField>
    <itemtemplate>
        <p><%#DataBinder.Eval(Container.DataItem, "NestedClass.Name")%></p>
    </itemtemplate>
</asp:TemplateField>

Alternatively, you can create a custom class which inherits BoundField and overrides GetValue to use DataBinder.Eval, as described in this blog post:

http://web.archive.org/web/20120121123301/http://iridescence.no/post/FixingBoundFieldSupportforCompositeObjects.aspx

Dominate answered 28/7, 2009 at 16:5 Comment(1)
wayback machine for broken link: web.archive.org/web/20120121123301/http://iridescence.no/post/…Midge
D
10

This extension on BoundField calls DataBinder.Eval(), which does support nested properties:

public class BetterBoundField : BoundField
{
    protected override object GetValue(Control controlContainer)
    {
        if (DataField.Contains("."))
        {
            var component = DataBinder.GetDataItem(controlContainer);
            return DataBinder.Eval(component, DataField);
        }
        return base.GetValue(controlContainer);
    }
}
Duelist answered 9/11, 2011 at 9:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.