views:

1202

answers:

3

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

+3  A: 

Try casting Eval("HtmlEncodedRecipients") to a List and calling .ToArray() on it.

Joel Coehoorn
A dirty hack; I like it :)
Janie
Thanks Joel. I had tried one or the other, but not both at the same time.The following works for me. Not exactly elegant, but it works.<asp:Label ID="RecipientsLabel" runat="server" Text='<%# String.Join("; ", ((System.Collections.Generic.List<string>)Eval("HtmlEncodedRecipients")).ToArray()) %>'></asp:Label>
Korey
+3  A: 

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
Spencer Ruport
+4  A: 

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>)
    {
        ...
Dave
he wants a string, not a string[] as the result, but otherwise this is what I was saying. won't it figure it out for you if your parameter is List<string>?
Max Schmeling
That's nicer looking, and what I ended up using. I did have to make the method public. I thought the code-behind would be a local reference. It is also a string, not a string[].
Korey