现在的位置: 首页 > 综合 > 正文

当使用EntityDataSource作为GridView的数据源时,在RowDataBound事件处理方法中得到对应当前行的实体对象

2011年12月29日 ⁄ 综合 ⁄ 共 497字 ⁄ 字号 评论关闭

方法来自这篇博文:

EntityDataSource: To wrap or not to wrap

首先,创建以下方法:

static  class EntityDataSourceExtensions
{
    public static TEntity GetItemObject<TEntity>(object dataItem)
        where TEntity : class
    {
        var entity = dataItem as TEntity;
        if (entity != null)
        {
            return entity;
        }
        var td = dataItem as ICustomTypeDescriptor;
        if (td != null)
        {
            return (TEntity)td.GetPropertyOwner(null);
        }
        return null;
    }
}

 

以下代码演示如何使用:

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
   var entity = EntityDataSourceExtensions.GetItemObject<Product>(e.Row.DataItem);
   //...
}

抱歉!评论已关闭.