Is "Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control." causing you grief?
If you seem to get "Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control." in a case where it doesn't seem to make any sense, my first questions are:
- Are you using <%#Eval("field")%> expression to bind the control? If you change that to <%#DataBinder.Eval(Container.DataItem,"field")%>, does that seem to fix the error?
- Are you databinding the control perhaps bit early, so that it is not possibly in the Controls collection yet?
There is a difference between <%#Eval%> and <%#DataBinder.Eval%> under the covers, even though documentation states that using Eval (TemplateControl.Eval to be exact) actually calls DataBinder.Eval - and their task is to do exactly the same job. Yes it does, but using just Eval means that ASP.NET itself resolves the object to which databinding happens. It does it internally with a stack which gets items added when Control.DataBind() is called, but the trick is that this happens only if Page property of the control is non-null at the point. So, if the Page-managed stack isn't up to date, and you get to the point when dataitem needs to be resolved - with Page.GetDataItem() method, you get the exception with previous message. The reason why DataBinder.Eval works, is that you provide it the target object manually, so ASP.NET doesn't need to do any resolving on its own.
This is causing grief most often in cases when you databind a control directly in its own constructor for example, and you use Eval. Use DataBinder.Eval instead or recheck is the control working as you expect it to work e.g make sure it is in the Controls collection properly before you databind it (that's useful also from state management viewpoint as viewstate tracking starts after control is added to the Controls collection)