views:

131

answers:

1

I have a repeater control, and I want to put an unknown number of <asp:Hyperlink>s into the template, for example if you start with this:

<asp:Repeater runat="server" ID="PetsRepeater">
 <ItemTemplate> 
  <%#DataBinder.Eval(Container.DataItem, "Owner")%>
  <%#this.ListPets(Container.DataItem)%>
    </ItemTemplate> 
</asp:Repeater>   

and in code behind:

public partial class test1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            PetOwner p = new PetOwner() {
                Owner = "Jimmy",
                PetNames = new List<String>() { "Nemo", "Dory" }
            };
            List<PetOwner> PetOwners = new List<PetOwner>() { p };
            PetsRepeater.DataSource = PetOwners;
            PetsRepeater.DataBind();
        }        
    }
    protected String ListPets(Object PetOwner)
    {
        StringBuilder sb = new StringBuilder();
        foreach (String Name in ((PetOwner)PetOwner).PetNames)
        {
            if (sb.Length > 0) sb.Append(", ");
            sb.Append(Name);                        
        }
        return sb.ToString();
    }
}
class PetOwner
{
    public String Owner;
    public List<String> PetNames;
}

Now suppose instead of having the string "Nemo, Dory" in my repeater, I want something like this:

<asp:HyperLink runat=server Text="Nemo" NavigateUrl="Pet.aspx?Name=Nemo" />, 
<asp:HyperLink runat=server Text="Dory" NavigateUrl="Pet.aspx?Name=Dory" />

How can I do that? I tried putting a foreach inline in the aspx page, but I get the error Invalid expression term 'foreach'.

+1  A: 

If you need to have an asp:Hyperlink control, and not just a simple tag, you should use a nested repeater. http://msdn.microsoft.com/en-us/library/aa478959.aspx

mamoo
Yes! So easy once you know about it. I had even thought of putting another repeater in but couldn't work out how to bind it. "Nested reperater" are the magic words...
Colin Pickard