Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eval with declarative data bound ASP.NET

I have been trying to use declarative data bound ASP.NET, and struggling with the "magic" that goes on behind the scenes.

How do I do get this to work in ASP.Net 2.0. This is inside a data bound FormView control.

<asp:Label ID="RecipientsLabel" runat="server" 
    Text='<%# String.Join("; ", Eval("HtmlEncodedRecipients")) %>'>
</asp:Label>

Note: HtmlEncodedRecipients is a List<string> property.

I get this error:

The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments

like image 210
Korey Avatar asked Dec 23 '22 10:12

Korey


2 Answers

I've found life is a lot easier if you just cast the DataItem to the type you're expecting. This makes intellisense kick in so you can see what's going on.

((MyObject)Container.DataItem).HtmlEncodedRecipients
like image 100
Spencer Ruport Avatar answered Jan 02 '23 23:01

Spencer Ruport


If it's a List then this is what you want:

String.Join("; ", ((List<string>)Eval("HtmlEncodedRecipients")).ToArray())

(The thing to remember is that if you put an Eval in a databinding string by itself, it will come up with a "nice" value to show. But if you use it in an expression, it returns type object, so you have to cast it.

That's getting a bit too gnarly to put inline, though, so do this:

Text='<%# ConvertRecipients(Eval("HtmlEncodedRecipients")) %>'>

and in your codebehind

string[] ConvertRecipients(object recipientObject)
{
    if(recipientObject is List<string>)
    {
        ...
like image 22
Dave Avatar answered Jan 02 '23 22:01

Dave