C# GridView 绑定了嵌套类的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1130351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:54:47  来源:igfitidea点击:

GridView bound with Properties of nested class

c#asp.netgridviewobjectdatasource

提问by Ant Swift

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:

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

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

“在所选数据源上找不到名为“NestedClass.Name”的字段或属性。”

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

GridView 绑定到一个 ObjectDataSource,而 ObjectDataSource 绑定到一个完全填充的 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; }
}

采纳答案by Evan

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

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

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

必须在 itemtemplate 中使用 DataBinder.Eval 来访问嵌套属性,而不是将其分配给 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:

或者,您可以创建一个自定义类,该类继承 BoundField 并覆盖 GetValue 以使用 DataBinder.Eval,如本博客文章中所述:

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

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

回答by Sjoerd

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

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