Friday 15 January 2010

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

If you are using controls which are bound in a cascading parent-child relationship, you might see the error:

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

I kept getting this, but then after reading this tutorial, I realised that I had been sorting a GridView in my Page_Load event, regardless of whether the page request was a PostBack or not.

This was causing the databinding events to get borked up, and hence the error. So I added a simple IF statement around the sorting command to only do so if the page request was not a postback. Et Voila! Success!

Lesson: If you see the above error, check that you are not attempting to bind to a dependent dropdown list a value from its container’s data context when the latter was not bound to the container.

In English: check where in the page lifecycle your binding/sorting takes place otherwise you will unhook your controls from their binding and break your code.

0 comments: