Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
like image 839
Funky Avatar asked Apr 08 '11 14:04

Funky


People also ask

What is difference between eval and bind in asp net?

The main difference between eval and bind is eval is read only, we can't change on database thing eval . While using bind we can appply some change to the database. Show activity on this post. The main difference between eval and bind is eval is read only, we can't change on database thing eval.

What is eval in ASPX?

Eval function is used to bind data to control inside a DataBound control, but it cannot update the values back to the database. Bind function can be used to bind data to control inside a DataBound control and also it can update the values back to the database.

What is Databinder eval?

Evaluates data-binding expressions at run time. Eval(Object, String, String) Evaluates data-binding expressions at run time and formats the result as a string.


2 Answers

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)";
    }
}
like image 78
Bazzz Avatar answered Sep 20 '22 19:09

Bazzz


I'm pretty sure you can do something like the following

(Note I don't have a compiler handy to test the exact syntax)

text = '<%# string.Format("{0}", (bool)Eval("IsLinkable") ? "Monkeys!" : string.Empty) %>'

Yes this is c# and your using vb.net, so you'll need to use vb syntax for a ternary operator.

Edit - was able to throw into into a simple data bind situation, worked like a charm.

like image 25
asawyer Avatar answered Sep 22 '22 19:09

asawyer