My contemplations and diurnal novelties are publicized here


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:

  1. 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?
  2. 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)

Source:- http://aspadvice.com/blogs/joteke/archive/2008/08/24/Is-_2200_Databinding-methods-such-as-Eval_280029002C00_-XPath_280029002C00_-and-Bind_28002900_-can-only-be-used-in-the-context-of-a-databound-control_2E002200_-causing-you-grief_3F00_.aspx

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: