【问题标题】:DataBind Generic "Dynamic" Class to GridViewDataBind 通用“动态”类到 GridView
【发布时间】:2012-07-04 16:07:47
【问题描述】:

如何将 GridView 数据绑定到如下类?

public class GenericEntity
{
    private readonly Dictionary<string, object> properties = new Dictionary<string, object>();
    public object this[string propertyName]
    {
        get
        {
            if (properties.ContainsKey(propertyName))
                return properties[propertyName];
            else
                return null;
        }
        set
        {
            if (value == null)
                properties.Remove(propertyName);
            else
                properties[propertyName] = value;
        }
    }
}

这个类可能有任意数量的属性,并且无法在编译时知道它们中的任何一个,只能在运行时知道,这是因为属性直接映射到来自 BD 的结果集的列。

如何将此 GenericEntity 类的列表数据绑定到 GridView?我尝试了以下方法,但出现“类不包含具有名称的属性...”的异常

var newColumn = new BoundField();
newColumn.HeaderText = resultsetDescription.FieldDisplayName;
newColumn.DataField = resultsetDescription.FieldName;
myGridView.Columns.Add(newColumn);

myGridView.DataSource = GetListOfGenericEntities(args);
myGridView.DataBind();

编辑:

我已经实现了SO answer 中提到的方法,但它仍然抛出属性异常......

【问题讨论】:

    标签: c# asp.net data-binding gridview


    【解决方案1】:

    如果您只需要将此通用列表绑定到GridView,我会将其转换为DataTable,然后将DataTable 绑定到GridView。你检查过Anonymous Types吗?您可以创建一个匿名类型的通用列表,然后将其绑定到您的GridView

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-03
      • 2011-06-15
      • 2011-10-20
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      相关资源
      最近更新 更多