ASP.NET Custom Control - DataBinding

2019-07-26 06:10发布

问题:

I have my custom control inside of a formview. This custom control has a variety of properties one of which is Value which I am trying to databind.

Using Container.DataItem I can databind my control, and everything works:

<fc:Literal runat="server" ID="readState" Label="State:" Value='<%# Container.DataItem("ActivityState") %>' />

Then when I try to databind using Eval, then it doesn't:

<fc:Literal runat="server" ID="readState" Label="State:" Value='<%# Eval("ActivityState") %>' />

Gives the Error:

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

Everything workds great with Container.DataItem, so my question is: Why does Container.DataItem work and Eval doesn't?

回答1:

Eval can only be used with templated controls.

The Eval method evaluates late-bound data expressions in the templates of data-bound controls such as the GridView, DetailsView, and FormView controls. At run time, the Eval method calls the Eval(Object, String) method of the DataBinder object, referencing the current data item of the naming container. The naming container is generally the smallest part of the data-bound control that contains a whole record, such as a row in a GridView control. You can therefore use the Eval method only for binding inside templates of a data-bound control.



回答2:

You need to implement/extend one of the server controls following to get databinding expression syntax:

Templated Databound Control: Couple of articles: http://msdn.microsoft.com/en-us/library/aa478964.aspx http://msdn.microsoft.com/en-us/library/aa479322.aspx

CompositeDataboundControl: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.compositedataboundcontrol.aspx

DatBoundControl: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.databoundcontrol.aspx