views:

288

answers:

1

I am using databinding to iterate through a recordset returned from the database, and one of those recordsets is a comma separated list of items - I'm trying to use a second repeater to display each of those items as a hyperlink. So far this is the code that I have:

<asp:Repeater ID="myRepeater" runat="server" DataSource='<%# DataBinder.Eval(Container.DataItem, "SomeList").ToString().Trim(',') %>'>
<ItemTemplate>
    <a href='http://somesite/downloadattachment.aspx?itemid=&lt;%# Container.ItemIndex %>'><%# Container.DataItem %></a>
</ItemTemplate>
</asp:Repeater>

The trouble is that so far there are 3 reasons why this doesnt work:

  • I get a server tag is not well formed error unless I remove the runat="server" - why is this? (And why does it work without the runat="server"?)
  • Container.DataItem Evaluates to an instance of System.Data.DataRowView - how do I get the current piece of the string that I split?
  • More importantly, this only seems to print out 1 Container.DataItem, even when I know there is a comma in the string I've given it - any ideas?
+1  A: 

Instead of Eval(), for non-trivial scenarios I generally cast Container.DataItem to the type I want, and then act on it from there in a type-safe way.

The "not well formed" error is caused by the single-quotes around the parameter to Trim(). If you use single quotes on the outside of your attribute definition, you can't use them inside it. In cases like yours where a databinding definition has a lot of code in it, I often create a helper method (either inside a script runat=server for for MVC views and other inline-code-friendly cases, or in code-behind for traditional web forms apps) which handles the code I want to run. By refactoring into a method, it clarifies the HTML and sidesteps the lame single/double-quote restrictions.

Regardless of where you put the code, In your case, you want to:

  1. cast Container.DataItem to DataRowView
  2. extract the SomeList column value using the [] operator
  3. call String.Split() on that string to turn your CSV string it into an array of strings
  4. use that as a data source of your inner repeater

The code should look something like this:

<asp:Repeater ID="myRepeater" runat="server" 
    DataSource='<%# ((System.Data.DataRowView)Container.DataItem)["SomeList"].ToString().Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries)%>'>
  <ItemTemplate>
    <a href='http://somesite/downloadattachment.aspx?itemid=&lt;%# Container.ItemIndex %>'>
      <%# Container.DataItem %>
    </a>
  </ItemTemplate>
</asp:Repeater>
Justin Grant
Kragen