Dynamic data get current row data in field template

345 Views Asked by At

I have a dynamic data website which has a custom field template,

CustomFieldTemplate_Edit.ascx

that will be used inside

ListDetails.aspx

for some pages. I have set it up where I need it to using the UIHint attribute and I want to implement some custom functionality. For this I need a way to get the data of the current row that contains my CustomFieldTemplate. How can I do this ?

public partial class CustomFieldTemplate_Edit : System.Web.DynamicData.FieldTemplateUserControl
{
    protected void Page_PreRender(object sender, EventArgs e)
    {
        //Need to get current row data, or at least the primary key here
    }
}

I noticed that FieldTemplateUserControl has a Row property but I don't know how to use it. When I try to access it I get this error:

"Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control."

1

There are 1 best solutions below

0
Adrian Buzea On

I have found a solution here. The answer is the Row property of the FieldTemplateUserControl, but you have to access it in the OnDataBinding event of the FieldTemplate.

After you get the Row, you can get the entities from it using these extension methods(taken from the link above) and it all works like a charm.

public static class EntityDataSourceExtensions
{
    public static TEntity GetEntityAs<TEntity>(this 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;
    }


    public static Object GetEntity(this object dataItem)
    {
        var td = dataItem as ICustomTypeDescriptor;


        if (td != null)
            return td.GetPropertyOwner(null);


        return null;
    }
}