System.InvalidOperationException – Eval(), XPath(), or Bind()

by Yugolancer


Posted on Thursday, February 4, 2016



If you get the following error you are about to get the solution either :)

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

Cause:

Usually it happens when you directly call say an Eval() function in the code-behind.

For example, you may have a GridView control with a label inside of the Template column:

<asp: id=" lblDescription " runat=" server " text="< %# Eval('Description') % >"></asp:>

 

Then for some reason you decide to move that to the code-behind AS IS so you say:


Dim lblDescription As Label = CType(e.Item.FindControl("lblDescription"), Label)
lblDescription.Text = Eval("Description").ToString()

Your project will compile but as soon as you try to open the certain Page, an exception ‘System.InvalidOperationException’ will be thrown.

Solution:

Just replace Eval() with DataBinder.Eval() making your code to looks like this:


Dim lblDescription As Label = CType(e.Item.FindControl("lblDescription"), Label)
lblDescription.Text = DataBinder.Eval(dataItem.DataItem, "Description").ToString()

Voila! Your problem has been solved.


Copyright © ASPNETer 2006 - 2016