Jim Rogers

Lives in Baton Rouge, LA, with two dogs, one cat, and one lovely wife. I'm a lead developer for GCR Incorporated.

Katrin and Jim

Month List

ASP Databinding Issues

by jim Oct 05, 2010 1:48 PM

There are a number of solutions out there for the error “Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.”

I fought with my bug for a while because the problem isn’t with an explicit call to any of these methods; it was with a ControlParameter on my ObjectDataSource.

<asp:DropDownList ID="cboBatchList" runat="server" 
    AppendDataBoundItems="true" 
    DataSourceID="srcBatchList" 
    DataTextField="Display" 
    DataValueField="ID" 
    SelectedValue='<%# Eval("BatchID") %>'>
    <asp:ListItem Text="Select a batch" Value="" />
</asp:DropDownList>                                                    
<asp:ObjectDataSource ID="srcBatchList" runat="server" 
    EnableViewState="false"
    OldValuesParameterFormatString="original_{0}" 
    SelectMethod="Select" 
    OnObjectCreating="TextListDataSource_ObjectCreating"
    TypeName="MyProject.Service.Reference.TextListService">
    <SelectParameters>
        <asp:Parameter Name="listName" DefaultValue="Batch" Type="String" />
        <asp:ControlParameter ControlID="frmLine" DefaultValue="" 
            Name="selectedID" PropertyName="DataKey['BatchID']" Type="UInt32" />
    </SelectParameters>
</asp:ObjectDataSource>

The Eval() in the DropDownList is fine (even a Bind will work,) but the control parameter reaches up into the containing form to get a property, and this fails. Presumably this uses the same methods internally that a call to Eval does, and therefore gives the same error message – which is a bit confusing in this context.

The fix is to set EnableViewState=”true” on the ObjectDataSource, which will then cache the list and not attempt to re-evaluate the control parameter on postbacks.

Tags:

Code