Using Eval in aspx only if the property exists in the element - throws DataBinding exception

I have an aspx page that has a 5-field relay. These fields are populated with two different types of items. One element has 3 properties: "A" "B" "C", and the other has "A" "B" "C" "D" "E".

I want to use the same repeater for both, but only show the corresponding properties for each of them. When I try to use Eval according to the "D" rule with clause 1, I get an error: DataBinding: "Item1" does not contain a property with the name "D".

I tried to use the if statement, but that did not help, and when I try to use the ItemDataBound event, it also throws an exception when trying to load Item1 (without throwing when trying to load Item2 with all properties.

How can I Eval only if a property exists?

+4
source share
1 answer

To solve your problem, it is important to understand how it Evalworks under the hood.

The statement is Evalconverted to a method call DataBinder.Evalat the aspx compilation stage. This means that the expression <%# Eval("A") %>is an abridged version <%# DataBinder.Eval(Container.DataItem, "A") #>. If you follow the method execution path Eval, you will see that the exception is thrown in GetPropertyValueif the container object does not contain the property:

// get a PropertyDescriptor using case-insensitive lookup
PropertyDescriptor pd = GetPropertiesFromCache(container).Find(propName, true);
if (pd != null) {
    prop = pd.GetValue(container);
}
else {
    throw new HttpException(SR.GetString(SR.DataBinder_Prop_Not_Found, container.GetType().FullName, propName));
}

, Eval, SafeEval :

public abstract class BasePage: Page
{
    public object SafeEval(object container, string expression)
    {
        try
        {
            return DataBinder.Eval(container, expression);
        }
        catch (HttpException e)
        {
            // Write error details to minimize the harm caused by suppressed exception 
            Trace.Write("DataBinding", "Failed to process the Eval expression", e);
        }

        return "Put here whatever default value you want";
    }
}

:

<asp:Label runat="server" Text='<%# SafeEval(Container.DataItem, "A")  %>'></asp:Label>

, , , /. , ASP.NET Eval.

+5

All Articles