当使用EntityDataSource作为GridView的数据源时,在RowDataBound事件处理方法中得到对应当前行的实体对象
方法来自这篇博文:
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); //... }
理解的越多,需要记忆的就越少