ASP.NET using Bind/Eval in .aspx in If statement

Funky picture Funky · Apr 8, 2011 · Viewed 70k times · Source

in my .aspx I'm looking to add in an If statement based on a value coming from the bind. I have tried the following:

<% if(bool.Parse(Eval("IsLinkable") as string)){ %>                    
        monkeys!!!!!!
        (please be aware there will be no monkeys, 
        this is only for humour purposes)
 <%} %>

IsLinkable is a bool coming from the Binder. I get the following error:

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

Answer

Bazzz picture Bazzz · Apr 8, 2011

You need to add your logic to the ItemDataBound event of ListView. In the aspx you cannot have an if-statement in the context of a DataBinder: <%# if() %> doesn't work.

Have a look here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound.aspx

The event will be raised for each item that will be bound to your ListView and therefore the context in the event is related to the item.

Example, see if you can adjust it to your situation:

protected void ListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        Label monkeyLabel = (Label)e.Item.FindControl("monkeyLabel");
        bool linkable = (bool)DataBinder.Eval(e.Item.DataItem, "IsLinkable");
        if (linkable)
           monkeyLabel.Text = "monkeys!!!!!! (please be aware there will be no monkeys, this is only for humour purposes)";
    }
}