Thursday, October 23, 2008

Bind an Entity to a Row.DataItem

It is innevitable these days that when building a website you will need to use the GridView control within Visual Studio. In my early days of programming, I used to simply use Row[some int] to get row information on the Editing, Deleting and ItemBound events (Bad). Now that I am using the entity framework, I needed a way to be able to strongly bind an entity to a Row that I selected within the Gridview. Easy!

 public static class EntityDataSourceHelper where TEntity : class
    {
public static TEntity GetDataItemEntity(object dataItem)
        {
            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;
        }
}

Calling this is simple....

      protected void Gridview2_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex > -1)
            {
                PersonEntity person=        EntityDataSourceHelper< PersonEntity  >. GetDataItemEntity(e.Row.DataItem);

            }
        }

This saves you from a couple of issues :

1. Referencing null column
2. Extra code to cater for null checks on rows
3. Extra code for casting etc

No comments: