使用嵌套类的属性绑定GridView

35

我有一个类似于下面列出的对象映射。当我尝试绑定GridView中NestedClass的属性时,会出现以下错误:

"未在所选数据源上找到名称为'NestedClass.Name'的字段或属性。"

GridView绑定到ObjectDataSource,而ObjectDataSource绑定到完全填充的BoundClass实例。

有没有任何解决方法?

示例类:

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

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

列名称'NestedClass.Name'在检索数据时不存在。 - waqasahmed
2个回答

55

在BoundField列中,只能显示实例的直接属性。

如果要访问嵌套属性,必须使用DataBinder.Eval在itemtemplate中进行访问,而不是将其分配给boundfield。

示例:

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

你可以创建一个自定义类,继承BoundField并重写GetValue方法,使用DataBinder.Eval来实现,详见这篇博客文章:

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


8
用于损坏链接的时光机:http://web.archive.org/web/20120121123301/http://iridescence.no/post/FixingBoundFieldSupportforCompositeObjects.aspx - user423430

10

BoundField上的这个扩展调用了DataBinder.Eval(),它支持嵌套属性:

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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接